用python代码做一个贪吃蛇小程序
时间: 2024-06-09 09:09:03 浏览: 86
好的,以下是一个简单的贪吃蛇小程序的 Python 代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
WINDOW_SIZE = (WINDOW_WIDTH, WINDOW_HEIGHT)
# 设置游戏窗口标题
pygame.display.set_caption("Snake Game")
# 创建游戏窗口
screen = pygame.display.set_mode(WINDOW_SIZE)
# 设置游戏相关变量
clock = pygame.time.Clock()
snake_block_size = 10
snake_speed = 20
# 定义颜色常量
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 定义蛇的初始位置和长度
snake_x = WINDOW_WIDTH / 2
snake_y = WINDOW_HEIGHT / 2
snake_length = 1
snake_list = []
# 定义食物的初始位置
food_x = round(random.randrange(0, WINDOW_WIDTH - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - snake_block_size) / 10.0) * 10.0
# 定义字体
font_style = pygame.font.SysFont("bahnschrift", 25)
# 定义游戏结束函数
def game_over():
message = font_style.render("Game Over", True, red)
screen.blit(message, [WINDOW_WIDTH/3, WINDOW_HEIGHT/3])
pygame.display.update()
pygame.time.wait(2000)
# 游戏主循环
game_over_flag = False
while not game_over_flag:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
# 处理按键事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_x -= snake_block_size
elif keys[pygame.K_RIGHT]:
snake_x += snake_block_size
elif keys[pygame.K_UP]:
snake_y -= snake_block_size
elif keys[pygame.K_DOWN]:
snake_y += snake_block_size
# 判断蛇是否吃到食物,如果吃到则增加长度并重新生成食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, WINDOW_WIDTH - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - snake_block_size) / 10.0) * 10.0
snake_length += 1
# 更新蛇的位置和长度
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断蛇是否撞墙或撞到自己,如果是则游戏结束
for block in snake_list[:-1]:
if block == snake_head:
game_over_flag = True
if snake_x < 0 or snake_x >= WINDOW_WIDTH or snake_y < 0 or snake_y >= WINDOW_HEIGHT:
game_over_flag = True
# 绘制游戏画面
screen.fill(black)
pygame.draw.rect(screen, green, [food_x, food_y, snake_block_size, snake_block_size])
for block in snake_list:
pygame.draw.rect(screen, white, [block[0], block[1], snake_block_size, snake_block_size])
pygame.display.update()
# 控制游戏帧率
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
```
运行结果如下所示:
![snake_game](https://img-blog.csdn.net/20180522132057839?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhbmd5aW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/75)
阅读全文