写出2048游戏的Python完整代码 使用tkinter
时间: 2023-09-11 21:04:39 浏览: 221
### 回答1:
这是一个使用 tkinter 库创建的 2048 游戏的示例代码:
```
import tkinter as tk
import random
# 定义游戏界面的大小
WIDTH = 400
HEIGHT = 600
# 定义各个数字方块的颜色
COLORS = {
0: "#FFFFFF",
2: "#FFEBCD",
4: "#F0E68C",
8: "#FFD700",
16: "#FFA500",
32: "#FF4500",
64: "#8B2500",
128: "#000000",
256: "#00FFFF",
512: "#00FF00",
1024: "#0000FF",
2048: "#800080"
}
class Game(tk.Tk):
def __init__(self):
super().__init__()
self.title("2048")
self.geometry(f"{WIDTH}x{HEIGHT}")
self.resizable(False, False)
# 初始化游戏界面
self.canvas = tk.Canvas(self, width=WIDTH, height=HEIGHT)
self.canvas.pack()
self.grid = [[0] * 4 for _ in range(4)]
self.score = 0
self.add_number()
self.add_number()
self.draw_grid()
# 绑定键盘事件
self.bind("<Up>", lambda event: self.move("up"))
self.bind("<Down>", lambda event: self.move("down"))
self.bind("<Left>", lambda event: self.move("left"))
self.bind("<Right>", lambda event: self.move("right"))
def add_number(self):
"""在空白的方块中随机添加数字"""
empty_cells = [(i, j) for i in range(4) for j in range(4) if self.grid[i][j] == 0]
if not empty_cells:
return
i, j = random.choice(empty_cells)
self.grid[i][j] = 2 if random.randint(1, 10) == 1 else 4
self.draw_number(i, j)
def draw_grid(self):
"""绘制游戏界面"""
self.canvas.delete("all")
for i in range(4):
for j in range(4):
x1, y1 = j * 100 + 10, i * 100 + 10
x2, y2 = j * 100 + 90, i * 100 + 90
self.canvas.create_rectangle(x1, y1, x2, y2, fill=COLORS[self.grid[i][j]])
if self.
### 回答2:
2048游戏是一款非常经典的益智游戏,在这里我将为你提供一个使用Python编写的完整代码,使用tkinter库来创建游戏界面。
```python
import tkinter as tk
import random
# 游戏界面相关常量
WIDTH = 400
HEIGHT = 400
GRID_SIZE = 4
GRID_PADDING = 10
# 初始化游戏界面和数据
root = tk.Tk()
root.title("2048")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
grid_cells = []
game_board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
# 在游戏界面上绘制方块
def draw_grid():
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
x = j * (WIDTH / GRID_SIZE)
y = i * (HEIGHT / GRID_SIZE)
value = game_board[i][j]
# 绘制方块背景
canvas.create_rectangle(x, y, x + (WIDTH / GRID_SIZE), y + (HEIGHT / GRID_SIZE), fill="#EEE4DA")
# 绘制方块上的数字
if value != 0:
text = canvas.create_text(x + (WIDTH / GRID_SIZE) / 2, y + (HEIGHT / GRID_SIZE) / 2, text=str(value), font=("Arial", 32, "bold"))
# 添加到方块列表
grid_cells.append(text)
# 在随机位置生成一个新数字
def generate_new_number():
available_cells = [(i, j) for i in range(GRID_SIZE) for j in range(GRID_SIZE) if game_board[i][j] == 0]
if len(available_cells) > 0:
i, j = random.choice(available_cells)
game_board[i][j] = random.choice([2, 4])
# 开始新游戏
def start_game():
global game_board
game_board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
draw_grid()
generate_new_number()
generate_new_number()
# 处理按键事件
def handle_key(event):
if event.char == "w":
move_up()
elif event.char == "s":
move_down()
elif event.char == "a":
move_left()
elif event.char == "d":
move_right()
# 向上移动方块
def move_up():
for j in range(GRID_SIZE):
for i in range(1, GRID_SIZE):
if game_board[i][j] != 0:
value = game_board[i][j]
k = i - 1
while k >= 0 and game_board[k][j] == 0:
game_board[k][j] = value
game_board[k+1][j] = 0
k -= 1
# 向下移动方块(类似向上移动)
def move_down():
for j in range(GRID_SIZE):
for i in range(GRID_SIZE-2, -1, -1):
if game_board[i][j] != 0:
value = game_board[i][j]
k = i + 1
while k < GRID_SIZE and game_board[k][j] == 0:
game_board[k][j] = value
game_board[k-1][j] = 0
k += 1
# 向左移动方块(类似向上移动)
def move_left():
for i in range(GRID_SIZE):
for j in range(1, GRID_SIZE):
if game_board[i][j] != 0:
value = game_board[i][j]
k = j - 1
while k >= 0 and game_board[i][k] == 0:
game_board[i][k] = value
game_board[i][k+1] = 0
k -= 1
# 向右移动方块(类似向上移动)
def move_right():
for i in range(GRID_SIZE):
for j in range(GRID_SIZE-2, -1, -1):
if game_board[i][j] != 0:
value = game_board[i][j]
k = j + 1
while k < GRID_SIZE and game_board[i][k] == 0:
game_board[i][k] = value
game_board[i][k-1] = 0
k += 1
# 监听按键事件
root.bind("<Key>", handle_key)
# 开始游戏
start_game()
# 运行界面
root.mainloop()
```
这是一个基本的2048游戏代码,通过运行以上代码,你将在一个包含游戏界面的窗口中玩2048游戏。你可以使用"w"、"s"、"a"、"d"四个按键来移动方块,游戏目标是合并相同数字的方块直到达到2048。祝你玩得开心!
### 回答3:
下面是一个基于tkinter库的2048游戏的Python完整代码:
```python
import tkinter as tk
import random
# 游戏界面大小
WIDTH = 400
HEIGHT = 400
# 棋盘格子数目
GRID_SIZE = 4
# 方向键对应的移动向量
UP = (-1, 0)
DOWN = (1, 0)
LEFT = (0, -1)
RIGHT = (0, 1)
# 初始化游戏界面
root = tk.Tk()
root.title("2048")
root.geometry(f"{WIDTH}x{HEIGHT}")
# 棋盘格子的大小
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
# 创建主游戏区域
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="#bbada0")
canvas.pack()
# 初始化游戏数据
grid_values = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
# 生成随机数并放置到空白格子中
def place_random_number():
empty_cells = [(i, j) for i in range(GRID_SIZE) for j in range(GRID_SIZE) if grid_values[i][j] == 0]
if empty_cells:
i, j = random.choice(empty_cells)
grid_values[i][j] = random.choice([2, 4])
# 检查游戏是否结束
def is_game_over():
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
if grid_values[i][j] == 0:
return False
if i < GRID_SIZE - 1 and grid_values[i][j] == grid_values[i + 1][j]:
return False
if j < GRID_SIZE - 1 and grid_values[i][j] == grid_values[i][j + 1]:
return False
return True
# 移动格子
def move(direction):
dx, dy = direction
moved = False
if dx == -1: # 上
for j in range(GRID_SIZE):
for i in range(1, GRID_SIZE):
if grid_values[i][j] != 0:
x = i
while x > 0 and grid_values[x - 1][j] == 0:
grid_values[x][j] = grid_values[x - 1][j]
grid_values[x - 1][j] = 0
x -= 1
moved = True
if x > 0 and grid_values[x - 1][j] == grid_values[x][j]:
grid_values[x][j] *= 2
grid_values[x - 1][j] = 0
moved = True
elif dx == 1: # 下
for j in range(GRID_SIZE):
for i in range(GRID_SIZE - 2, -1, -1):
if grid_values[i][j] != 0:
x = i
while x < GRID_SIZE - 1 and grid_values[x + 1][j] == 0:
grid_values[x][j] = grid_values[x + 1][j]
grid_values[x + 1][j] = 0
x += 1
moved = True
if x < GRID_SIZE - 1 and grid_values[x + 1][j] == grid_values[x][j]:
grid_values[x][j] *= 2
grid_values[x + 1][j] = 0
moved = True
elif dy == -1: # 左
for i in range(GRID_SIZE):
for j in range(1, GRID_SIZE):
if grid_values[i][j] != 0:
y = j
while y > 0 and grid_values[i][y - 1] == 0:
grid_values[i][y] = grid_values[i][y - 1]
grid_values[i][y - 1] = 0
y -= 1
moved = True
if y > 0 and grid_values[i][y - 1] == grid_values[i][y]:
grid_values[i][y] *= 2
grid_values[i][y - 1] = 0
moved = True
elif dy == 1: # 右
for i in range(GRID_SIZE):
for j in range(GRID_SIZE - 2, -1, -1):
if grid_values[i][j] != 0:
y = j
while y < GRID_SIZE - 1 and grid_values[i][y + 1] == 0:
grid_values[i][y] = grid_values[i][y + 1]
grid_values[i][y + 1] = 0
y += 1
moved = True
if y < GRID_SIZE - 1 and grid_values[i][y + 1] == grid_values[i][y]:
grid_values[i][y] *= 2
grid_values[i][y + 1] = 0
moved = True
if moved:
place_random_number()
# 绘制棋盘
canvas.delete("all")
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
x1 = j * GRID_WIDTH
y1 = i * GRID_HEIGHT
x2 = x1 + GRID_WIDTH
y2 = y1 + GRID_HEIGHT
canvas.create_rectangle(x1, y1, x2, y2, fill="#eee4da", outline="#ccc0b3")
if grid_values[i][j] != 0:
value = str(grid_values[i][j])
color = "#776e65" if grid_values[i][j] < 8 else "#f9f6f2"
canvas.create_text(x1 + GRID_WIDTH // 2, y1 + GRID_HEIGHT // 2, text=value, font=("Arial", 20, "bold"), fill=color)
# 处理按键事件
def on_key_press(event):
if event.keysym == "Up":
move(UP)
elif event.keysym == "Down":
move(DOWN)
elif event.keysym == "Left":
move(LEFT)
elif event.keysym == "Right":
move(RIGHT)
if is_game_over():
canvas.create_text(WIDTH // 2, HEIGHT // 2, text="Game Over!", font=("Arial", 30, "bold"), fill="#776e65")
# 绑定按键事件
root.bind("<Key>", on_key_press)
# 初始化游戏
place_random_number()
place_random_number()
# 主循环
root.mainloop()
```
这段代码创建了一个基于tkinter库的2048游戏界面,并实现了游戏的核心逻辑,包括生成随机数、移动格子、判断游戏是否结束等功能。同时,代码还绑定了上、下、左、右方向键的按键事件,使得玩家可以通过键盘操作来移动格子。
阅读全文