用户:
淳朴的狼王蛛bbye查看:0 回复:1 评论:0 创建时间:2023-08-13T12:54:28
【作品展示】

【作品介绍】
贪吃蛇
【作品源代码】
import tkinter as tk
import random
class SnakeGame(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.canvas_width = 400
self.canvas_height = 400
self.delay = 100
self.direction = "Right"
self.canvas = tk.Canvas(
self.master, width=self.canvas_width, height=self.canvas_height)
self.canvas.pack()
self.snake = [(100, 100), (80, 100), (60, 100)]
self.food = self.create_food()
self.score = 0
self.master.bind("", self.on_key_press)
self.create_widgets()
def create_widgets(self):
self.start_button = tk.Button(
self.master, text="开始游戏", command=self.start_game)
self.start_button.pack()
self.score_label = tk.Label(self.master, text="得分: 0")
self.score_label.pack()
def start_game(self):
self.start_button.config(state=tk.DISABLED)
self.canvas.delete("all")
self.snake = [(100, 100), (80, 100), (60, 100)]
self.food = self.create_food()
self.score = 0
self.direction = "Right"
self.score_label.config(text="得分: 0")
self.move_snake()
def create_food(self):
x = random.randint(1, (self.canvas_width - 10) // 10) * 10
y = random.randint(1, (self.canvas_height - 10) // 10) * 10
return x, y
def move_snake(self):
x, y = self.snake[0]
if self.direction == "Up":
y -= 10
elif self.direction == "Down":
y += 10
elif self.direction == "Left":
x -= 10
elif self.direction == "Right":
x += 10
self.snake.insert(0, (x, y))
if x == self.food[0] and y == self.food[1]:
self.score += 10
self.score_label.config(text="得分: {}".format(self.score))
self.canvas.delete("food")
self.food = self.create_food()
else:
self.snake.pop()
self.draw_snake()
if self.check_collision():
self.game_over()
else:
self.master.after(self.delay, self.move_snake)
def draw_snake(self):
self.canvas.delete("snake")
for x, y in self.snake:
self.canvas.create_rectangle(
x, y, x+10, y+10, fill="green", tags="snake")
self.canvas.create_oval(
self.food[0], self.food[1], self.food[0]+10, self.food[1]+10, fill="red", tags="food")
self.canvas.tag_raise("food")
def check_collision(self):
x, y = self.snake[0]
if x < 0 or x >= self.canvas_width or y < 0 or y >= self.canvas_height or (x, y) in self.snake[1:]:
return True
else:
return False
def game_over(self):
self.canvas.create_text(self.canvas_width/2, self.canvas_height/2,
text="游戏结束", font=("Arial", 24), fill="red")
self.start_button.config(state=tk.NORMAL)
def on_key_press(self, event):
keysym = event.keysym
if keysym in ["Up", "Down", "Left", "Right"]:
if keysym == "Up" and self.direction != "Down":
self.direction = "Up"
elif keysym == "Down" and self.direction != "Up":
self.direction = "Down"
elif keysym == "Left" and self.direction != "Right":
self.direction = "Left"
elif keysym == "Right" and self.direction != "Left":
self.direction = "Right"
root = tk.Tk()
game = SnakeGame(root)
root.mainloop()
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn