Python 贪吃蛇游戏代码示例 - 初学者指南
这是一个简单的贪吃蛇游戏 Python 代码示例,供初学者参考。
import tkinter as tk
import random
# 定义常量
WIDTH = 500
HEIGHT = 500
DELAY = 100
UNIT_SIZE = 20
# 初始化变量
score = 0
direction = 'Right'
new_direction = 'Right'
snake = [(0, 0), (UNIT_SIZE, 0), (2 * UNIT_SIZE, 0)]
food = None
# 创建主窗口
root = tk.Tk()
root.title('Snake Game')
# 创建画布
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
# 创建蛇和食物
def create_snake():
for x, y in snake:
canvas.create_rectangle(x, y, x + UNIT_SIZE, y + UNIT_SIZE, fill='green')
def create_food():
global food, food_x, food_y
food_x = random.randint(0, (WIDTH - UNIT_SIZE) // UNIT_SIZE) * UNIT_SIZE
food_y = random.randint(0, (HEIGHT - UNIT_SIZE) // UNIT_SIZE) * UNIT_SIZE
food = canvas.create_oval(food_x, food_y, food_x + UNIT_SIZE, food_y + UNIT_SIZE, fill='red')
# 蛇的移动
def move_snake():
global direction, new_direction, score
head_x, head_y = snake[-1]
if new_direction == 'Up':
head_y -= UNIT_SIZE
elif new_direction == 'Down':
head_y += UNIT_SIZE
elif new_direction == 'Left':
head_x -= UNIT_SIZE
elif new_direction == 'Right':
head_x += UNIT_SIZE
snake.append((head_x, head_y))
if head_x == food_x and head_y == food_y:
score += 10
canvas.delete(food)
create_food()
else:
snake.pop(0)
canvas.delete('all')
create_snake()
canvas.create_text(WIDTH - 50, 20, text=f'Score: {score}')
canvas.after(DELAY, move_snake)
# 碰撞检测
def check_collision():
global snake
head = snake[-1]
x, y = head
if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
game_over()
for i in range(len(snake) - 1):
if head == snake[i]:
game_over()
# 游戏结束
def game_over():
canvas.create_text(WIDTH // 2, HEIGHT // 2, text='Game Over!', font=('Arial', 20))
canvas.after_cancel(move_id)
canvas.after_cancel(check_id)
# 处理键盘事件
def on_key_press(event):
global new_direction
if event.keysym == 'Up' and direction != 'Down':
new_direction = 'Up'
elif event.keysym == 'Down' and direction != 'Up':
new_direction = 'Down'
elif event.keysym == 'Left' and direction != 'Right':
new_direction = 'Left'
elif event.keysym == 'Right' and direction != 'Left':
new_direction = 'Right'
# 绑定键盘事件
canvas.bind_all('<Key>', on_key_press)
# 启动游戏
create_snake()
create_food()
move_id = canvas.after(DELAY, move_snake)
check_id = canvas.after(DELAY, check_collision)
root.mainloop()
代码说明:
-
导入库:
import tkinter as tk导入 Tkinter 库来创建图形界面,import random导入随机数库来生成食物的位置。 -
定义常量:
WIDTH和HEIGHT定义游戏窗口的宽度和高度。DELAY定义蛇移动的延迟时间。UNIT_SIZE定义蛇和食物的尺寸。
-
初始化变量:
score记录游戏分数。direction和new_direction分别表示蛇当前移动方向和下一个移动方向。snake是一个列表,记录蛇身体的坐标。food是一个变量,记录食物的图形对象。
-
创建主窗口和画布:
root = tk.Tk()创建主窗口。root.title('Snake Game')设置窗口标题。canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)创建画布。canvas.pack()将画布添加到窗口中。
-
创建蛇和食物:
create_snake()函数用于在画布上绘制蛇。create_food()函数用于在画布上随机生成食物。
-
蛇的移动:
move_snake()函数用于更新蛇的位置。- 函数首先获取蛇头的坐标。
- 然后根据
new_direction更新蛇头的坐标。 - 将新的蛇头坐标添加到
snake列表中。 - 如果蛇头与食物的坐标重合,则增加分数,删除食物,并重新生成食物。
- 否则,删除蛇尾的坐标。
- 清空画布,重新绘制蛇和食物,并更新分数显示。
- 使用
canvas.after(DELAY, move_snake)定时器来重复调用move_snake()函数,实现蛇的持续移动。
-
碰撞检测:
check_collision()函数用于检测蛇是否撞到墙壁或自己。- 函数首先获取蛇头的坐标。
- 然后检查蛇头是否超出游戏区域。
- 如果超出,则调用
game_over()函数。 - 然后检查蛇头是否与蛇身体的任何其他部分重合。
- 如果重合,则调用
game_over()函数。
-
游戏结束:
game_over()函数用于显示游戏结束信息。- 函数在画布上显示“Game Over!”字样。
- 使用
canvas.after_cancel(move_id)和canvas.after_cancel(check_id)取消定时器,停止游戏。
-
处理键盘事件:
on_key_press()函数用于处理键盘事件。- 函数获取键盘输入,根据方向键更新
new_direction,但要确保蛇不能朝反方向移动。
-
绑定键盘事件:
canvas.bind_all('<Key>', on_key_press)绑定键盘事件,使游戏响应方向键。
-
启动游戏:
create_snake()和create_food()函数分别用于创建蛇和食物。move_id = canvas.after(DELAY, move_snake)和check_id = canvas.after(DELAY, check_collision)分别启动定时器,实现蛇的移动和碰撞检测。root.mainloop()启动 Tkinter 事件循环,使游戏运行。
代码运行步骤:
- 确保你的电脑上已经安装了 Python 和 Tkinter 库。
- 将代码保存为一个 Python 文件,例如
snake_game.py。 - 在命令行中运行
python snake_game.py。
运行代码后,你将看到一个贪吃蛇游戏窗口。你可以使用方向键控制蛇的方向。当蛇撞到墙壁或自己时,游戏结束。
原文地址: https://www.cveoy.top/t/topic/mUed 著作权归作者所有。请勿转载和采集!