使用python与pygame,编写一个贪吃蛇游戏
时间: 2023-12-10 08:39:39 浏览: 86
基于python+PyGame的贪吃蛇游戏
好的,下面是一个简单的贪吃蛇游戏的代码示例:
```python
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义方向
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 初始化pygame模块
pygame.init()
# 设置窗口大小和标题
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 设置时钟
clock = pygame.time.Clock()
# 加载字体
font = pygame.font.SysFont(None, 25)
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.size = 3 # 初始长度
self.direction = RIGHT # 初始方向
self.body = [(100, 100), (90, 100), (80, 100)] # 初始坐标
def move(self):
if self.direction == UP:
new_head = (self.body[0][0], self.body[0][1] - 10)
elif self.direction == DOWN:
new_head = (self.body[0][0], self.body[0][1] + 10)
elif self.direction == LEFT:
new_head = (self.body[0][0] - 10, self.body[0][1])
elif self.direction == RIGHT:
new_head = (self.body[0][0] + 10, self.body[0][1])
self.body.insert(0, new_head)
if len(self.body) > self.size:
self.body.pop()
def change_direction(self, direction):
if direction == UP and self.direction != DOWN:
self.direction = UP
elif direction == DOWN and self.direction != UP:
self.direction = DOWN
elif direction == LEFT and self.direction != RIGHT:
self.direction = LEFT
elif direction == RIGHT and self.direction != LEFT:
self.direction = RIGHT
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, [x, y, 10, 10])
# 定义食物类
class Food:
def __init__(self):
self.pos = (0, 0)
self.color = RED
self.randomize_pos()
def randomize_pos(self):
self.pos = (random.randint(0, screen_width - 10) // 10 * 10,
random.randint(0, screen_height - 10) // 10 * 10)
def draw(self):
pygame.draw.rect(screen, self.color, [self.pos[0], self.pos[1], 10, 10])
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
game_over = False
while not game_over:
# 事件循环
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
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)
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == food.pos:
snake.size += 1
food.randomize_pos()
# 判断是否撞到墙或自己的身体
if snake.body[0][0] < 0 or snake.body[0][0] >= screen_width or \
snake.body[0][1] < 0 or snake.body[0][1] >= screen_height or \
snake.body[0] in snake.body[1:]:
game_over = True
# 绘制屏幕
screen.fill(BLACK)
snake.draw()
food.draw()
# 绘制分数
score_text = font.render("Score: {}".format(snake.size - 3), True, WHITE)
screen.blit(score_text, [10, 10])
# 刷新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(10)
# 退出游戏
pygame.quit()
```
这个示例代码使用了pygame模块来实现游戏的绘制和事件处理,同时定义了一个Snake类和一个Food类来管理贪吃蛇和食物的状态。在游戏循环中,每帧都会处理用户输入、移动贪吃蛇、判断是否吃到食物或撞到墙或身体、绘制屏幕和分数等操作。最后,在游戏结束时退出pygame模块。
阅读全文