您的位置:首页 > 文旅 > 美景 > python 代码设计贪吃蛇

python 代码设计贪吃蛇

2024/12/22 17:50:35 来源:https://blog.csdn.net/2302_77382298/article/details/140361693  浏览:    关键词:python 代码设计贪吃蛇
代码:
# -*- codeing = utf-8 -*-
import tkinter as tk
import random
from tkinter import messageboxclass Snake:def __init__(self, master):self.master = masterself.master.title("Snake")# 创建画布self.canvas = tk.Canvas(self.master, width=400, height=400, bg="white")self.canvas.pack()# 初始化游戏数据self.snake = [(0, 0), (0, 1), (0, 2)]self.food = (5, 5)self.direction = "Right"self.score = 0# 绑定键盘事件self.master.bind("<Key>", self.on_key_press)# 开始游戏self.start_game()def start_game(self):# 绘制贪吃蛇和食物self.draw_snake()self.draw_food()# 更新游戏状态self.update_game()def draw_snake(self):# 清空画布self.canvas.delete("all")# 绘制贪吃蛇for x, y in self.snake:x1 = x * 20y1 = y * 20x2 = x1 + 20y2 = y1 + 20self.canvas.create_rectangle(x1, y1, x2, y2, fill="green")def draw_food(self):# 绘制食物x1 = self.food[0] * 20y1 = self.food[1] * 20x2 = x1 + 20y2 = y1 + 20self.canvas.create_oval(x1, y1, x2, y2, fill="red")def update_game(self):# 更新贪吃蛇位置head_x, head_y = self.snake[-1]if self.direction == "Left":new_head = (head_x - 1, head_y)elif self.direction == "Right":new_head = (head_x + 1, head_y)elif self.direction == "Up":new_head = (head_x, head_y - 1)else:new_head = (head_x, head_y + 1)self.snake.append(new_head)del self.snake[0]# 检查游戏是否结束if new_head[0] < 0 or new_head[0] >= 20 or new_head[1] < 0 or new_head[1] >= 20 or new_head in self.snake[:-1]:tk.messagebox.showinfo("Game Over", f"Score: {self.score}")return# 检查贪吃蛇是否吃掉食物if new_head == self.food:while True:food_x = random.randint(0, 19)food_y = random.randint(0, 19)if (food_x, food_y) not in self.snake:breakself.food = (food_x, food_y)tail_x, tail_y = self.snake[0]if self.direction == "Left":new_tail = (tail_x + 1, tail_y)elif self.direction == "Right":new_tail = (tail_x - 1, tail_y)elif self.direction == "Up":new_tail = (tail_x, tail_y + 1)else:new_tail = (tail_x, tail_y - 1)self.snake.insert(0, new_tail)self.score += 1# 绘制贪吃蛇和食物self.draw_snake()self.draw_food()# 定时更新游戏状态self.master.after(200, self.update_game)def on_key_press(self, event):if event.keysym in ["Left", "Right", "Up", "Down"]:self.direction = event.keysymif __name__ == "__main__":root = tk.Tk()snake = Snake(root)root.mainloop()

结果图:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com