用python编写一个贪吃蛇游戏
时间: 2023-08-28 13:07:01 浏览: 81
Python编写一个贪吃蛇游戏
当然可以!下面是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame
import random
# 游戏窗口的宽度和高度
WIDTH = 800
HEIGHT = 600
# 贪吃蛇每一节身体的大小
BODY_SIZE = 20
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 初始化pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
def show_score(score):
score_text = score_font.render("分数: " + str(score), True, WHITE)
screen.blit(score_text, [10, 10])
def draw_snake(snake_body):
for body_part in snake_body:
pygame.draw.rect(screen, GREEN, [body_part[0], body_part[1], BODY_SIZE, BODY_SIZE])
def game_loop():
game_over = False
game_quit = False
# 贪吃蛇初始位置
x = WIDTH / 2
y = HEIGHT / 2
# 贪吃蛇移动的速度
x_change = 0
y_change = 0
# 贪吃蛇身体列表,其中每个元素都是一个包含x和y坐标的元组
snake_body = []
snake_length = 1
# 食物的初始位置
food_x = round(random.randrange(0, WIDTH - BODY_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, HEIGHT - BODY_SIZE) / 20.0) * 20.0
while not game_quit:
while game_over:
screen.fill(BLACK)
game_over_text = font_style.render("游戏结束!", True, RED)
screen.blit(game_over_text, [WIDTH / 2 - 100, HEIGHT / 2 - 50])
show_score(snake_length - 1)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_quit = True
game_over = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_quit = True
game_over = False
if event.key == pygame.K_r:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_quit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -BODY_SIZE
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = BODY_SIZE
y_change = 0
elif event.key == pygame.K_UP:
y_change = -BODY_SIZE
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = BODY_SIZE
x_change = 0
# 更新贪吃蛇的位置
x += x_change
y += y_change
# 判断是否吃到食物
if x == food_x and y == food_y:
food_x = round(random.randrange(0, WIDTH - BODY_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, HEIGHT - BODY_SIZE) / 20.0) * 20.0
snake_length += 1
# 判断是否碰到边界或自身
if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
game_over = True
head = []
head.append(x)
head.append(y)
snake_body.append(head)
if len(snake_body) > snake_length:
del snake_body[0]
for body_part in snake_body[:-1]:
if body_part == head:
game_over = True
screen.fill(BLACK)
pygame.draw.rect(screen, RED, [food_x, food_y, BODY_SIZE, BODY_SIZE])
draw_snake(snake_body)
show_score(snake_length - 1)
pygame.display.flip()
clock.tick(15)
pygame.quit()
game_loop()
```
这个代码使用了pygame库来创建游戏窗口、处理键盘事件和绘制图形。贪吃蛇的身体由一个列表来表示,每一节身体都是一个包含x和y坐标的元组。游戏循环中,根据键盘事件来更新贪吃蛇的位置,判断是否吃到食物,以及判断是否碰到边界或自身。游戏窗口每帧都会被刷新,以显示最新的贪吃蛇位置和分数。
希望这个代码对你有帮助!如果有任何问题,请随时提问。
阅读全文