python 贪吃蛇gui界面
时间: 2023-09-14 17:12:12 浏览: 122
以下是一个简单的Python贪吃蛇GUI界面的示例代码,使用了Tkinter库:
```python
import tkinter as tk
import random
# 定义常量
WIDTH = 500
HEIGHT = 500
SPEED = 100
GRID_SIZE = 20
class Snake(tk.Canvas):
def __init__(self):
super().__init__(width=WIDTH, height=HEIGHT, background="black", highlightthickness=0)
self.snake_positions = [(100, 100), (80, 100), (60, 100)]
self.food_position = self.set_new_food_position()
self.direction = "Right"
self.score = 0
self.create_objects()
self.bind_all("<Key>", self.on_key_press)
self.after(SPEED, self.perform_actions)
def create_objects(self):
self.create_text(
45, 12, text=f"Score {self.score}", tag="score", fill="#fff", font=("TkDefaultFont", 14)
)
for x_position, y_position in self.snake_positions:
self.create_rectangle(
x_position, y_position, x_position+GRID_SIZE, y_position+GRID_SIZE, fill="#fff", tag="snake"
)
self.create_rectangle(
self.food_position[0], self.food_position[1], self.food_position[0]+GRID_SIZE,
self.food_position[1]+GRID_SIZE, fill="#ff0000", tag="food"
)
def move_snake(self):
head_x_position, head_y_position = self.snake_positions[0]
if self.direction == "Right":
new_head_position = (head_x_position + GRID_SIZE, head_y_position)
elif self.direction == "Left":
new_head_position = (head_x_position - GRID_SIZE, head_y_position)
elif self.direction == "Down":
new_head_position = (head_x_position, head_y_position + GRID_SIZE)
elif self.direction == "Up":
new_head_position = (head_x_position, head_y_position - GRID_SIZE)
self.snake_positions = [new_head_position] + self.snake_positions[:-1]
for segment, position in zip(self.find_withtag("snake"), self.snake_positions):
self.coords(segment, position[0], position[1], position[0] + GRID_SIZE, position[1] + GRID_SIZE)
def perform_actions(self):
if self.check_collisions():
self.end_game()
return
self.check_food_collision()
self.move_snake()
self.after(SPEED, self.perform_actions)
def check_collisions(self):
head_x_position, head_y_position = self.snake_positions[0]
return (
head_x_position in (0, WIDTH)
or head_y_position in (20, HEIGHT)
or (head_x_position, head_y_position) in self.snake_positions[1:]
)
def on_key_press(self, e):
new_direction = e.keysym
all_directions = ("Up", "Down", "Left", "Right")
opposites = ({"Up", "Down"}, {"Left", "Right"})
if (
new_direction in all_directions
and {new_direction, self.direction} not in opposites
):
self.direction = new_direction
def check_food_collision(self):
if self.snake_positions[0] == self.food_position:
self.score += 1
self.snake_positions.append(self.snake_positions[-1])
self.create_rectangle(
*self.snake_positions[-1], self.snake_positions[-1][0]+GRID_SIZE, self.snake_positions[-1][1]+GRID_SIZE,
fill="#fff", tag="snake"
)
self.food_position = self.set_new_food_position()
self.coords(self.find_withtag("food"), self.food_position[0], self.food_position[1],
self.food_position[0]+GRID_SIZE, self.food_position[1]+GRID_SIZE)
score = self.find_withtag("score")
self.itemconfigure(score, text=f"Score: {self.score}", tag="score")
def set_new_food_position(self):
while True:
x_position = random.randint(0, (WIDTH-GRID_SIZE) // GRID_SIZE) * GRID_SIZE
y_position = random.randint(2, (HEIGHT-GRID_SIZE) // GRID_SIZE) * GRID_SIZE
food_position = (x_position, y_position)
if food_position not in self.snake_positions:
return food_position
def end_game(self):
self.delete(tk.ALL)
self.create_text(
self.winfo_width() / 2, self.winfo_height() / 2, text=f"Game over! You scored {self.score} points!", fill="#fff",
font=("TkDefaultFont", 24)
)
if __name__ == "__main__":
root = tk.Tk()
root.title("Snake")
root.resizable(False, False)
board = Snake()
board.pack()
root.mainloop()
```
这个示例代码使用了Canvas来绘制游戏界面,监听键盘事件来控制蛇的移动,检测碰撞并更新得分,以及生成新的食物。你可以根据需要进行修改和扩展。
阅读全文