1 / app.py
asffadsa's picture
Update app.py
1b80930 verified
import gradio as gr
import numpy as np
# 初始化游戏板
def initialize_board():
board = np.zeros((4, 4), dtype=int)
add_new_tile(board)
add_new_tile(board)
return board
# 添加新的数字块
def add_new_tile(board):
zeros = list(zip(*np.where(board == 0)))
if zeros:
x, y = zeros[np.random.choice(len(zeros))]
board[x, y] = np.random.choice([2, 4], p=[0.9, 0.1])
# 移动数字块
def move(board, direction):
if direction == 'left':
board = np.rot90(board, 1)
board = move_left(board)
board = np.rot90(board, -1)
elif direction == 'right':
board = np.rot90(board, -1)
board = move_left(board)
board = np.rot90(board, 1)
elif direction == 'up':
board = move_left(board)
elif direction == 'down':
board = np.rot90(board, 2)
board = move_left(board)
board = np.rot90(board, 2)
return board
# 向左移动数字块
def move_left(board):
new_board = np.zeros((4, 4), dtype=int)
for i in range(4):
row = board[i, :]
row = row[row != 0]
row = merge(row)
new_board[i, :len(row)] = row
return new_board
# 合并相同的数字块
def merge(row):
for i in range(len(row) - 1):
if row[i] == row[i + 1]:
row[i] *= 2
row[i + 1] = 0
row = row[row != 0]
return row
# 游戏主循环
def game_loop(board, direction):
if direction:
board = move(board, direction)
add_new_tile(board)
return board
# 初始化游戏板
board = initialize_board()
# 创建Gradio界面
def update_board(direction):
global board
board = game_loop(board, direction)
return board
with gr.Blocks() as demo:
gr.Markdown("# 2048 Game")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## Controls")
up_button = gr.Button("Up")
down_button = gr.Button("Down")
left_button = gr.Button("Left")
right_button = gr.Button("Right")
with gr.Column(scale=2):
gr.Markdown("## Game Board")
board_display = gr.Dataframe(board, headers=["", "", "", ""], datatype=["number", "number", "number", "number"])
up_button.click(update_board, inputs=None, outputs=board_display, _js="() => 'up'")
down_button.click(update_board, inputs=None, outputs=board_display, _js="() => 'down'")
left_button.click(update_board, inputs=None, outputs=board_display, _js="() => 'left'")
right_button.click(update_board, inputs=None, outputs=board_display, _js="() => 'right'")
demo.launch()