请用python编写一段贪吃蛇游戏
下面是一个简单的Python代码,实现了一个基本的贪吃蛇游戏:
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏窗口大小
window_width = 800
window_height = 600
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇游戏")
# 游戏时钟
clock = pygame.time.Clock()
# 蛇头位置和速度
snake_size = 10
snake_x = window_width / 2
snake_y = window_height / 2
snake_x_change = 0
snake_y_change = 0
# 蛇身列表
snake_body = []
snake_length = 1
# 食物位置
food_x = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
# 游戏结束标志
game_over = False
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -snake_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_size
snake_x_change = 0
# 更新蛇头位置
snake_x += snake_x_change
snake_y += snake_y_change
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
snake_length += 1
# 更新蛇身列表
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
# 判断是否撞到墙或自己
if snake_x >= window_width or snake_x < 0 or snake_y >= window_height or snake_y < 0:
game_over = True
for segment in snake_body[:-1]:
if segment == snake_head:
game_over = True
# 刷新窗口背景
window.fill(black)
# 绘制蛇身和食物
for segment in snake_body:
pygame.draw.rect(window, white, [segment[0], segment[1], snake_size, snake_size])
pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size])
# 更新窗口显示
pygame.display.update()
# 控制游戏速度
clock.tick(10)
# 退出游戏
pygame.quit()
这段代码使用了pygame库来实现游戏窗口和绘制图形的功能。游戏窗口大小为800x600,蛇身和食物都是以10x10的方块表示。玩家可以通过方向键控制蛇的移动方向。游戏循环中不断更新蛇的位置,判断是否吃到食物或撞到墙或自己,然后绘制游戏窗口并更新显示。控制游戏速度的clock.tick(10)函数可以调整游戏的运行速度
原文地址: https://www.cveoy.top/t/topic/hS0p 著作权归作者所有。请勿转载和采集!