• 智能AI问答!更聪明、更完整、原创作!
  • 一款基于GPT的超级AI机器人,可以回答问题、聊天、创作、写文案!

2048小游戏的代码

发布于 2023-12-02 09:24:12

下面是一个简单的2048小游戏的Python代码示例:

import random

# 初始化游戏界面
def init_game():
    game_board = [[0] * 4 for _ in range(4)]
    add_new_tile(game_board)
    add_new_tile(game_board)
    return game_board

# 打印游戏界面
def print_game_board(game_board):
    for row in game_board:
        print(row)

# 在空白位置随机添加一个新的数字2或4
def add_new_tile(game_board):
    empty_tiles = []
    for i in range(len(game_board)):
        for j in range(len(game_board[i])):
            if game_board[i][j] == 0:
                empty_tiles.append((i, j))
    if empty_tiles:
        i, j = random.choice(empty_tiles)
        game_board[i][j] = random.choice([2, 4])

# 移动游戏界面
def move(game_board, direction):
    moved = False
    if direction == 'up':
        for j in range(len(game_board[0])):
            for i in range(1, len(game_board)):
                if game_board[i][j] != 0:
                    k = i
                    while k > 0 and game_board[k-1][j] == 0:
                        game_board[k-1][j] = game_board[k][j]
                        game_board[k][j] = 0
                        k -= 1
                        moved = True
                    if k > 0 and game_board[k-1][j] == game_board[k][j]:
                        game_board[k-1][j] *= 2
                        game_board[k][j] = 0
                        moved = True
    # 其他三个方向的移动逻辑类似,这里省略
    return moved

# 判断游戏是否结束
def is_game_over(game_board):
    for i in range(len(game_board)):
        for j in range(len(game_board[i])):
            if game_board[i][j] == 0:
                return False
            if i > 0 and game_board[i][j] == game_board[i-1][j]:
                return False
            if i < len(game_board)-1 and game_board[i][j] == game_board[i+1][j]:
                return False
            if j > 0 and game_board[i][j] == game_board[i][j-1]:
                return False
            if j < len(game_board[i])-1 and game_board[i][j] == game_board[i][j+1]:
                return False
    return

# 主游戏逻辑
def main():
    game_board = init_game()
    while True:
        print_game_board(game_board)
        if is_game_over(game_board):
            print("Game Over!")
            break
        direction = input("Enter move direction: ")
        moved = move(game_board, direction)
        if moved:
            add_new_tile(game_board)

# 运行游戏
if __name__ == "__main__":
    main()

这是一个简化版本的2048小游戏代码,其中包含了初始化游戏界面、打印游戏界面、在空白位置随机添加新数字、移动游戏界面、判断游戏是否结束等功能。你可以根据需要进行修改和完善。

0 条评论

发布
问题

在线
客服