tkinter贪吃虫程序编写
时间: 2024-04-23 14:18:46 浏览: 126
一个python tkinter 贪吃蛇(有AI)
4星 · 用户满意度95%
Tkinter是Python的一个标准GUI库,可以用于创建图形用户界面。贪吃虫程序是一个经典的小游戏,玩家控制一个虫子在屏幕上移动并吃掉食物,每吃到一个食物,虫子的身体会变长一节。下面是一个简单的Tkinter贪吃虫程序的编写示例:
```python
import tkinter as tk
import random
class SnakeGame(tk.Canvas):
def __init__(self, master):
super().__init__(master, width=400, height=400, background="black")
self.snake_body = [(100, 100), (90, 100), (80, 100)]
self.food = self.create_food()
self.direction = "Right"
self.bind_all("<Key>", self.on_key_press)
self.score = 0
self.speed = 150
self.game_loop()
def create_food(self):
while True:
x = random.randint(1, 39) * 10
y = random.randint(1, 39) * 10
if (x, y) not in self.snake_body:
return self.create_oval(x, y, x+10, y+10, fill="red")
def move(self):
head_x, head_y = self.snake_body[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:
new_head = (head_x + 10, head_y)
self.snake_body.insert(0, new_head)
if self.food in self.snake_body:
self.score += 1
self.delete(self.food)
self.food = self.create_food()
if self.score % 5 == 0:
self.speed -= 10
else:
self.delete(self.snake_body.pop())
if (new_head[0] < 0 or new_head[0] >= 400 or
new_head[1] < 0 or new_head[1] >= 400 or
new_head in self.snake_body[1:]):
self.game_over()
else:
self.create_rectangle(new_head[0], new_head[1],
new_head[0]+10, new_head[1]+10,
fill="green")
def game_loop(self):
self.move()
if not self.game_over_flag:
self.after(self.speed, self.game_loop)
def on_key_press(self, event):
keysyms = event.keysym.lower()
if keysyms in ["up", "down", "left", "right"]:
opposite_directions = {"Up": "Down", "Down": "Up",
"Left": "Right", "Right": "Left"}
if keysyms != opposite_directions[self.direction]:
self.direction = keysyms
def game_over(self):
self.delete(tk.ALL)
self.create_text(self.winfo_width() / 2, self.winfo_height() / 2,
text=f"Game Over! Score: {self.score}",
fill="white", font=("Courier", 20), justify=tk.CENTER)
self.game_over_flag = True
root = tk.Tk()
root.title("Snake Game")
root.resizable(False, False)
game = SnakeGame(root)
game.pack()
root.mainloop()
```
这个示例代码使用了Tkinter的Canvas组件来创建游戏界面,通过继承Canvas类并重写相关方法来实现贪吃虫游戏的逻辑。玩家可以通过方向键控制虫子的移动方向,当虫子吃到食物时,得分增加并且速度加快。当虫子碰到边界或者自己的身体时,游戏结束。
阅读全文