贪吃蛇代码python运用pygame精灵
时间: 2024-12-29 18:22:39 浏览: 19
### Python Pygame 实现贪吃蛇游戏代码示例
为了更好地理解如何利用 `pygame.sprite` 来构建更复杂的游戏结构,在此提供一段基于精灵(Sprite)类实现的简化版贪吃蛇游戏代码片段。
#### 导入必要的模块并初始化环境变量
```python
import pygame
from random import randint
from pygame.locals import *
```
#### 定义全局常量
```python
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
BLOCK_SIZE = 20
SNAKE_COLOR = (0, 255, 0)
FOOD_COLOR = (255, 0, 0)
BG_COLOR = (0, 0, 0)
DIRECTION_UP = 'UP'
DIRECTION_DOWN = 'DOWN'
DIRECTION_LEFT = 'LEFT'
DIRECTION_RIGHT = 'RIGHT'
INITIAL_SNAKE_LENGTH = 3
```
#### 创建 Snake 类继承自 `pygame.sprite.Sprite`
通过定义一个名为 `SnakeSegment` 的子类来表示每一条蛇身上的节段,并让其继承自 `pygame.sprite.Sprite`。这使得可以方便地管理多个图形对象及其属性,如位置、颜色等。
```python
class Snake(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([BLOCK_SIZE, BLOCK_SIZE])
self.image.fill(SNAKE_COLOR)
self.rect = self.image.get_rect()
# 初始化蛇头的位置和其他参数
start_x = SCREEN_WIDTH // 2
start_y = SCREEN_HEIGHT // 2
self.body_segments = []
for i in range(INITIAL_SNAKE_LENGTH):
segment = Snake.Segment(start_x - i * BLOCK_SIZE, start_y)
self.add_segment(segment)
self.direction = DIRECTION_RIGHT
class Segment(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([BLOCK_SIZE, BLOCK_SIZE])
self.image.fill(SNAKE_COLOR)
self.rect = self.image.get_rect(topleft=(x,y))
def add_segment(self, segment):
"""向蛇体添加新的节段"""
self.body_segments.append(segment)
self.kill() # 移除旧的对象实例以便替换为新列表中的所有部分
for seg in reversed(self.body_segments):
self.add(seg)
```
#### 食物 Food 类同样也继承自 `pygame.sprite.Sprite`
用于随机生成食物的位置,并确保不会出现在当前蛇身上。
```python
class Food(pygame.sprite.Sprite):
def __init__(self, snake_body_positions):
super().__init__()
self.image = pygame.Surface([BLOCK_SIZE, BLOCK_SIZE])
self.image.fill(FOOD_COLOR)
while True:
pos = (
randint(BLOCK_SIZE, SCREEN_WIDTH-BLOCK_SIZE),
randint(BLOCK_SIZE, SCREEN_HEIGHT-BLOCK_SIZE)
)
if not any(s.rect.collidepoint(pos) for s in snake_body_positions):
break
self.rect = self.image.get_rect(center=pos)
```
#### 主函数 Main Function 中设置游戏循环逻辑
这里包含了事件监听器、碰撞检测机制以及屏幕刷新等功能。
```python
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), DOUBLEBUF | HWSURFACE)
pygame.display.set_caption('PyGame Snake Game with Sprites')
clock = pygame.time.Clock()
all_sprites_list = pygame.sprite.Group()
snake = Snake()
food = None
score = 0
all_sprites_list.add(snake)
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT or \
(event.type == KEYDOWN and event.key == K_ESCAPE):
running = False
elif event.type == KEYDOWN:
if event.key == K_w and snake.direction != DIRECTION_DOWN:
snake.direction = DIRECTION_UP
elif event.key == K_s and snake.direction != DIRECTION_UP:
snake.direction = DIRECTION_DOWN
elif event.key == K_a and snake.direction != DIRECTION_RIGHT:
snake.direction = DIRECTION_LEFT
elif event.key == K_d and snake.direction != DIRECTION_LEFT:
snake.direction = DIRECTION_RIGHT
# 更新蛇的状态
head_pos = list(snake.body_segments[-1].rect.topleft)
if snake.direction == DIRECTION_UP:
head_pos[1] -= BLOCK_SIZE
elif snake.direction == DIRECTION_DOWN:
head_pos[1] += BLOCK_SIZE
elif snake.direction == DIRECTION_LEFT:
head_pos[0] -= BLOCK_SIZE
elif snake.direction == DIRECTION_RIGHT:
head_pos[0] += BLOCK_SIZE
new_head = Snake.Segment(*head_pos)
snake.add_segment(new_head)
# 如果吃到食物,则增加长度;否则移除最后一个身体部位模拟移动效果
if not food or snake.body_segments[-1].rect.colliderect(food.rect):
score += 1
food = Food(snake.body_segments)
all_sprites_list.add(food)
else:
old_tail = snake.body_segments.pop(0)
all_sprites_list.remove(old_tail)
# 检查是否撞墙或咬到自己
if not (0 <= head_pos[0] < SCREEN_WIDTH and 0 <= head_pos[1] < SCREEN_HEIGHT)\
or any(head_pos == part.rect.topleft for part in snake.body_segments[:-1]):
running = False
screen.fill(BG_COLOR)
all_sprites_list.draw(screen)
pygame.display.update()
clock.tick(10 + score//5) # 动态调整速度随着得分提高而加快
print(f'Final Score: {score}')
pygame.quit()
if __name__ == '__main__':
main()
```
这段程序实现了基本的功能需求,即玩家可以通过键盘方向键控制贪吃蛇的方向变化,当它碰到墙壁或其他自身节点时结束游戏,并且每当成功吞噬掉一颗食物颗粒就会相应增长自己的体型同时提升分数[^1]。
阅读全文