用python写一个贪吃蛇小游戏
时间: 2023-12-07 22:57:52 浏览: 44
好的,以下是一个简单的贪吃蛇小游戏的Python代码,希望能帮到你:
```python
import pygame
import random
# 定义颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义方向常量
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
WINDOW_SIZE = (500, 500)
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("贪吃蛇小游戏")
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [(250, 250)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = ((cur[0] + (x * 10)), (cur[1] + (y * 10)))
if new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [(250, 250)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
def draw(self, surface):
for p in self.positions:
r = pygame.Rect((p[0], p[1]), (10, 10))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 定义食物类
class Food:
def __init__(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, 49) * 10, random.randint(0, 49) * 10)
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (10, 10))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.turn((0, -1))
elif event.key == pygame.K_DOWN:
snake.turn((0, 1))
elif event.key == pygame.K_LEFT:
snake.turn((-1, 0))
elif event.key == pygame.K_RIGHT:
snake.turn((1, 0))
# 移动贪吃蛇
snake.move()
# 检查是否吃到食物
if snake.get_head_position() == food.position:
snake.length += 1
food.randomize_position()
# 绘制游戏界面
screen.fill(WHITE)
snake.draw(screen)
food.draw(screen)
pygame.display.update()
# 控制帧率
clock.tick(10)
# 退出 Pygame
pygame.quit()
```
阅读全文