用Python写一个贪吃蛇的代码
时间: 2024-04-25 12:04:19 浏览: 48
python 贪吃蛇代码
5星 · 资源好评率100%
当然可以!以下是一个简单的贪吃蛇代码,希望能帮助到你:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置标题
pygame.display.set_caption('贪吃蛇')
# 设置游戏帧率
clock = pygame.time.Clock()
FPS = 10
# 定义贪吃蛇的类
class Snake(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([20, 20])
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
self.speed_x = 20
self.speed_y = 0
self.length = 1
self.body = []
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
if self.rect.x > SCREEN_WIDTH:
self.rect.x = 0
elif self.rect.x < 0:
self.rect.x = SCREEN_WIDTH
elif self.rect.y > SCREEN_HEIGHT:
self.rect.y = 0
elif self.rect.y < 0:
self.rect.y = SCREEN_HEIGHT
self.body.insert(0, list((self.rect.x, self.rect.y)))
if len(self.body) > self.length:
self.body.pop()
def grow(self):
self.length += 1
# 定义食物的类
class Food(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([20, 20])
self.image.fill(RED)
self.rect = self.image.get_rect()
self.new_position()
def new_position(self):
self.rect.x = random.randrange(0, SCREEN_WIDTH, 20)
self.rect.y = random.randrange(0, SCREEN_HEIGHT, 20)
# 创建贪吃蛇和食物的对象
snake = Snake()
food = Food()
# 创建所有精灵组
all_sprites_group = pygame.sprite.Group()
all_sprites_group.add(snake)
all_sprites_group.add(food)
# 游戏主循环
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake.speed_x = -20
snake.speed_y = 0
elif event.key == pygame.K_RIGHT:
snake.speed_x = 20
snake.speed_y = 0
elif event.key == pygame.K_UP:
snake.speed_x = 0
snake.speed_y = -20
elif event.key == pygame.K_DOWN:
snake.speed_x = 0
snake.speed_y = 20
# 检测贪吃蛇是否吃到食物
if pygame.sprite.collide_rect(snake, food):
food.new_position()
snake.grow()
# 检测贪吃蛇是否撞到自己
for i in snake.body[1:]:
if snake.rect.x == i[0] and snake.rect.y == i[1]:
done = True
# 更新所有精灵组
all_sprites_group.update()
# 绘制所有精灵组
screen.fill(BLACK)
all_sprites_group.draw(screen)
# 更新屏幕
pygame.display.flip()
# 设置游戏帧率
clock.tick(FPS)
# 退出 pygame
pygame.quit()
```
阅读全文