写个贪吃蛇小程序的python代码
时间: 2023-12-11 10:04:01 浏览: 67
好的,以下是一个简单的贪吃蛇小程序的Python代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 600
window_height = 400
window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏刷新率
clock = pygame.time.Clock()
fps = 10
# 定义贪吃蛇
snake_block_size = 10
snake_speed = 15
snake_list = []
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_block_size, snake_block_size])
# 定义食物
food_block_size = 10
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
def draw_food():
pygame.draw.rect(window, red, [food_x, food_y, food_block_size, food_block_size])
# 定义游戏循环
game_over = False
x1 = window_width / 2
y1 = window_height / 2
x1_change = 0
y1_change = 0
snake_length = 1
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_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 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_over = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制游戏界面
window.fill(white)
draw_food()
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 x in snake_list[:-1]:
if x == snake_head:
game_over = True
draw_snake(snake_block_size, snake_list)
pygame.display.update()
# 判断蛇是否吃到食物
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
snake_length += 1
# 控制游戏刷新率
clock.tick(fps)
# 退出pygame
pygame.quit()
```
运行以上代码即可开始游戏。注意需要安装Pygame库才能正常运行。
阅读全文