帮我生成一段贪吃蛇代码,要求可以在Python3上运行
时间: 2024-05-15 18:17:30 浏览: 7
好的,以下是一段Python3的贪吃蛇代码:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
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("Snake")
# 设置时钟对象
clock = pygame.time.Clock()
# 定义方块大小
BLOCK_SIZE = 20
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义蛇类
class Snake(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([BLOCK_SIZE, BLOCK_SIZE])
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 定义食物类
class Food(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([BLOCK_SIZE, BLOCK_SIZE])
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, SCREEN_WIDTH-BLOCK_SIZE, BLOCK_SIZE)
self.rect.y = random.randrange(0, SCREEN_HEIGHT-BLOCK_SIZE, BLOCK_SIZE)
# 定义主函数
def main():
# 初始化游戏
snake_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
food_list = pygame.sprite.Group()
snake = Snake(300, 300)
snake_list.add(snake)
all_sprites_list.add(snake)
food = Food()
food_list.add(food)
all_sprites_list.add(food)
# 定义初始方向
direction = 'right'
# 定义初始分数
score = 0
# 游戏循环
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:
direction = 'left'
elif event.key == pygame.K_RIGHT:
direction = 'right'
elif event.key == pygame.K_UP:
direction = 'up'
elif event.key == pygame.K_DOWN:
direction = 'down'
# 移动蛇头
if direction == 'right':
snake.rect.x += BLOCK_SIZE
elif direction == 'left':
snake.rect.x -= BLOCK_SIZE
elif direction == 'up':
snake.rect.y -= BLOCK_SIZE
elif direction == 'down':
snake.rect.y += BLOCK_SIZE
# 如果蛇头碰到边界或者碰到自己,结束游戏
if snake.rect.x < 0 or snake.rect.y < 0 or snake.rect.x > SCREEN_WIDTH-BLOCK_SIZE or snake.rect.y > SCREEN_HEIGHT-BLOCK_SIZE or pygame.sprite.spritecollide(snake, snake_list, False):
done = True
# 如果蛇头碰到食物,分数加一,重新生成食物
if pygame.sprite.spritecollide(snake, food_list, True):
score += 1
food = Food()
food_list.add(food)
all_sprites_list.add(food)
# 删除蛇尾
if len(snake_list) > score:
snake_tail = snake_list.sprites()[0]
snake_list.remove(snake_tail)
all_sprites_list.remove(snake_tail)
# 添加蛇头
snake_list.add(snake)
all_sprites_list.add(snake)
# 清除屏幕
screen.fill(WHITE)
# 绘制所有精灵
all_sprites_list.draw(screen)
# 绘制分数
text = font.render("Score: {}".format(score), True, BLACK)
screen.blit(text, [10, 10])
# 更新屏幕
pygame.display.flip()
# 设置帧率
clock.tick(10)
# 退出pygame
pygame.quit()
# 调用主函数
if __name__ == "__main__":
main()
```
希望对你有帮助。