用python设计贪吃蛇游戏
时间: 2023-08-15 11:36:22 浏览: 85
基于python设计的贪吃蛇游戏
5星 · 资源好评率100%
好的,这是一个关于贪吃蛇游戏的问题,我已经记下来了。下面是一个简单的实现:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕尺寸
size = (600, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Snake")
# 定义方块的大小
block_size = 10
# 定义游戏结束的标志
game_over = False
# 定义蛇的初始位置和方向
snake_pos = [[size[0] / 2, size[1] / 2]]
snake_direction = "right"
# 定义食物的初始位置
food_pos = [random.randrange(0, size[0], block_size), random.randrange(0, size[1], block_size)]
# 定义蛇的移动函数
def move_snake(snake_pos, snake_direction):
if snake_direction == "right":
new_pos = [snake_pos[0][0] + block_size, snake_pos[0][1]]
elif snake_direction == "left":
new_pos = [snake_pos[0][0] - block_size, snake_pos[0][1]]
elif snake_direction == "up":
new_pos = [snake_pos[0][0], snake_pos[0][1] - block_size]
elif snake_direction == "down":
new_pos = [snake_pos[0][0], snake_pos[0][1] + block_size]
snake_pos.insert(0, new_pos)
snake_pos.pop()
return snake_pos
# 定义游戏结束函数
def game_over_screen():
font = pygame.font.SysFont(None, 50)
text = font.render("Game Over", True, WHITE)
screen.blit(text, [size[0] / 2 - 80, size[1] / 2 - 25])
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and snake_direction != "left":
snake_direction = "right"
elif event.key == pygame.K_LEFT and snake_direction != "right":
snake_direction = "left"
elif event.key == pygame.K_UP and snake_direction != "down":
snake_direction = "up"
elif event.key == pygame.K_DOWN and snake_direction != "up":
snake_direction = "down"
# 移动蛇
snake_pos = move_snake(snake_pos, snake_direction)
# 检查是否吃到食物
if snake_pos[0] == food_pos:
food_pos = [random.randrange(0, size[0], block_size), random.randrange(0, size[1], block_size)]
snake_pos.append(snake_pos[-1])
# 检查是否碰壁或者撞到自己
if snake_pos[0][0] < 0 or snake_pos[0][0] > size[0] - block_size or snake_pos[0][1] < 0 or snake_pos[0][1] > size[1] - block_size:
game_over_screen()
game_over = True
for i in range(1, len(snake_pos)):
if snake_pos[0] == snake_pos[i]:
game_over_screen()
game_over = True
# 绘制屏幕
screen.fill(BLACK)
pygame.draw.rect(screen, GREEN, [food_pos[0], food_pos[1], block_size, block_size])
for pos in snake_pos:
pygame.draw.rect(screen, WHITE, [pos[0], pos[1], block_size, block_size])
pygame.display.update()
# 设置游戏帧率
clock = pygame.time.Clock()
clock.tick(10)
# 退出游戏
pygame.quit()
```
在这个实现中,我们使用了`pygame`库来创建游戏窗口和处理游戏事件,同时实现了蛇的移动、食物的生成、游戏结束的判断等逻辑。在游戏循环中,我们不断地更新蛇的位置,检查是否吃到食物或者碰壁或者撞到自己,然后绘制屏幕并且设置游戏帧率,以保证游戏的流畅性。
阅读全文