pygame小游戏贪吃蛇源代码
时间: 2024-07-13 10:01:12 浏览: 152
pygame是一个流行的Python库,用于创建2D游戏,其中包括著名的贪吃蛇游戏。编写一个基本的贪吃蛇游戏的源代码可能会包含以下几个主要部分:
1. **导入模块**:
```python
import pygame
import sys
```
2. **初始化pygame**:
```python
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
```
3. **定义贪吃蛇类 (Snake)**:
```python
class Snake:
def __init__(self):
self.body = [[100, 100], [90, 100], [80, 100]] # 初始位置和长度
self.direction = [0, 1] # 默认向右移动
def move(self):
new_head = [self.body + self.direction, self.body + self.direction]
self.body.insert(0, new_head) # 在头部添加新位置
if new_head in self.body[1:]:
game_over = True # 如果头撞到身体,则游戏结束
else:
self.body.pop() # 移除蛇尾
return not game_over
```
4. **绘制贪吃蛇和食物(Food)**:
```python
def draw_snake(screen, snake):
for pos in snake.body:
pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(pos, pos, 10, 10))
def place_food(snake):
while True:
food_pos = [random.randint(0, screen.get_width() // 10) * 10, random.randint(0, screen.get_height() // 10) * 10]
if food_pos not in snake.body:
break
return food_pos
```
5. **主游戏循环**:
```python
snake = Snake()
food_pos = place_food(snake)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_UP] and snake.direction != [0, -1]:
snake.direction = [-1, 0]
elif keys_pressed[pygame.K_DOWN] and snake.direction != [0, 1]:
snake.direction = [1, 0]
elif keys_pressed[pygame.K_LEFT] and snake.direction != [1, 0]:
snake.direction = [0, 1]
elif keys_pressed[pygame.K_RIGHT] and snake.direction != [-1, 0]:
snake.direction = [0, -1]
snake.move()
screen.fill((0, 0, 0)) # 清屏
draw_snake(screen, snake)
draw_rect(screen, food_pos, (255, 0, 0)) # 绘制食物
pygame.display.flip()
clock.tick(10) # 控制帧率
```
完整代码会包括更多的细节,如碰撞检测、得分计算等。如果你想深入了解整个源代码,请查阅相关的pygame教程或搜索在线示例。
阅读全文