怎么给贪吃蛇加固定的障碍物?试过好多次,障碍物都是一闪而过和游戏分离开了,怎么让障碍物和游戏融合地较好?(解决后另有打赏)
import turtle as t
import copy as c
import random as r
#初始化,模拟蛇,就是一个方块列表
snake=[[0,0],[0,10],[0,20]]
aim=[0,10] #移动目标
food=[r.randrange(-25,25)*10,r.randrange(-25,25)*10]
time=300
#动态调整移动的方向
def change(x,y):
aim[0]=x
aim[1]=y#画出方块
def square(x,y,size,color):
t.penup()
t.goto(x,y)
t.pendown()
t.color(color) #设置颜色
t.begin_fill() #渲染
for i in range(4):
t.forward(size)
t.left(90)
t.end_fill()#渲染
#判断边界
def inside(head):
if head[0]>250:
head[0]-=250*2
elif head[0]<-250:
head[0]+=250*2
if head[1]>250:
head[1]-=250*2
elif head[1]<-250:
head[1]+=250*2
return head
#移动--解析:头部添加方块,尾巴消除一个方块
# 最后画的最上面的方块--设定为头部
def move_snake():
head=c.deepcopy(snake[-1]) #复制一份头部坐标
#确定方向
head=[head[0]+aim[0],head[1]+aim[1]] #确定新头的坐标
if head in snake:
print('game over')
square(head[0],head[1],10,'yellow')
#边界判断
inside(head)
#移动蛇
if head==food:
food[0]=r.randrange(-24,24)*10
food[1]=r.randrange(-24,24)*10
else:
snake.pop(0) #去尾巴
snake.append(head) #添加头
#删除之前的动画
t.clear()
#画食物
square(food[0],food[1],10,'red')
#障碍
for i in snake:
square(i[0],i[1],10,'black')
t.update() #刷新
t.ontimer(move_snake,time) #递归
t.tracer(False)#除去动画效果
t.hideturtle() #隐藏箭头
#监听键盘
t.listen()
t.onkey(lambda :change(0,10),'w')
t.onkey(lambda :change(0,-10),'s')
t.onkey(lambda :change(10,0),'d')
t.onkey(lambda :change(-10,0),'a')
#设定屏幕大小
t.setup(500,500)
#运行
move_snake()
t.done() #暂停屏幕