美文网首页
200行python实现2048

200行python实现2048

作者: Louis_Duan | 来源:发表于2018-09-12 17:01 被阅读0次
    import curses #控制字符界面
    from random import  randrange, choice
    #random.randrange([start], stop[, step]),
    # 从指定范围内,按指定基数递增的集合中 获取一个随机数。
    #random.choice从序列中获取一个随机元素。
    from collections import  defaultdict#默认字典
    
    
    
    letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']#ord函数以一个字符为参数,返回对应的ASCII数值,或者Unicode数值
    actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
    actions_dict = dict(zip(letter_codes,actions*2)) #zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
    #[(W,Up),(A,Left),..(q,Exit)]-->{W:Up, A:Left,...q:Exit}
    
    #用户输入
    def get_user_action(keyboard):
        char = 'N'
        while char not in actions_dict:
            char = keyboard.getch()
        return  actions_dict[char]
    #矩阵转置
    def transpose(field):#进行一个二维列表的转换
        return [list(row) for row in zip(*field)]
    
    #矩阵逆转
    def invert(field):
        return [row[::-1] for row in field]
    
    #创建棋盘
    class GameField(object):#class:类的关键字;GameField:自定义类的标识符;object;要继承的类名(是一个更大的类,可以从这个父类中继承一些功能和特性),object是默认值。
        def __init__(self, height=4, width=4, win=2048):#__init__是超类object下的一个初始化对象数据的函数
            self.height = height    #高
            self.width = width      #宽
            self.win_value = win    #过关分数
            self.score = 0          #当前分数
            self.highscore = 0      #最高分数
            self.reset()            #棋盘重置
        #重置棋盘
        def reset(self):
            if self.score > self.highscore:
                self.highscore = self.score
            self.score = 0
            self.field = [[0 for i in range(self.width)] for j in range(self.height)]#嵌套的列表,四行四列
            self.spawn()
            self.spawn()#在嵌套的列表里随机的生成元素
    
        def move(self,direction):#合并
            #一行向左合并
            def move_row_left(row):
                def tighten(row): #把零散的非零单元挤到一起
                    new_row = [i for i in row if i !=0]
                    new_row += [0 for i in range(len(row)-len(new_row))]
                    return new_row
                def merge(row): #对邻近元素进行合并
                    pair = False
                    new_row = []
                    for i in range(len(row)):
                        if pair:
                            new_row.append(2 * row[i])#合并
                            self.score += 2 * row[i]#记录分数
                            pair = False
                        else:
                            if i +1 < len(row) and row[i] == row[i + 1]:
                                pair = True
                                new_row.append(0)
                            else:
                                new_row.append(row[i])
                    assert  len(new_row) == len(row)
                    return  new_row
                #先挤到一块再合并再挤到一起
                return tighten(merge(tighten(row)))
            #通过对矩阵进行转置和逆转,可以直接从左移得到其余三个方向的移动操作
            moves = {}
            moves['Left'] = lambda field:                   \
                [move_row_left(row) for row in field]
            moves['Right'] = lambda field:                   \
                invert(moves['Left'](invert(field)))
            moves['Up'] = lambda field:                 \
                transpose(moves['Left'](transpose(field)))
            moves['Down'] = lambda field:                   \
                transpose(moves['Right'](transpose(field)))
    
            if direction in  moves:
                if self.move_is_possible(direction):
                    self.field = moves[direction](self.field)
                    self.spawn()
                    return True
                else:
                    return False
        #判断输赢
        def is_win(self):
            return any(any(i >= self.win_value for i in row) for row in self.field)
    
        def is_gameover(self):
            return not any(self.move_is_possible(move) for move in actions)
    
        #绘制游戏界面
        def draw(self,screen):
            help_string1 = '(W)Up (S)Down (A)Left (D)Right'
            help_string2 = '      (R)Restart (Q)Exit'
            gameover_string = '            GAME OVER'
            win_string = '                YOU WIN!'
            def cast(string):
                screen.addstr(string + '\n')#调用方法把字符串打印到屏幕
    
            #绘制水平分割线
            def draw_hor_separator():
                line = '+' + ('+------' * self.width + '+')[1:]
                separator = defaultdict(lambda: line)
                if not hasattr(draw_hor_separator, 'counter'):
                    draw_hor_separator.counter = 0
                cast(separator[draw_hor_separator.counter])
                draw_hor_separator.counter += 1
            def draw_row(row):
                cast(''.join('|{: ^5} '.format(num) if num > 0 else '|      ' for num in row)+ '|')
    
            screen.clear()
            cast('SCORE: ' + str(self.score))#绘制当前分数和最高分
            if 0 != self.highscore:
                cast('HIGHSCORE:' + str(self.highscore))
            for row in self.field:
                draw_hor_separator()#绘制分割线
                draw_row(row)#绘制行
            draw_hor_separator()#绘制底边的线
            if self.is_win():
                cast(win_string)
            else:
                if self.is_gameover():
                    cast(gameover_string)
                else:
                    cast(help_string1)
            cast(help_string2)
    
        #棋盘操作
        #随机生成一个2或者4
        def spawn(self):
            new_element = 4 if randrange(100) > 89 else 2#9:1的比例生成4和2
            (i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] ==0])#通过choice选择一个未被占领的位置
            self.field[i][j] = new_element
    
        #判断能否移动
        def move_is_possible(self,diretion):
                def row_is_left_movable(row):#判断是否可以向左移动
                    def change(i):
                        if row[i] == 0 and row[i + 1] !=0:
                            return True
                        if row[i] !=0 and row[i + 1] == row[i]:
                            return  True
                        return False
                    return any(change(i) for i in range(len(row) - 1))#any,只要有一个是ture结果就是ture
                check = {}
                check['Left'] = lambda field:                   \
                    any(row_is_left_movable(row) for row in field)
                check['Right'] = lambda field:                  \
                    check['Left'](invert(field))
                check['Up']     =lambda  field:                 \
                    check['Left'](transpose(field))
                check['Down'] =lambda field:                    \
                    check['Right'](transpose(field))
                if diretion in check:
                    return check[diretion](self.field)
                else:
                    return False
    #主逻辑
    def main(stdscr):#标准屏幕,curses模块
        def init():
            #重置游戏棋盘
            game_field.reset()
            return  'Game'
        def not_game(state):
            #画出 GameOver 或者 Win 的界面
            game_field.draw(stdscr)
            #读取用户输入得到的action,判断是重启游戏还是结束游戏
            action = get_user_action(stdscr)
            responses = defaultdict(lambda : state)#默认是当前状态,没有行为就会一直在当前界面循环
            #collections.defaultdict可以接受一个函数作为参数来初始化
            responses['Restart'],responses['Exit']='Init','Exit'#对应不同的行为转换到不同的状态
            return responses[action]
        def game():
            #画出当前棋盘的状态
            game_field.draw(stdscr)
            #读取用户输入得到的action
            action = get_user_action(stdscr)
            if action == 'Restart':
                return  'Init'
            if action == 'Exit':
                return  'Exit'
            if game_field.move(action):
                if game_field.is_win():
                    return 'Win'
                if game_field.is_gameover():
                    return 'Gameover'
            return 'Game'
        state_actions = {
            'Init': init,
            'Win': lambda: not_game('Win'),
            'Gameover': lambda : not_game('Gameover'),
            'Game': game
        }
        curses.use_default_colors()
    
        game_field = GameField(win=2048)
    
    
        state = 'Init'
        #状态机开始循环
        while state != 'Exit':
            state = state_actions[state]()
    curses.wrapper(main)#把stdscr对象传入main函数里,wrapper接口

    相关文章

      网友评论

          本文标题:200行python实现2048

          本文链接:https://www.haomeiwen.com/subject/spqbgftx.html