询问
以图形方式给出贪吃蛇的python代码
回答
以下是一个使用Python和Tkinter库实现的简单贪吃蛇游戏的代码。这个游戏支持基本的功能,包括蛇的移动、吃食物、增长身体,以及游戏结束的判断。
import tkinter as tk
import random
class SnakeGame:
def __init__(self, master):
self.master = master
self.master.title("贪吃蛇")
self.board_size = 400 # 游戏画布大小
self.cell_size = 20 # 每个格子的大小
self.rows = self.board_size // self.cell_size
self.cols = self.board_size // self.cell_size
# 初始化游戏状态
self.snake = [(5, 5), (5, 4), (5, 3)] # 蛇的初始位置(用格子坐标表示)
self.food = None
self.direction = "Right" # 蛇的初始方向
self.running = True
# 创建画布
self.canvas = tk.Canvas(self.master, width=self.board_size, height=self.board_size, bg="black")
self.canvas.pack()
# 绑定键盘事件
self.master.bind("", self.change_direction)
# 放置食物
self.place_food()
# 开始游戏循环
self.update_game()
def place_food(self):
"""随机放置食物"""
while True:
food = (random.randint(0, self.rows - 1), random.randint(0, self.cols - 1))
if food not in self.snake: # 确保食物不会出现在蛇的身体上
self.food = food
break
def change_direction(self, event):
"""更改蛇的移动方向"""
new_direction = event.keysym
# 防止蛇直接反向移动
if (new_direction == "Up" and self.direction != "Down") or \
(new_direction == "Down" and self.direction != "Up") or \
(new_direction == "Left" and self.direction != "Right") or \
(new_direction == "Right" and self.direction != "Left"):
self.direction = new_direction
def update_game(self):
"""更新游戏状态"""
if not self.running:
return
# 移动蛇
head_x, head_y = self.snake[0]
if self.direction == "Up":
head_x -= 1
elif self.direction == "Down":
head_x += 1
elif self.direction == "Left":
head_y -= 1
elif self.direction == "Right":
head_y += 1
# 新的蛇头位置
new_head = (head_x, head_y)
# 检查游戏结束条件
if (new_head in self.snake or # 撞到自己
head_x < 0 or head_x >= self.rows or # 撞到上/下边界
head_y < 0 or head_y >= self.cols): # 撞到左/右边界
self.running = False
self.game_over()
return
# 更新蛇的身体
self.snake.insert(0, new_head)
if new_head == self.food:
# 吃到食物,放置新的食物
self.place_food()
else:
# 没有吃到食物,移除蛇尾
self.snake.pop()
# 更新画布
self.update_canvas()
# 设置游戏循环的速度(100毫秒更新一次)
self.master.after(300, self.update_game)
def update_canvas(self):
"""更新画布内容"""
self.canvas.delete("all") # 清空画布
# 绘制蛇
for x, y in self.snake:
x1 = y * self.cell_size
y1 = x * self.cell_size
x2 = x1 + self.cell_size
y2 = y1 + self.cell_size
self.canvas.create_rectangle(x1, y1, x2, y2, fill="green", outline="")
# 绘制食物
if self.food:
fx, fy = self.food
x1 = fy * self.cell_size
y1 = fx * self.cell_size
x2 = x1 + self.cell_size
y2 = y1 + self.cell_size
self.canvas.create_oval(x1, y1, x2, y2, fill="red", outline="")
def game_over(self):
"""游戏结束"""
self.canvas.create_text(self.board_size // 2, self.board_size // 2,
text="游戏结束", fill="white", font=("Arial", 24))
if __name__ == "__main__":
root = tk.Tk()
game = SnakeGame(root)
root.mainloop()
代码说明
画布设置:
游戏画布大小为400x400像素。
每个格子大小为20x20像素,整个棋盘为20x20格。
蛇的表示:
蛇的身体用一个列表表示,列表中的每个元素是蛇身体每一节的坐标(行、列)。
蛇的初始长度为3。
食物:
食物随机生成,确保不会出现在蛇的身体上。
蛇吃到食物后,长度增加,并生成新的食物。
蛇的移动:
根据当前方向更新蛇头的位置,并将新位置插入蛇的身体列表中。
如果没有吃到食物,则移除蛇尾,保持长度不变。
游戏结束:
当蛇撞到自己或边界时,游戏结束,并在画布中央显示“游戏结束”提示。
键盘事件:
使用事件监听方向键,改变蛇的移动方向。
防止蛇直接反向移动(例如从“上”直接变为“下”)。
游戏速度:
使用self.master.after(100, self.update_game)设置游戏循环,每100毫秒更新一次。
运行代码
将上述代码复制到Python环境中运行,确保已安装tkinter库(通常Python自带)。运行后会弹出一个窗口,显示贪吃蛇游戏。
使用方向键(↑、↓、←、→)控制蛇的移动。
吃到红色的食物后,蛇会变长。
撞到自己或边界时,游戏结束,并显示“游戏结束”提示。
扩展功能
如果您希望进一步扩展游戏,可以尝试以下功能:
增加难度:随着蛇的长度增加,逐渐加快游戏速度。
计分系统:在界面上显示得分,食物被吃掉时得分增加。
障碍物:在棋盘上随机生成障碍物,增加游戏难度。
存档功能:记录最高分并在游戏开始时显示。