用Python编写一个贪吃蛇
时间: 2023-11-16 14:06:58 浏览: 75
好的,下面是一个简单的贪吃蛇游戏代码示例:
```python
import pygame, random
# 初始化pygame
pygame.init()
# 游戏区域大小
width = 640
height = 480
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的初始位置
snake_block_size = 10
x1 = width / 2
y1 = height / 2
# 定义蛇移动的步长
x1_change = 0
y1_change = 0
# 定义食物的初始位置
foodx = round(random.randrange(0, width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block_size) / 10.0) * 10.0
# 定义蛇的长度
snake_list = []
snake_length = 1
# 绘制蛇的函数
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], snake_block_size, snake_block_size])
# 游戏结束的函数
def game_over():
font_style = pygame.font.SysFont(None, 50)
message = font_style.render('Game Over!', True, red)
screen.blit(message, [width / 2 - 100, height / 2 - 50])
# 游戏循环
game_over_flag = False
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断蛇是否碰到边界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over()
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制背景
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, red, [foodx, foody, snake_block_size, snake_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 block in snake_list[:-1]:
if block == snake_head:
game_over()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block_size) / 10.0) * 10.0
snake_length += 1
# 绘制蛇
draw_snake(snake_block_size, snake_list)
# 刷新游戏屏幕
pygame.display.update()
# 控制游戏帧率
clock.tick(20)
# 退出游戏
pygame.quit()
quit()
```
这个代码示例使用了pygame库来实现贪吃蛇游戏的绘制和游戏逻辑。运行代码后,就可以开始玩贪吃蛇游戏了。
阅读全文