使用python语言设计贪吃蛇游戏
时间: 2023-10-25 14:10:16 浏览: 73
基于python设计的贪吃蛇游戏
5星 · 资源好评率100%
好的,下面是一个简单的贪吃蛇游戏的Python代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 500
window_height = 500
game_display = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption('贪吃蛇')
# 设置颜色变量
black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 0, 0)
green = (0, 200, 0)
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置蛇的初始位置和长度
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
# 设置食物初始位置
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
# 定义蛇的移动函数
def snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, green, [x[0], x[1], snake_block_size, snake_block_size])
# 运行游戏循环
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
# 获取键盘按键
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x_change = -snake_block_size
y_change = 0
elif keys[pygame.K_RIGHT]:
x_change = snake_block_size
y_change = 0
elif keys[pygame.K_UP]:
x_change = 0
y_change = -snake_block_size
elif keys[pygame.K_DOWN]:
x_change = 0
y_change = snake_block_size
# 蛇头的位置
snake_head = []
snake_head.append(food_x)
snake_head.append(food_y)
# 将蛇头添加至蛇的列表中
snake_list.append(snake_head)
# 如果蛇的长度大于设定值,则删除蛇尾以保持长度不变
if len(snake_list) > snake_length:
del snake_list[0]
# 如果蛇头与食物重合,则增加长度,重新生成食物位置
if food_x == snake_head[0] and food_y == snake_head[1]:
snake_length += 1
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
# 如果蛇头与边界发生碰撞,则游戏结束
if snake_head[0] >= window_width or snake_head[0] < 0 or snake_head[1] >= window_height or snake_head[1] < 0:
game_exit = True
# 如果蛇头与蛇身发生碰撞,则游戏结束
for x in snake_list[:-1]:
if x == snake_head:
game_exit = True
# 设置背景颜色
game_display.fill(black)
# 绘制食物
pygame.draw.rect(game_display, red, [food_x, food_y, snake_block_size, snake_block_size])
# 绘制蛇
snake(snake_block_size, snake_list)
# 更新游戏窗口
pygame.display.update()
# 控制游戏帧率
clock.tick(snake_speed)
# 结束pygame
pygame.quit()
# 退出程序
quit()
```
以上是一个基本的贪吃蛇游戏代码示例,你可以根据需要进行修改和优化。
阅读全文