生成食物 让蛇变长
1 生成一个矩形的食物
如果检测检测到蛇头与食物产生了碰撞 刷行一个新的食物 旧的食物会被覆盖
2 让蛇的身体变长
用到了if和else 如果跟食物有碰撞 就不删除蛇的末尾 如果没碰撞就删掉
3运用到了colliderect去检测与食物的碰撞
4运用了random去随机生成了食物的位置
import pygame
import random
pygame.init()
size = (600, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("生成食物, 让蛇变长")
clock = pygame.time.Clock()
body_size = 20
green = (0, 255, 0)#浅绿色
dark_grenn = (0, 204, 0)#深绿色
red = (255, 0, 0)#大红色
snake_body = [
pygame.Rect(100, 100, body_size, body_size),#头部
pygame.Rect(80, 100, body_size, body_size),
pygame.Rect(60, 100, body_size, body_size)
]#初始状态下蛇的身体有 3 节
# 1 让蛇往上移动 如果旧的头部坐标(x y)那么新的坐标(x, y-20)
# 2 让蛇向右移动 旧头部的坐标(x y)那么新的坐标(x+20, y)
# 3 往下移动 但坐标是(x, y) 新坐标(x, y+20)
# 4 往左移动 旧坐标是(x, y) 新坐标(x-20, y)
direction = 1 # 右:1 下;2 左:3 上:4
running = True
food = pygame.Rect(random.randint(10,500), random.randint(10, 380), body_size, body_size)
while running:
screen.fill((0, 0, 0))
pygame.draw.rect(screen, red, food)
events = pygame.event.get()#获取所有事件
for e in events:
if e.type == pygame.QUIT:#响应退出时间
running = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_UP:
direction = 4
if e.key == pygame.K_DOWN:
direction = 2
if e.key == pygame.K_LEFT:
direction = 3
if e.key == pygame.K_RIGHT:
direction = 1
if direction ==1:
nx = snake_body[0].x + body_size# 新头部的x坐标
ny = snake_body[0].y# 新头部的 y 坐标
if direction == 2:
nx = snake_body[0].x # 新头部的x坐标
ny = snake_body[0].y + body_size # 新头部的 y 坐标
if direction == 3:
nx = snake_body[0].x - body_size # 新头部的x坐标
ny = snake_body[0].y # 新头部的 y 坐标
if direction == 4:
nx = snake_body[0].x # 新头部的x坐标
ny = snake_body[0].y - body_size # 新头部的 y 坐标
nh = pygame.Rect(nx, ny, body_size, body_size) # 新头部的正方形
snake_body.insert(0, nh) # 插入新的头部
if nh.colliderect(food):#如果碰到食物, 就生成新的事物, 而且不删除尾巴
food = pygame.Rect(random.randint(10, 500 ), random.randint(10, 300), body_size, body_size)
else:
snake_body.pop() # 删除旧的尾巴
for body in snake_body:#遍历每一个矩形(body)
pygame.draw.rect(screen, green, body)#在screen上画出绿色的矩形
pygame.draw.rect(screen, dark_grenn, snake_body[0])#用深绿色画出头部矩形, 效果:覆盖刚出来的浅绿色头部
pygame.display.update()#刷新屏幕
clock.tick(2)
pygame.quit() #释放资源
浙公网安备 33010602011771号