贪吃蛇是怎么实现的,比如有5个结点的蛇,1,2,3,4,5,1是头,5是尾,结点的坐标用(x,y)表示,蛇要移动x,y怎么变化?没有转向的时候好理解,如果是在水平方向直着走,所有结点的横坐标x+1,如果是在垂直方向直着走,所有结点的纵坐标y+1。蛇不能像螃蟹一样横着走,如果蛇要拐弯,蛇其他结点的也是紧紧跟着蛇头转向。
蛇头转向,蛇身体的结点的坐标如何变化呢?比如蛇现在的位置从蛇头开始依次的坐标为(0,4),(0,3),(0,2),(0,1),(0,0),我们用一个数组来存这些坐标。蛇要向右转,进到第一象限,结点如何移动? 首先是头结点坐标变为(1,4),原先装(0,0)的位置被蛇头用掉了,原先其他的位置依次换成下一个位置就行了。妙啊!
许多年前我在思考这个问题的时候没学到循环数组。当时我的设想是,蛇头改变方向,记下改变位置的坐标和方向,其他结点到达这个位置时也改变方向,但这种做法只能让蛇折一次,就最多使蛇变成一个L形,不能让蛇变成S形,因为当蛇处于L形状时,又让蛇转向会,产生了两个转向点,但只记录了一个,导致bug产生。
附录:
实验数据
head,tail,x,y=0,0,50,60
head,tail,x,y=1,1,50,70
head,tail,x,y=2,2,50,80
head,tail,x,y=3,3,50,90
head,tail,x,y=4,4,50,100
head,tail,x,y=5,5,50,110
head,tail,x,y=6,6,50,120
head,tail,x,y=7,7,50,130
head,tail,x,y=8,8,50,140
head,tail,x,y=9,9,50,150
head,tail,x,y=10,10,50,160
head,tail,x,y=11,11,50,170
head,tail,x,y=12,12,50,180
head,tail,x,y=13,13,50,190
head,tail,x,y=14,14,50,200
head,tail,x,y=15,15,50,210
head,tail,x,y=16,16,50,220
head,tail,x,y=17,17,50,230
head,tail,x,y=18,18,50,240
head,tail,x,y=19,19,50,250
head,tail,x,y=0,0,50,260
head,tail,x,y=4,19,150,300
head,tail,x,y=5,0,160,300
head,tail,x,y=6,1,170,300
head,tail,x,y=7,2,180,300
key is down0
head,tail,x,y=8,3,180,-10
head,tail,x,y=9,4,180,0
head,tail,x,y=10,5,180,10
head,tail,x,y=11,6,180,20
head,tail,x,y=12,7,180,30
head,tail,x,y=13,8,180,40
head,tail,x,y=14,9,180,50
head,tail,x,y=15,10,180,60
head,tail,x,y=16,11,180,70
head,tail,x,y=17,12,180,80
key is right2
head,tail,x,y=18,13,190,80
head,tail,x,y=19,14,200,80
head,tail,x,y=0,15,210,80
key is down0
head,tail,x,y=1,16,210,90
head,tail,x,y=2,17,210,100
head,tail,x,y=3,18,210,110
head,tail,x,y=4,19,210,120
head,tail,x,y=5,0,210,130
head,tail,x,y=6,1,210,140
head,tail,x,y=7,2,210,150
head,tail,x,y=8,3,210,160
head,tail,x,y=9,4,210,170
head,tail,x,y=10,5,210,180
head,tail,x,y=11,6,210,190
key is left3
head,tail,x,y=12,6,200,190
head,tail,x,y=13,7,190,190
head,tail,x,y=14,8,180,190
head,tail,x,y=15,9,170,190
head,tail,x,y=16,10,160,190
head,tail,x,y=17,11,150,190
head,tail,x,y=18,12,140,190
head,tail,x,y=19,13,130,190
head,tail,x,y=0,14,120,190