下面代码是一个使用Pygame库编写的贪吃蛇小游戏。
import pygame
import random
import copy
# 初始化蛇移动的位置
move_up = True
move_down = False
move_left = False
move_right = False
# 1.1游戏初始化
pygame.init() # 初始化Pygame
clock = pygame.time.Clock() # 创建Pygame时钟对象
pygame.display.set_caption("贪吃蛇小游戏") # 设置窗口标题
screen = pygame.display.set_mode((500, 500)) # 创建游戏窗口
# 随机生成食物坐标
food_x = random.randint(0, 490)
food_y = random.randint(0, 490)
food_point = [food_x, food_y]
# 蛇的初始位置和大小
snake_list = [
[10, 10]
]
# 控制贪吃蛇的速度
snake_speed = 10 # 调整这个值来改变速度
# 1.2游戏主循环
running = True
while running:
for event in pygame.event.get(): # 遍历所有事件
if event.type == pygame.QUIT: # 如果点击关闭窗口按钮,则退出游戏
running = False
elif event.type == pygame.KEYDOWN: # 如果有按键按下事件
if event.key == pygame.K_UP: # 如果按下上方向键
move_up, move_down, move_left, move_right = True, False, False, False
elif event.key == pygame.K_DOWN: # 如果按下下方向键
move_up, move_down, move_left, move_right = False, True, False, False
elif event.key == pygame.K_LEFT: # 如果按下左方向键
move_up, move_down, move_left, move_right = False, False, True, False
elif event.key == pygame.K_RIGHT: # 如果按下右方向键
move_up, move_down, move_left, move_right = False, False, False, True
clock.tick(snake_speed) # 控制贪吃蛇的速度
screen.fill([255, 255, 255]) # 填充背景色为白色
# 绘制食物
food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0)
snake_rect = []
for point in snake_list:
# 绘制蛇的每个部分
snake_rect.append(pygame.draw.circle(screen, [255, 0, 0], point, 5, 0))
# 如果蛇头碰到食物,则吃掉食物,并重新生成食物
if food_rect.collidepoint(point):
snake_list.append(food_point)
food_point = [random.randint(0, 490), random.randint(0, 490)]
food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0)
break
# 移动蛇的位置
pos = len(snake_list) - 1
while pos > 0:
snake_list[pos] = copy.deepcopy(snake_list[pos - 1])
pos -= 1
# 根据移动方向更新蛇头位置
if move_right:
snake_list[pos][0] += 10
if snake_list[pos][0] > 500:
snake_list[pos][0] = 0
if move_up:
snake_list[pos][1] -= 10
if snake_list[pos][1] < 0:
snake_list[pos][1] = 500
if move_down:
snake_list[pos][1] += 10
if snake_list[pos][1] > 500:
snake_list[pos][1] = 0
if move_left:
snake_list[pos][0] -= 10
if snake_list[pos][0] < 0:
snake_list[pos][0] = 500
# 如果蛇头碰到身体,则结束游戏
head_rect = snake_rect[0]
count = len(snake_rect)
while count > 1:
if head_rect.colliderect(snake_rect[count - 1]):
running = False
count -= 1
pygame.display.update() # 更新屏幕显示
pygame.quit() # 退出Pygame
1.这段代码首先初始化了Pygame库,并设置了游戏窗口的大小和标题。
2.然后,它创建了一个食物,并初始化了蛇的位置和速度。
3.在游戏主循环中,它监听用户的按键事件,根据按键改变蛇的移动方向。
4.蛇的每个部分都会按照蛇头的移动方向移动,蛇头会吃掉食物,并生成新的食物。
5.如果蛇头碰到身体,则游戏结束。
效果如下:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/101019.html