Python简单游戏练习——2048

2020.06.28

  1. 参考:
    有哪些适合新手练手的Python项目?
    Python实例浅谈之八2048游戏(字符界面)
  2. 运行环境:
    在这里插入图片描述
  3. 代码
# -*- coding: utf-8 -*-

import random

class Game2048(object):
    def __init__(self):

        print("Welcome to the 2048 game!")
        print("Input: w(up) s(down) a(left) d(right)   q(quit)")
        self.DIRECTIONS = ['w', 's', 'a', 'd']

        self.ROW = 4
        self.COL = 4
        self.matrix = []
        for row in range(self.ROW):
            # Python random模块sample、randint、shuffle、choice随机函数概念和应用:
            # https://www.cnblogs.com/dylancao/p/8202888.html
            self.matrix.append([random.choice([0,0,0,0,0,2,2,4]) for col in range(self.COL)])
        self.score = 0
    
    def PrintMatrix(self):
        for row in self.matrix:
            for e in row:
                print("\t %d" % e, end = "")
            print("\n")
        print("Total score: %-08d " % self.score, end = "")
        self.operator = input("operator: ").lower()

    def CalNextMatrix(self):
        self.next_matrix = dict()
        self.next_score = dict()

        # 按direction对齐mlist中的数字
        def align(mlist, direction): 
            new_list = [0 for e in mlist]

            if direction == 'w' or direction == 'a':
                op_list = mlist
                now_index = 0
                dindex = 1
            else:
                op_list = reversed(mlist)
                now_index = len(mlist) - 1
                dindex = -1

            for e in op_list:
                if e:
                    new_list[now_index] = e
                    now_index += dindex
            
            return new_list

        # 按direction查找mlist中相邻且相同的数字并将其相加
        def addSame(mlist, direction): 
            is_add = False
            mlen = len(mlist)

            if direction == 'w' or direction == 'a':
                ilist = list(range(mlen - 1))
                di = 1
            else:
                ilist = list(reversed(range(1, mlen)))
                di = -1
            self.next_score[direction] = 0

            for i in ilist:
                if mlist[i] and mlist[i] == mlist[i + di]:
                    self.next_score[direction] += mlist[i]
                    mlist[i] *= 2
                    mlist[i + di] = 0
                    is_add = True

            return is_add

        ############################主体部分##########################
        have_next = False
        mlists_w = []
        for direction in self.DIRECTIONS:
            # matrix是按行存储的,这里要生成按列存储的mlists
            # 转换之后'w'和'a'的操作一致,'s'和'd'的操作一致
            if direction == 'w': 
                mlists = []
                for col in range(self.COL):
                    mlist = []
                    for row in self.matrix:
                        mlist.append(row[col])
                    mlists.append(mlist)
                mlists_w = mlists[:]
            elif direction == 's':
                mlists = mlists_w[:]
            else:
                mlists = self.matrix[:]
            
            # 计算变换后的矩阵
            is_move = False
            is_add = False
            for i, mlist in enumerate(mlists):
                # Python传参传什么?
                # https://zhuanlan.zhihu.com/p/64628390
                mlists[i] = align(mlist, direction)
                is_move = is_move or (mlist != mlists[i])
                is_this_add = addSame(mlists[i], direction)
                is_add = is_add or is_this_add
                mlists[i] = align(mlists[i], direction)
            have_this_next = is_move or is_add

            # 随机加一格2
            if have_this_next:
                have_next = True

                ilist = list(range(len(mlists)))
                # Python3.x中数据随机重排基本方法 
                # https://blog.csdn.net/jerrygaoling/article/details/79897414
                random.shuffle(ilist)
                is_addnew = False 
                for i in ilist:
                    if not is_addnew:
                        zero_indices = []
                        for ei, e in enumerate(mlists[i]):
                            if not e:
                                zero_indices.append(ei)
                        if zero_indices:
                            is_addnew = True
                            zero_pos = random.choice(zero_indices)
                            mlists[i][zero_pos] = 2
                    else:
                        break
            
            # 将按列存储的mlists复原成按行存储的
            if direction == 'w' or direction == 's': 
                tmp_mlists = []
                for row in range(self.ROW):
                    mlist = []
                    for col in mlists:
                        mlist.append(col[row])
                    tmp_mlists.append(mlist)
                self.next_matrix[direction] = tmp_mlists[:]
            else:
                self.next_matrix[direction] = mlists[:]
        
        return have_next

    def Play(self):
        while self.CalNextMatrix():
            self.PrintMatrix()
            if self.operator == "q":
                break
            elif self.operator in self.DIRECTIONS:
                self.matrix = self.next_matrix[self.operator][:]
                self.score += self.next_score[self.operator]
            else:
                while self.operator not in self.DIRECTIONS + ["q"]:
                    print("Wrong Input! available operator: w(up) s(down) a(left) d(right)   q(quit)")
                    self.operator = input("operator: ").lower()
                if self.operator == "q":
                    break
        
        if self.operator == "q":
            print("Bye!")
        else:
            print("Can't continue.")
            


game = Game2048()
game.Play()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,让我们开始Python模拟登录imooc.com的练习。 首先,我们需要导入需要的库,包括requests和BeautifulSoup。requests库用于发送http请求,BeautifulSoup库用于解析html文本。 ```python import requests from bs4 import BeautifulSoup ``` 接下来,我们需要获取登录页面的html代码。我们可以使用requests库的get()方法来发送一个get请求,并将返回的html代码存储在一个变量中。 ```python login_url = 'https://www.imooc.com/' login_page = requests.get(login_url) login_soup = BeautifulSoup(login_page.text, 'html.parser') ``` 接下来,我们需要从登录页面中获取登录所需的信息,包括表单的action、method、以及需要提交的表单数据。我们可以使用BeautifulSoup库来解析html代码,并使用find()方法来查找表单元素。 ```python # 获取登录表单元素 login_form = login_soup.find('form', attrs={'id': 'signup-form'}) # 获取表单的action和method action_url = login_form['action'] method = login_form['method'] # 获取需要提交的表单数据 email = input('请输入邮箱:') password = input('请输入密码:') data = { 'email': email, 'password': password } ``` 接下来,我们可以使用requests库的post()方法来发送一个post请求,将表单数据提交到服务器。需要注意的是,我们需要将表单数据和请求头一起提交到服务器。 ```python # 构造请求头 headers = { 'Referer': login_url, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 发送post请求 response = requests.post(action_url, data=data, headers=headers) ``` 最后,我们可以判断登录是否成功,可以通过检查返回的html代码中是否包含登录成功的提示信息来判断。 ```python # 判断登录是否成功 if '个人中心' in response.text: print('登录成功!') else: print('登录失败!') ``` 完整代码如下: ```python import requests from bs4 import BeautifulSoup # 获取登录页面html代码 login_url = 'https://www.imooc.com/' login_page = requests.get(login_url) login_soup = BeautifulSoup(login_page.text, 'html.parser') # 获取登录表单元素 login_form = login_soup.find('form', attrs={'id': 'signup-form'}) # 获取表单的action和method action_url = login_form['action'] method = login_form['method'] # 获取需要提交的表单数据 email = input('请输入邮箱:') password = input('请输入密码:') data = { 'email': email, 'password': password } # 构造请求头 headers = { 'Referer': login_url, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 发送post请求 response = requests.post(action_url, data=data, headers=headers) # 判断登录是否成功 if '个人中心' in response.text: print('登录成功!') else: print('登录失败!') ``` 注意,此代码仅供学习参考。在实际应用中,请勿使用模拟登录的方式获取个人信息,以免造成不必要的风险。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值