python做一个贪食蛇的游戏
时间: 2023-05-24 16:02:21 浏览: 109
Python编写一个贪吃蛇游戏
好的,下面是 Python 实现贪食蛇游戏的示例代码:
```python
import pygame
import random
pygame.init()
# 游戏窗口大小
width = 800
height = 600
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
# 创建窗口
display = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪食蛇")
# 定义贪食蛇的头和身体
block_size = 10
snake_list = []
snake_length = 1
# 定义食物位置
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0
# 定义贪食蛇移动方向
direction = "right"
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 显示分数
def show_score(score):
score_text = font_style.render("得分: " + str(score), True, blue)
display.blit(score_text, [0, 0])
# 显示贪食蛇
def draw_snake(snake_list, block_size):
for x in snake_list:
pygame.draw.rect(display, black, [x[0], x[1], block_size, block_size])
# 开始游戏
def game_loop():
game_over = False
game_close = False
# 贪食蛇的初始位置
x1 = width / 2
y1 = height / 2
# 贪食蛇的移动速度
x1_change = 0
y1_change = 0
# 记录得分
score = 0
global direction
# 游戏循环
while not game_over:
# 游戏结束
while game_close == True:
# 显示得分
show_score(score)
# 提示游戏结束
message = font_style.render("游戏结束,按 Q 退出,按 C 重新开始", True, red)
display.blit(message, [(width / 2) - 150, (height / 2) - 50])
pygame.display.update()
# 处理按键事件
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
# 处理键盘事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = "left"
x1_change = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
direction = "right"
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
direction = "up"
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
direction = "down"
y1_change = block_size
x1_change = 0
# 边界处理
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
# 更新贪食蛇位置
x1 += x1_change
y1 += y1_change
# 显示背景
display.fill(white)
# 显示食物
pygame.draw.rect(display, blue, [food_x, food_y, block_size, block_size])
# 更新贪食蛇的身体
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 处理贪食蛇吃到食物的情况
for snake in snake_list[:-1]:
if snake == snake_head:
game_close = True
# 更新得分
show_score(score)
# 显示贪食蛇
draw_snake(snake_list, block_size)
pygame.display.update()
# 当贪食蛇吃到食物时,更新食物位置,并增加贪食蛇长度
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0
snake_length += 1
score += 10
# 控制贪食蛇移动速度
pygame.time.Clock().tick(20)
# 退出游戏
pygame.quit()
quit()
game_loop()
```
这是一个比较简单的贪食蛇游戏实现,利用 pygame 库实现图形界面。在游戏中,贪食蛇会自动移动,玩家通过按键控制贪食蛇的移动方向,贪食蛇吃到食物后会增加长度,当贪食蛇碰到墙壁或自身时,游戏结束,并显示得分。
阅读全文