帮我用python 写一段 贪吃蛇的程序
时间: 2023-08-28 14:40:52 浏览: 74
以下是一个简单的贪吃蛇程序示例,你可以在Python环境中运行它:
```
import pygame
import random
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# 定义蛇类
class Snake:
def __init__(self):
self.body = [[100, 50], [90, 50], [80, 50]]
self.direction = "RIGHT"
self.score = 0
def move(self):
if self.direction == "RIGHT":
new_head = [self.body[0][0] + 10, self.body[0][1]]
elif self.direction == "LEFT":
new_head = [self.body[0][0] - 10, self.body[0][1]]
elif self.direction == "UP":
new_head = [self.body[0][0], self.body[0][1] - 10]
elif self.direction == "DOWN":
new_head = [self.body[0][0], self.body[0][1] + 10]
self.body.insert(0, new_head)
# 判断是否吃到食物
if self.body[0] == food.position:
food.generate()
self.score += 10
else:
self.body.pop()
def change_direction(self, direction):
if direction == "RIGHT" and not self.direction == "LEFT":
self.direction = "RIGHT"
elif direction == "LEFT" and not self.direction == "RIGHT":
self.direction = "LEFT"
elif direction == "UP" and not self.direction == "DOWN":
self.direction = "UP"
elif direction == "DOWN" and not self.direction == "UP":
self.direction = "DOWN"
def draw(self, screen):
for segment in self.body:
pygame.draw.rect(screen, white, pygame.Rect(segment[0], segment[1], 10, 10))
# 定义食物类
class Food:
def __init__(self):
self.position = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10]
def generate(self):
self.position = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10]
def draw(self, screen):
pygame.draw.rect(screen, red, pygame.Rect(self.position[0], self.position[1], 10, 10))
# 初始化游戏
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('贪吃蛇')
clock = pygame.time.Clock()
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_RIGHT:
snake.change_direction("RIGHT")
elif event.key == pygame.K_LEFT:
snake.change_direction("LEFT")
elif event.key == pygame.K_UP:
snake.change_direction("UP")
elif event.key == pygame.K_DOWN:
snake.change_direction("DOWN")
# 移动蛇
snake.move()
# 绘制界面
screen.fill(black)
snake.draw(screen)
food.draw(screen)
pygame.display.update()
# 判断是否游戏结束
if snake.body[0][0] < 0 or snake.body[0][0] > 490 or snake.body[0][1] < 0 or snake.body[0][1] > 490:
running = False
print("Game Over! Your score is:", snake.score)
for segment in snake.body[1:]:
if snake.body[0] == segment:
running = False
print("Game Over! Your score is:", snake.score)
# 控制游戏速度
clock.tick(10)
# 退出游戏
pygame.quit()
```
这段程序使用了pygame库来实现游戏界面的绘制和事件的处理,同时定义了Snake和Food两个类来实现贪吃蛇的功能,并通过循环来实现游戏的运行。
阅读全文