python简单贪吃蛇代码
时间: 2023-07-03 10:20:19 浏览: 122
好的,下面是一个简单的贪吃蛇代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏界面大小
screen = pygame.display.set_mode((600, 600))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义贪吃蛇类
class Snake(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((20, 20))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = 20
self.direction = "right"
self.body = [(x, y), (x - 20, y), (x - 40, y)]
def update(self):
if self.direction == "right":
self.rect.x += self.speed
elif self.direction == "left":
self.rect.x -= self.speed
elif self.direction == "up":
self.rect.y -= self.speed
elif self.direction == "down":
self.rect.y += self.speed
self.body.insert(0, (self.rect.x, self.rect.y))
self.body.pop()
def grow(self):
self.body.append((self.rect.x, self.rect.y))
def change_direction(self, direction):
self.direction = direction
# 定义食物类
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.rect.x = random.randint(0, 29) * 20
self.rect.y = random.randint(0, 29) * 20
# 定义游戏结束函数
def game_over():
font = pygame.font.Font(None, 36)
text = font.render("Game Over", True, WHITE)
screen.blit(text, (250, 250))
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
# 创建贪吃蛇和食物对象
snake = Snake(300, 300)
food = Food()
# 创建精灵组
all_sprites = pygame.sprite.Group()
all_sprites.add(snake, food)
# 设置游戏循环
running = True
clock = pygame.time.Clock()
while running:
# 设置帧率
clock.tick(10)
# 处理事件
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.change_direction("up")
elif event.key == pygame.K_DOWN:
snake.change_direction("down")
elif event.key == pygame.K_LEFT:
snake.change_direction("left")
elif event.key == pygame.K_RIGHT:
snake.change_direction("right")
# 判断是否吃到食物
if snake.rect.colliderect(food.rect):
food.kill()
food = Food()
all_sprites.add(food)
snake.grow()
# 判断是否撞到自身或边界
if snake.rect.x < 0 or snake.rect.x > 580 or snake.rect.y < 0 or snake.rect.y > 580:
game_over()
for i in range(1, len(snake.body)):
if snake.rect.colliderect(pygame.Rect(snake.body[i], (20, 20))):
game_over()
# 更新精灵组
all_sprites.update()
# 绘制游戏界面
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display.flip()
# 退出pygame
pygame.quit()
```
这是一个比较简单的贪吃蛇游戏代码,它使用了pygame库来创建游戏界面和处理事件,通过定义Snake类和Food类来实现贪吃蛇和食物的功能,同时使用精灵组来管理所有的游戏元素。在游戏循环中,每帧都会检测是否吃到食物、是否撞到自身或边界等情况,并更新精灵组和绘制游戏界面。
阅读全文