Python 간단 한 2048 미니 게임 실현

7867 단어 python2048 게임
간단 한 2048 미니 게임
더 이상 말 하지 않 고 직접 그림 을 그 렸 습 니 다.여 기 는 GUI 와 같은 것 을 실현 하지 못 했 습 니 다.필요 하 다 면 스스로 실현 할 수 있 습 니 다.

다음은 코드 모듈 입 니 다.그 중에서 2048 게임 은 원래 인터넷 에 많 았 습 니 다.저 는 상세 하 게 쓰 지 않 고 주석 에 적 었 습 니 다.유일 하 게 주의해 야 할 것 은 먼저 행렬 의 전 치 를 알 아야 한 다 는 것 이다.여기 서 사용 할 것 이다.

import random

board = [[0, 0, 0, 0],
         [0, 0, 0, 0],
         [0, 0, 0, 0],
         [0, 0, 0, 0]]


#       
def display(board, score):
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[0][0], board[0][1], board[0][2], board[0][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[1][0], board[1][1], board[1][2], board[1][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[2][0], board[2][1], board[2][2], board[2][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[3][0], board[3][1], board[3][2], board[3][3]), '        :', score)


#      , 4*4        2
def init(board):
    #        0
    for i in range(4):
        for j in range(4):
            board[i][j] = 0
    #       2     
    randomposition = random.sample(range(0, 15), 2)
    board[int(randomposition[0] / 4)][randomposition[0] % 4] = 2
    board[int(randomposition[1] / 4)][randomposition[1] % 4] = 2


def addSameNumber(boardList, direction):
    '''                 ,       

    :param boardList:                   
    :param direction: direction == 'left'      ,            ,      ,     0
                      direction == 'right'      ,            ,      ,     0
    :return:
    '''
    addNumber = 0
    #          
    if direction == 'left':
        for i in [0, 1, 2]:
            if boardList[i] == boardList[i+1] != 0:
                boardList[i] *= 2
                boardList[i + 1] = 0
                addNumber += boardList[i]
                return {'continueRun': True, 'addNumber': addNumber}
        return {'continueRun': False, 'addNumber': addNumber}
    #          
    else:
        for i in [3, 2, 1]:
            if boardList[i] == boardList[i-1] != 0:
                boardList[i] *= 2
                boardList[i - 1] = 0
                addNumber += boardList[i]
                return {'continueRun': True, 'addNumber': addNumber}
        return {'continueRun': False, 'addNumber': addNumber}


def align(boardList, direction):
    '''       

    direction == 'left':    ,  [8,0,0,2]    [8,2,0,0]
    direction == 'right':    ,  [8,0,0,2]    [0,0,8,2]
    '''
    #         0, [8,0,0,2]->[8,2],1.  0   ,          
    # boardList.remove(0):                ,  [8,0,0,2]     0
    for x in range(boardList.count(0)):
        boardList.remove(0)
    #    0      ,[8,2]->[8,2,0,0]
    if direction == 'left':
        boardList.extend([0 for x in range(4 - len(boardList))])
    else:
        boardList[:0] = [0 for x in range(4 - len(boardList))]


def handle(boardList, direction):
    '''
        ( )    ,       ( )      ,     
    :param boardList:     ,     ( )    
    :param direction:     ,          'left',        'right'
    :return:     ( )       
    '''
    addscore = 0
    #      ,             
    align(boardList, direction)
    result = addSameNumber(boardList, direction)
    #  result['continueRun']  True,        
    while result['continueRun']:
        #     ,        ,          
        addscore += result['addNumber']
        align(boardList, direction)
        result = addSameNumber(boardList, direction)
    #       ,             
    return {'addscore': addscore}


#       ,               ,     
def operator(board):
    #            ,               (       )
    addScore = 0
    gameOver = False
    #     
    direction = 'left'
    op = input("       :")
    if op in ['a', 'A']:
        #     
        direction = 'left'
        #         
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']

    elif op in ['d', 'D']:
        direction = 'right'
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']

    elif op in ['w', 'W']:
        #             
        direction = 'left'
        board = list(map(list, zip(*board)))
        #         
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']
        board = list(map(list, zip(*board)))

    elif op in ['s', 'S']:
        #             
        direction = 'right'
        board = list(map(list, zip(*board)))
        #         
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']
        board = list(map(list, zip(*board)))
    else:
        print("    !   [W, S, A, D]      ")
        return {'gameOver': gameOver, 'addScore': addScore, 'board': board}

    #            0   ,    ,     
    number_0 = 0
    for q in board:
        # count(0)  0     ,       
        number_0 += q.count(0)
    #   number_0 0,    
    if number_0 == 0:
        gameOver = True
        return {'gameOver': gameOver, 'addScore': addScore, 'board': board}
    #       ,           2  4,   3:1
    else:
        addnum = random.choice([2,2,2,4])
        position_0_list = []
        #   0   ,     
        for i in range(4):
            for j in range(4):
                if board[i][j] == 0:
                    position_0_list.append(i*4 + j)
    #       0          ,        2  4
    randomposition = random.sample(position_0_list, 1)
    board[int(randomposition[0] / 4)][randomposition[0] % 4] = addnum
    return {'gameOver': gameOver, 'addScore': addScore, 'board': board}


if __name__ == '__main__':
    print('  :W( ) S( ) A( ) D( ).')
    #        ,    
    gameOver = False
    init(board)
    score = 0
    #      ,     
    while gameOver != True:
        display(board, score)
        operator_result = operator(board)
        board = operator_result['board']
        if operator_result['gameOver'] == True:
            print("    ,   !")
            print("      :", score)
            gameOver = operator_result['gameOver']
            break
        else:
            #        
            score += operator_result['addScore']
            if score >= 2048:
                print("    ,      !")
                print("      :", score)
                #     
                gameOver = True
                break
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기