Python贪吃蛇游戏实现详解(附完整代码及教程)
import tkinter as tk
import random
class SnakeGame(tk.Tk):
def __init__(self):
super().__init__()
self.title("贪吃蛇游戏")
self.geometry("400x400")
self.snake_positions = [(100, 100), (90, 100), (80, 100)]
self.food_position = self.set_new_food_position()
self.direction = 'Right'
self.score = 0
self.speed = 100
self.canvas = tk.Canvas(self, bg='black', height=400, width=400)
self.canvas.pack()
self.bind('<Key>', self.on_key_press)
self.game_loop()
def game_loop(self):
if self.check_collision():
self.game_over()
return
self.move_snake()
if self.snake_positions[0] == self.food_position:
self.score += 1
self.speed -= 5
self.snake_positions.append(self.snake_positions[-1])
self.food_position = self.set_new_food_position()
self.canvas.delete('all')
self.draw_elements()
self.after(self.speed, self.game_loop)
def move_snake(self):
head_x, head_y = self.snake_positions[0]
if self.direction == 'Up':
new_head = (head_x, head_y - 10)
elif self.direction == 'Down':
new_head = (head_x, head_y + 10)
elif self.direction == 'Left':
new_head = (head_x - 10, head_y)
else: # Right
new_head = (head_x + 10, head_y)
self.snake_positions.insert(0, new_head)
self.snake_positions.pop()
def draw_elements(self):
for pos in self.snake_positions:
self.canvas.create_rectangle(pos[0], pos[1], pos[0]+10, pos[1]+10, fill='green')
self.canvas.create_oval(self.food_position[0]-10, self.food_position[1]-10,
self.food_position[0]+10, self.food_position[1]+10, fill='red')
self.canvas.create_text(200, 20, text=f"Score: {self.score}", fill='white')
def set_new_food_position(self):
while True:
x = random.randint(0, 39) * 10
y = random.randint(0, 39) * 10
if (x, y) not in self.snake_positions:
return x, y
def on_key_press(self, e):
if e.keysym == 'Up' and self.direction != 'Down':
self.direction = 'Up'
elif e.keysym == 'Down' and self.direction != 'Up':
self.direction = 'Down'
elif e.keysym == 'Left' and self.direction != 'Right':
self.direction = 'Left'
elif e.keysym == 'Right' and self.direction != 'Left':
self.direction = 'Right'
def check_collision(self):
head_x, head_y = self.snake_positions[0]
return (head_x, head_y) in self.snake_positions[1:] or \
head_x < 0 or head_x >= 400 or head_y < 0 or head_y >= 400
def game_over(self):
self.canvas.create_text(200, 200, text="Game Over!", fill='white', font=('Arial', 20))
self.unbind('<Key>')
self.after(2000, self.destroy)
if __name__ == "__main__":
game = SnakeGame()
game.mainloop()
注意:用户可通过上下左右箭头操控贪吃蛇的移动方向
效果如下:

优点:
①结构清晰:通过定义SnakeGame类封装了整个游戏逻辑,使得代码组织有序,易于理解和维护。
②简洁明了:虽然实现的是一个完整的游戏,但代码量适中,没有冗余部分,每个方法的职责明确,如game_loop负责游戏循环,move_snake负责蛇的移动逻辑等。
③响应式控制:通过绑定键盘事件<Key>,实现了玩家可以通过上下左右键控制蛇的移动方向,增加了游戏的互动性。
④碰撞检测:通过check_collision方法有效地检测蛇头是否触碰到自身身体或边界,逻辑简单且有效。
⑤动态难度调整:每当蛇吃到食物,分数增加的同时游戏速度加快(self.speed -= 5),这增加了游戏的挑战性和趣味性。
⑥良好的用户反馈:游戏过程中实时显示得分,并在游戏结束时显示“Game Over!”信息,同时终止游戏循环并关闭窗口,用户体验友好。
随机食物位置:通过set_new_food_position方法确保食物出现在蛇身体之外的位置,实现了食物随机出现的机制,增加了游戏的不可预测性和乐趣。
⑦资源管理:在游戏结束时通过unbind('<Key>')防止游戏结束后继续接收键盘输入,并使用destroy方法关闭窗口,合理地释放了资源。
作者:爱新觉罗·牢大