• Python入门 —— 2048实战(字符界面和图形界面)


    2048 game (共4种实现方法)

    目录:
        .. 图形界面
                ... pygame 和 numpy
        .. 字符界面
                ... 第一种 
                        ... curses 
                        ... wxpython
                ... 第二种
                        ... 极简
     

    代码后面附有效果图。 

    图形界面

    用python的pygame库写的2048游戏

    • 程序目前在python3环境下运行,首先安装pygame库和numpy库,pip install pygamepip install numpy
    • 安装模块完成后,进入终端来到目录,执行python box.py

      box.py代码如下:

    # _*_ coding:UTF-8 _*_
    
    import numpy,sys,random,pygame
    from pygame.locals import*
    
    Size = 4                                          #4*4行列
    Block_WH = 110                                    #每个块的长度宽度
    BLock_Space = 10                                  #两个块之间的间隙
    Block_Size = Block_WH*Size+(Size+1)*BLock_Space
    Matrix = numpy.zeros([Size,Size])                 #初始化矩阵4*4的0矩阵
    Screen_Size = (Block_Size,Block_Size+110)
    Title_Rect = pygame.Rect(0,0,Block_Size,110)      #设置标题矩形的大小
    Score = 0
    
    Block_Color = {
            0:(150,150,150),
            2:(255,255,255),
            4:(255,255,128),
            8:(255,255,0),
            16:(255,220,128),
            32:(255,220,0),
            64:(255,190,0),
            128:(255,160,0),
            256:(255,130,0),
            512:(255,100,0),
            1024:(255,70,0),
            2048:(255,40,0),
            4096:(255,10,0),
    }                                                     #数块颜色
    
    #基础类
    class UpdateNew(object):
        """docstring for UpdateNew"""
        def __init__(self,matrix):
            super(UpdateNew, self).__init__()
            self.matrix = matrix
            self.score  = 0
            self.zerolist = []
    
        def combineList(self,rowlist):
            start_num = 0
            end_num = Size-rowlist.count(0)-1
            while start_num < end_num:
                if rowlist[start_num] == rowlist[start_num+1]:
                    rowlist[start_num] *= 2
                    self.score += int(rowlist[start_num])                      #每次返回累加的分数
                    rowlist[start_num+1:] = rowlist[start_num+2:]
                    rowlist.append(0)
                start_num += 1
            return rowlist
    
        def removeZero(self,rowlist):
            while True:
                mid = rowlist[:]                      #拷贝一份list
                try:
                    rowlist.remove(0)
                    rowlist.append(0)
                except:
                    pass
                if rowlist == mid:
                    break;
            return self.combineList(rowlist)
    
        def toSequence(self,matrix):
            lastmatrix = matrix.copy()
            m,n = matrix.shape                                         #获得矩阵的行,列
            for i in range(m):
                newList = self.removeZero(list(matrix[i]))
                matrix[i] = newList
                for k in range(Size-1,Size-newList.count(0)-1,-1):     #添加所有有0的行号列号
                    self.zerolist.append((i,k))
            if matrix.min() == 0 and (matrix!=lastmatrix).any():       #矩阵中有最小值0且移动后的矩阵不同,才可以添加0位置处添加随机数
                GameInit.initData(Size,matrix,self.zerolist)
            return matrix
                              
    
    class LeftAction(UpdateNew):
        """docstring for LeftAction"""
        def __init__(self,matrix):
            super(LeftAction, self).__init__(matrix)
    
        def handleData(self):
            matrix = self.matrix.copy()                               #获得一份矩阵的复制
            newmatrix = self.toSequence(matrix)
            return newmatrix,self.score
    
    class RightAction(UpdateNew):
        """docstring for RightAction"""
        def __init__(self,matrix):
            super(RightAction, self).__init__(matrix)
    
        def handleData(self):
            matrix = self.matrix.copy()[:,::-1]
            newmatrix = self.toSequence(matrix)
            return newmatrix[:,::-1],self.score
    
    class UpAction(UpdateNew):
        """docstring for UpAction"""
        def __init__(self,matrix):
            super(UpAction, self).__init__(matrix)
    
        def handleData(self):
            matrix = self.matrix.copy().T
            newmatrix = self.toSequence(matrix)
            return newmatrix.T,self.score
    
    
    class DownAction(UpdateNew):
        """docstring for DownAction"""
        def __init__(self,matrix):
            super(DownAction, self).__init__(matrix)
    
        def handleData(self):
            matrix = self.matrix.copy()[::-1].T
            newmatrix = self.toSequence(matrix)
            return newmatrix.T[::-1],self.score
    
    
    class GameInit(object):
        """docstring for GameInit"""
        def __init__(self):
            super(GameInit, self).__init__()
    
        @staticmethod
        def getRandomLocal(zerolist = None):
            if zerolist == None:
                a = random.randint(0,Size-1)
                b = random.randint(0,Size-1)
            else:
                a,b = random.sample(zerolist,1)[0]
            return a,b
    
        @staticmethod
        def getNewNum():                             #随机返回2或者4
            n = random.random()
            if n > 0.8:
                n = 4
            else:
                n = 2
            return n
    
    
        @classmethod
        def initData(cls,Size,matrix = None,zerolist = None):
            if matrix is None:
                matrix = Matrix.copy()
            a,b = cls.getRandomLocal(zerolist)       #zerolist空任意返回(x,y)位置,否则返回任意一个0元素位置
            n = cls.getNewNum()
            matrix[a][b] = n
            return matrix                           #返回初始化任意位置为2或者4的矩阵
    
        @classmethod
        def drawSurface(cls,screen,matrix,score):
            pygame.draw.rect(screen,(255,255,255),Title_Rect)              #第一个参数是屏幕,第二个参数颜色,第三个参数rect大小,第四个默认参数
            font1 = pygame.font.SysFont('simsun',48)
            font2 = pygame.font.SysFont(None,32)
            screen.blit(font1.render('Score:',True,(255,127,0)),(20,25))     #font.render第一个参数是文本内容,第二个参数是否抗锯齿,第三个参数字体颜色
            screen.blit(font1.render('%s' % score,True,(255,127,0)),(170,25))
            screen.blit(font2.render('up',True,(255,127,0)),(360,20))
            screen.blit(font2.render('left  down  right',True,(255,127,0)),(300,50))
            a,b = matrix.shape
            for i in range(a):
                for j in range(b):
                    cls.drawBlock(screen,i,j,Block_Color[matrix[i][j]],matrix[i][j])
    
    
        @staticmethod
        def drawBlock(screen,row,column,color,blocknum):
            font = pygame.font.SysFont('stxingkai',80)
            w = column*Block_WH+(column+1)*BLock_Space
            h = row*Block_WH+(row+1)*BLock_Space+110
            pygame.draw.rect(screen,color,(w,h,110,110))
            if blocknum != 0:
                fw,fh = font.size(str(int(blocknum)))
                screen.blit(font.render(str(int(blocknum)),True,(0,0,0)),(w+(110-fw)/2,h+(110-fh)/2))
    
        @staticmethod
        def keyDownPressed(keyvalue,matrix):
            if keyvalue == K_LEFT:
                return LeftAction(matrix)
            elif keyvalue == K_RIGHT:
                return RightAction(matrix)
            elif keyvalue == K_UP:
                return UpAction(matrix)
            elif keyvalue == K_DOWN:
                return DownAction(matrix)
    
        @staticmethod
        def gameOver(matrix):
            testmatrix = matrix.copy()
            a,b = testmatrix.shape
            for i in range(a):
                for j in range(b-1):
                    if testmatrix[i][j] == testmatrix[i][j+1]:                    #如果每行存在相邻两个数相同,则游戏没有结束
                        print('游戏没有结束')
                        return False
            for i in range(b):
                for j in range(a-1):
                    if testmatrix[j][i] == testmatrix[j+1][i]:
                        print('游戏没有结束')
                        return False
            print('游戏结束')
            return True
    
    def main():
        pygame.init()
        screen = pygame.display.set_mode(Screen_Size,0,32)      #屏幕设置
        matrix = GameInit.initData(Size)
        currentscore = 0
        GameInit.drawSurface(screen,matrix,currentscore)
        pygame.display.update()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == pygame.KEYDOWN:
                    actionObject = GameInit.keyDownPressed(event.key,matrix)     #创建各种动作类的对象
                    matrix,score = actionObject.handleData()                     #处理数据
                    currentscore += score   
                    GameInit.drawSurface(screen,matrix,currentscore)
                    if matrix.min() != 0:
                        GameInit.gameOver(matrix)
            pygame.display.update()
    
    
    if __name__ == '__main__':
        main()
    • 最终效果图如下:

     

    字符界面

    用字符输出的2048游戏

    第一种 (来源:200 行代码实现简易版 2048 游戏"")

    - 利用curses库实现2048游戏

    • 导入curses库  pip install curses

     注意:可能会出现错误
    导入时:

     pip 安装时:

     安装不成功则点击这里,下载curses ,cmd到对应目录pip安装即可

    例:pip install crcmod-1.7-cp36-cp36m-win_amd64.whl (64位系统的python3.6版本)

     

    • 用户操作

    上W 下S 左A 右D 重置R 退出Q

    • 状态机

      处理游戏主逻辑的时候我们会用到一种十分常用的技术:状态机,或者更准确的说是有限状态机(FSM)
      你会发现 2048 游戏很容易就能分解成几种状态的转换。
      state 存储当前状态, state_actions 这个词典变量作为状态转换的规则,它的 key 是状态,value 是返回下一个状态的函数:

    • Init: init()

    Game

    • Game: game()

    Game

    Win

    GameOver

    Exit

    • Win: lambda: not_game(‘Win’)

    Init

    Exit

    • Gameover: lambda: not_game(‘Gameover’)

    Init

    Exit

    • Exit: 退出循环

      状态机会不断循环,直到达到 Exit 终结状态结束程序。

    • 代码如下:

    # -*- coding: utf-8 -*-
    
    import curses
    from random import randrange, choice
    from collections import defaultdict
    
    #Defines valid inputs to not allow for input errors
    actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
    lettercodes = [ord(ch) for ch in 'WASDRQwasdrq']
    actions_dict = dict(zip(lettercodes, actions * 2))
    
    # Character not in dictonary so it adds it to the dictionary to make it recongized
    def get_user_action(keyboard):
        char = 'N'
        while char not in actions_dict:
            char = keyboard.getch()
        return actions_dict[char]
    
    # Transpose of matrix to determine tile moveability
    def transpose(field):
        return [list(row) for row in zip(*field)]
    
    # Inversion of matrix to determine tile moveability
    def invert(field):
        return [row[::-1] for row in field]
    
    #Defines game terms: 4x4 matrix, if you get 2048 you win anf
    class GameField(object):
        def __init__(self, height=4, width=4, win=2048):
            self.height = height
            self.width = width
            self.win_value = 2048
            self.score = 0
            self.highscore = 0
            self.reset()
    # Randomly inputs a either 2 or 4 into the board after a move has been made
        def spawn(self):
            new_element = 4 if randrange(100) > 89 else 2
            (i, j) = choice([(i, j) for i in range(self.width) for j in
                             range(self.height) if self.field[i][j] == 0])
            self.field[i][j] = new_element
     # resets score but if a highscore it updates highscore first
        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()
     #Defines all the movements in the the game
        def move(self, direction):
            def move_row_left(row):
                #Collapses one row once 2 tiles are merged
                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
                #merges 2 tiles if they are equal and multiplies the value by itself of the new tile. Them upates the score accordingly
                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 same value will append the 2 tiles
                            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)))
            #Shows valid moves for each direction
            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 move is valid it will spawn a new random tile (2 or 4)
            if direction in moves:
                if self.move_is_possible(direction):
                    self.field = moves[direction](self.field)
                    self.spawn()
                    return True
                else:
                    return False
        # win if 2048 is reached
        def is_win(self):
            return any(any(i >= self.win_value for i in row) for row in self.field)
        #game is over if no possible moves on field
        def is_gameover(self):
            return not any(self.move_is_possible(move) for move in actions)
    # Draws to screen depending on action
        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 + '
    ')
    #seperator for horizontal tile sqaures
            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
    #draws rows to create table to play game
            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('HGHSCORE: ' + str(self.highscore))
            for row in self.field:
                draw_hor_separator()
                draw_row(row)
            draw_hor_separator()
            if self.is_win(): # if you win print you win string
                cast(win_string)
            else:
                if self.is_gameover(): # if you lose print game over string
                    cast(gameover_string)
                else:
                    cast(help_string1)
            cast(help_string2)
    # checks if valid move is possible for tile
        def move_is_possible(self, direction):
            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))
    # checks the directions in which a tile can move
            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 direction in check:
                return check[direction](self.field)
            else:
                return False
    # main class to run game
    def main(stdscr):
        # initalize game
        def init():
            #重置游戏棋盘
            game_field.reset()
            return 'Game'
    #gives options if game is open but not in play
        def not_game(state):
            #画出 GameOver 的画面
            #读取用户输入判断是Restart还是Exit
            game_field.draw(stdscr)
            action = get_user_action(stdscr)
            responses = defaultdict(lambda: state)
            responses['Restart'], responses['Exit'] = 'Init', 'Exit'
            return responses[action]
    
        def game():
    # based on response will act appropriately (user says restart it will restart)
            game_field.draw(stdscr)
            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'
    # defines the 4 possible actions that the user can be in
        state_actions = {
            'Init' : init,
            'Win' : lambda: not_game('Win'),
            'Gameover': lambda: not_game('Gameover'),
            'Game': game
        }
        #As long as user doesnt exit keep game going
        curses.use_default_colors()
        game_field = GameField(win = 32)
        state = 'Init'
        while state != 'Exit':
            state = state_actions[state]()
    
    curses.wrapper(main)
    • 运行效果

    简单:

    • 安装 wx 库 pip install wxpython

    • 运行以下代码

    # -*- coding: utf-8 -*-
    
    #Importing libraries to be used
    import wx 
    import os
    import random
    import copy
    
    # creating the user interface frame that the user will interact with and perform actions that will have an appropriate response
    class Frame(wx.Frame):
        def __init__(self,title):
            #created a default toolbar of application with a resizeable option and minimize box 
            super(Frame,self).__init__(None,-1,title,
                    style=wx.DEFAULT_FRAME_STYLE^wx.MAXIMIZE_BOX^wx.RESIZE_BORDER)
            #Setting different colours for each tile in the game
            self.colors = {0:(204,192,179),2:(238, 228, 218),4:(237, 224, 200),
                    8:(242, 177, 121),16:(245, 149, 99),32:(246, 124, 95),
                    64:(246, 94, 59),128:(237, 207, 114),256:(237, 207, 114),
                    512:(237, 207, 114),1024:(237, 207, 114),2048:(237, 207, 114),
                    4096:(237, 207, 114),8192:(237, 207, 114),16384:(237, 207, 114),
                    32768:(237, 207, 114),65536:(237, 207, 114),131072:(237, 207, 114),
                    262144:(237, 207, 114),524288:(237, 207, 114),1048576:(237, 207, 114),
                    2097152:(237, 207, 114),4194304:(237, 207, 114),
                    8388608:(237, 207, 114),16777216:(237, 207, 114),
                    33554432:(237, 207, 114),67108864:(237, 207, 114),
                    134217728:(237, 207, 114),268435456:(237, 207, 114),
                    536870912:(237, 207, 114),1073741824:(237, 207, 114),
                    2147483648:(237, 207, 114),4294967296:(237, 207, 114),
                    8589934592:(237, 207, 114),17179869184:(237, 207, 114),
                    34359738368:(237, 207, 114),68719476736:(237, 207, 114),
                    137438953472:(237, 207, 114),274877906944:(237, 207, 114),
                    549755813888:(237, 207, 114),1099511627776:(237, 207, 114),
                    2199023255552:(237, 207, 114),4398046511104:(237, 207, 114),
                    8796093022208:(237, 207, 114),17592186044416:(237, 207, 114),
                    35184372088832:(237, 207, 114),70368744177664:(237, 207, 114),
                    140737488355328:(237, 207, 114),281474976710656:(237, 207, 114),
                    562949953421312:(237, 207, 114),1125899906842624:(237, 207, 114),
                    2251799813685248:(237, 207, 114),4503599627370496:(237, 207, 114),
                    9007199254740992:(237, 207, 114),18014398509481984:(237, 207, 114),
                    36028797018963968:(237, 207, 114),72057594037927936:(237, 207, 114)}
         #Initalize game           
            self.setIcon()
            self.initGame()
        #Displays game and provides settings to move the tiles
            panel = wx.Panel(self)
            panel.Bind(wx.EVT_KEY_DOWN,self.onKeyDown)
            panel.SetFocus()
            self.initBuffer()
            self.Bind(wx.EVT_SIZE,self.onSize) 
            self.Bind(wx.EVT_PAINT, self.onPaint)
            self.Bind(wx.EVT_CLOSE,self.onClose)
            self.SetClientSize((505,720))
            self.Center()
            self.Show()
        #Puts on board so user can see
        def onPaint(self,event):
            dc = wx.BufferedPaintDC(self,self.buffer)
        # Saves score and terminates when closed
        def onClose(self,event):
            self.saveScore()
            self.Destroy()
        #   putting icon on toolbar
        def setIcon(self):
            icon = wx.Icon("icon.ico",wx.BITMAP_TYPE_ICO)
            self.SetIcon(icon)
         #Opens previous game and loads and updates score
        def loadScore(self):
            if os.path.exists("bestscore.ini"):
                ff = open("bestscore.ini")
                self.bstScore = ff.read()
                ff.close()
         #Saves score and writes to file so it may be opened later
        def saveScore(self):
            ff = open("bestscore.ini","w")
            ff.write(str(self.bstScore))
            ff.close()
         #Initalize game so when it opens it displays text, score and all data needed for the game
        def initGame(self):
            self.bgFont = wx.Font(50,wx.SWISS,wx.NORMAL,wx.BOLD,face=u"Roboto")
            self.scFont = wx.Font(36,wx.SWISS,wx.NORMAL,wx.BOLD,face=u"Roboto")
            self.smFont = wx.Font(12,wx.SWISS,wx.NORMAL,wx.NORMAL,face=u"Roboto")
            self.curScore = 0
            self.bstScore = 0
            self.loadScore()
            # 4 rows and 4 coloums for tiles ( using arrays because it easily represents system used )
            self.data = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
            count = 0
            # First 2 tile inialized if 1 tile it must be 2 but if 2 tiles connected then its 4
            while count<2: 
                row = random.randint(0,len(self.data)-1) 
                col = random.randint(0,len(self.data[0])-1)
                if self.data[row][col]!=0: continue           
                self.data[row][col] = 2 if random.randint(0,1) else 4
                count += 1
             # empty bitmap to put pixels in for game   
        def initBuffer(self):
            w,h = self.GetClientSize()
            self.buffer = wx.EmptyBitmap(w,h)
            #Displays all drawings to the screen
        def onSize(self,event):
            self.initBuffer()
            self.drawAll()
            #Placing tiles on screen and multiplying by 2 if 2 tiles interact with one another(game logic) 
        def putTile(self):
            available = []
            for row in range(len(self.data)):
                for col in range(len(self.data[0])):
                    if self.data[row][col]==0: available.append((row,col)) # add tile if empty square
            if available:
                row,col = available[random.randint(0,len(available)-1)]
                self.data[row][col] = 2 if random.randint(0,1) else 4 
                return True
            return False
        def update(self,vlist,direct): # updates score and game tiles 
            score = 0
            if direct: #up or left
                i = 1
                while i<len(vlist): 
                    # if 2 tiles of equal value mesh upward it multiples the values and deletes the ith number (2 squares = 1 square)
                    if vlist[i-1]==vlist[i]:
                        del vlist[i]
                        vlist[i-1] *= 2
                        score += vlist[i-1] # Adds multiplied value to score 
                        i += 1
                    i += 1
            else:
                #direction moved downward same thing as above but different direction
                i = len(vlist)-1
                while i>0:
                    if vlist[i-1]==vlist[i]:
                        del vlist[i]
                        vlist[i-1] *= 2
                        score += vlist[i-1]
                        i -= 1
                    i -= 1      
            return score
            # The calucation and keeping logs of data for score (upward and downward movements)
        def slideUpDown(self,up):
            score = 0
            numCols = len(self.data[0])
            numRows = len(self.data)
            oldData = copy.deepcopy(self.data)
            
            for col in range(numCols):
                cvl = [self.data[row][col] for row in range(numRows) if self.data[row][col]!=0]
                if len(cvl)>=2:
                    score += self.update(cvl,up)
                for i in range(numRows-len(cvl)):
                    if up: cvl.append(0)
                    else: cvl.insert(0,0)
                for row in range(numRows): self.data[row][col] = cvl[row]
            return oldData!=self.data,score
        
        # The calucation and keeping logs of data for score (right and left movements)
        def slideLeftRight(self,left):
            score = 0
            numRows = len(self.data)
            numCols = len(self.data[0])
            oldData = copy.deepcopy(self.data)
            
            for row in range(numRows):
                rvl = [self.data[row][col] for col in range(numCols) if self.data[row][col]!=0]
                if len(rvl)>=2:           
                    score += self.update(rvl,left)
                for i in range(numCols-len(rvl)):
                    if left: rvl.append(0)
                    else: rvl.insert(0,0)
                for col in range(numCols): self.data[row][col] = rvl[col]
            return oldData!=self.data,score
        def isGameOver(self):
            copyData = copy.deepcopy(self.data)
            
            flag = False # Tile is not moveable or you have lost if all tiles cant move any pieces up,down, left or right 
            if not self.slideUpDown(True)[0] and not self.slideUpDown(False)[0] and 
                    not self.slideLeftRight(True)[0] and not self.slideLeftRight(False)[0]:
                flag = True #continue playing and copydata 
            if not flag: self.data = copyData
            return flag
      # Game logic to see if you can make a move or end the game
        def doMove(self,move,score):
            # if you can move put a tile and update change
            if move:
                self.putTile()
                self.drawChange(score)
                # if game is over put a message box and update best score if its the new best score
                if self.isGameOver():
                    if wx.MessageBox(u"游戏结束,是否重新开始?",u"哈哈",
                            wx.YES_NO|wx.ICON_INFORMATION)==wx.YES:
                        bstScore = self.bstScore
                        self.initGame()
                        self.bstScore = bstScore
                        self.drawAll()
                        
        # when you click a directon for the tile to move, it moves in the appropriate direction
        def onKeyDown(self,event):
            keyCode = event.GetKeyCode()
                    
            if keyCode==wx.WXK_UP:
                self.doMove(*self.slideUpDown(True))
            elif keyCode==wx.WXK_DOWN:
                self.doMove(*self.slideUpDown(False))
            elif keyCode==wx.WXK_LEFT:
                self.doMove(*self.slideLeftRight(True))
            elif keyCode==wx.WXK_RIGHT:
                self.doMove(*self.slideLeftRight(False))        
                    
         # Creates background for the game board
        def drawBg(self,dc):
            dc.SetBackground(wx.Brush((250,248,239)))
            dc.Clear()
            dc.SetBrush(wx.Brush((187,173,160)))
            dc.SetPen(wx.Pen((187,173,160)))
            dc.DrawRoundedRectangle(15,150,475,475,5)
            #Creates a 2048 logo
        def drawLogo(self,dc):
            dc.SetFont(self.bgFont)
            dc.SetTextForeground((119,110,101))
            dc.DrawText(u"2048",15,26)
            # provides text to screen (Chinese text)
        def drawLabel(self,dc):
            dc.SetFont(self.smFont)
            dc.SetTextForeground((119,110,101))
            dc.DrawText(u"合并相同数字,得到2048吧!",15,114)
            dc.DrawText(u"怎么玩: 
    用-> <- 上下左右箭头按键来移动方块. 
                    
    当两个相同数字的方块碰到一起时,会合成一个!",15,639)
            # Displays score to screen 
        def drawScore(self,dc):            
            dc.SetFont(self.smFont)
            scoreLabelSize = dc.GetTextExtent(u"SCORE")
            bestLabelSize = dc.GetTextExtent(u"BEST")
            curScoreBoardMinW = 15*2+scoreLabelSize[0]
            bstScoreBoardMinW = 15*2+bestLabelSize[0]
            curScoreSize = dc.GetTextExtent(str(self.curScore))
            bstScoreSize = dc.GetTextExtent(str(self.bstScore))
            curScoreBoardNedW = 10+curScoreSize[0]
            bstScoreBoardNedW = 10+bstScoreSize[0]
            curScoreBoardW = max(curScoreBoardMinW,curScoreBoardNedW)
            bstScoreBoardW = max(bstScoreBoardMinW,bstScoreBoardNedW)
            dc.SetBrush(wx.Brush((187,173,160)))
            dc.SetPen(wx.Pen((187,173,160)))
            dc.DrawRoundedRectangle(505-15-bstScoreBoardW,40,bstScoreBoardW,50,3)
            dc.DrawRoundedRectangle(505-15-bstScoreBoardW-5-curScoreBoardW,40,curScoreBoardW,50,3)
            dc.SetTextForeground((238,228,218))
            dc.DrawText(u"BEST",505-15-bstScoreBoardW+(bstScoreBoardW-bestLabelSize[0])/2,48)
            dc.DrawText(u"SCORE",505-15-bstScoreBoardW-5-curScoreBoardW+(curScoreBoardW-scoreLabelSize[0])/2,48)
            dc.SetTextForeground((255,255,255))
            dc.DrawText(str(self.bstScore),505-15-bstScoreBoardW+(bstScoreBoardW-bstScoreSize[0])/2,68)
            dc.DrawText(str(self.curScore),505-15-bstScoreBoardW-5-curScoreBoardW+(curScoreBoardW-curScoreSize[0])/2,68)
        # Put rounded rectangular tiles on screen
        def drawTiles(self,dc):
            dc.SetFont(self.scFont)
            for row in range(4):
                for col in range(4):
                    value = self.data[row][col]
                    color = self.colors[value]
                    if value==2 or value==4:
                        dc.SetTextForeground((119,110,101))
                    else:
                        dc.SetTextForeground((255,255,255))
                    dc.SetBrush(wx.Brush(color))
                    dc.SetPen(wx.Pen(color))
                    dc.DrawRoundedRectangle(30+col*115,165+row*115,100,100,2)
                    size = dc.GetTextExtent(str(value))
                    while size[0]>100-15*2: # changes font size based on number within tile
                        self.scFont = wx.Font(self.scFont.GetPointSize()*4/5,wx.SWISS,wx.NORMAL,wx.BOLD,face=u"Roboto")
                        dc.SetFont(self.scFont)
                        size = dc.GetTextExtent(str(value))
                    if value!=0: dc.DrawText(str(value),30+col*115+(100-size[0])/2,165+row*115+(100-size[1])/2)
        # Draws everything to the screen
        def drawAll(self):
            dc = wx.BufferedDC(wx.ClientDC(self),self.buffer)
            self.drawBg(dc)
            self.drawLogo(dc)
            self.drawLabel(dc)
            self.drawScore(dc)
            self.drawTiles(dc)
        # Calculates current score and checks if it is the best score and if so updates    
        def drawChange(self,score):
            dc = wx.BufferedDC(wx.ClientDC(self),self.buffer)
            if score:
                self.curScore += score
                if self.curScore > self.bstScore:
                    self.bstScore = self.curScore
                self.drawScore(dc)
            self.drawTiles(dc)
         # Shows creator info
    if __name__ == "__main__":
        app = wx.App()
        Frame(u"2048 v1.0.1 by Guolz")
        app.MainLoop()

    第二种

    直接运行一下代码
    # -*- coding:UTF-8 -*-
    
    import random
    import os
    import sys
    
    v = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
    
    
    def display(v, score):
        print("%4d%4d%4d%4d" % (v[0][0], v[0][1], v[0][2], v[0][3])) 
        print("%4d%4d%4d%4d" % (v[1][0], v[1][1], v[1][2], v[1][3]))
        print("%4d%4d%4d%4d" % (v[2][0], v[2][1], v[2][2], v[2][3]))
        print("%4d%4d%4d%4d" % (v[3][0], v[3][1], v[3][2], v[3][3]))
        print("Total score: %d" % score)
    
    
    def init(v):
        for i in range(4):
            v[i] = [random.choice([0, 0, 0, 2, 2, 4]) for x in range(4)]
    
    
    def align(vList, direction):
        for i in range(vList.count(0)):
            vList.remove(0)
        zeros = [0 for x in range(4 - len(vList))]
        if direction == 'left':
            vList.extend(zeros)
        else:
            vList[:0] = zeros
    
    
    def addSame(vList, direction):
        score = 0
        if direction == 'left':
            for i in [0, 1, 2]:
                align(vList, direction)
                if vList[i] == vList[i + 1] != 0:
                    vList[i] *= 2
                    vList[i + 1] = 0
                    score += vList[i]
                    return {'bool': True, 'score': score}
        else:
            for i in [3, 2, 1]:
                align(vList, direction)
                if vList[i] == vList[i - 1] != 0:
                    vList[i] *= 2
                    vList[i - 1] = 0
                    score += vList[i]
                    return {'bool': True, 'score': score}
        return {'bool': False, 'score': score}
    
    
    def handle(vList, direction):
        totalScore = 0
        align(vList, direction)
        result = addSame(vList, direction)
        while result['bool'] == True:
            totalScore += result['score']
            align(vList, direction)
            result = addSame(vList, direction)
        return totalScore
    
    
    def operation(v):
        totalScore = 0
        gameOver = False
        direction = 'left'
        op = input('operator:')
        if op in ['a', 'A']:
            direction = 'left'
            for row in range(4):
                totalScore += handle(v[row], direction)
        elif op in ['d', 'D']:
            direction = 'right'
            for row in range(4):
                totalScore += handle(v[row], direction)
        elif op in ['w', 'W']:
            direction = 'left'
            for col in range(4):
                vList = [v[row][col] for row in range(4)]
                totalScore += handle(vList, direction)
                for row in range(4):
                    v[row][col] = vList[row]
        elif op in ['s', 'S']:
            direction = 'right'
            for col in range(4):
                vList = [v[row][col] for row in range(4)]
                totalScore += handle(vList, direction)
                for row in range(4):
                    v[row][col] = vList[row]
        else:
            print("Invalid input,please enter a charactor in [W,S,A,D] or the lower")
            gameOver = True
            return {'gameOver': gameOver, 'score': totalScore}
    
        N = 0
        for q in v:
            N += q.count(0)
    
        if N == 0:
            gameOver = True
            return {'gameover': gameOver, 'score': totalScore}
    
        num = random.choice([2, 2, 2, 4])
        k = random.randrange(1, N + 1)
        n = 0
    
        for i in range(4):
            for j in range(4):
                if v[i][j] == 0:
                    n += 1
                    if n == k:
                        v[i][j] = num
                        break
    
        return {'gameOver': gameOver, 'score': totalScore}
    
    
    init(v)
    score = 0
    print("Input: W(Up) S(Down) A(Left) D(Right), press <CR>.")
    while True:
        os.system("cls")
        display(v, score)
        result = operation(v)
        print(result["score"])
        if result['gameOver'] == True:
            print("Game Over, You failed!")
            print("Your total score %d" % (score))
            sys.exit(1)
        else:
            score += result['score']
            if score >= 2048:
                print("Game Over, You Win!!!")
                print("Your total score: %d" % (score))
                sys.exit(0)

    最终效果图:

     

     

     

    ### ||| || | Detanima in Dark
    如果还有问题未能得到解决,搜索887934385交流群,领取资料工具安装包学习
  • 相关阅读:
    Server Application Unavailable 解决办法 (转)
    SQL SERVER:分割函数 split
    Win32汇编_基础
    Win32汇编_异常_筛选器
    创建进程常用函数
    内存常用函数
    桃花庵歌
    文天祥的诗
    Socket I/O模型全接触
    函数指针的神奇
  • 原文地址:https://www.cnblogs.com/pypypy/p/11957199.html
Copyright © 2020-2023  润新知