我一直觉得贪吃蛇游戏中食物都是静止不动,等着蛇来吃掉有些不太合理,毕竟蛇一般吃的都是老鼠,鸡等活物,它们怎么可能坐以待毙一动不动的等着蛇来吃掉呢,所以我决定更改一下贪吃蛇的代码,让食物可以自由活动,我们需要重新定义食物模块,我们假设贪吃蛇吃的是鸡,这首先定义一个鸡模块,同样的,鸡也是由列表组成的:
class chichken(object):
def __init__(self): self.item=[(40,20),(40,19)]
相同的,当蛇吃鸡后,鸡同样需要重新生成,这端代码也是不变的:
def update(self,screen,enlarge,snack):
if enlarge:
self.item[0]=np.random.randint(1,BOARDWIDTH-2),np.random.randint(1,BOARDHEIGHT-2)
while self.item in snack.item:
self.item[0]=np.random.randint(1, BOARDWIDTH - 2), np.random.randint(1, BOARDHEIGHT - 2)
self._draw(screen,self.item[0][0],self.item[0][1])
那么我们如何能让小鸡自己动起来呢,参照蛇移动的原理,笔者同样定义了一个self.y和self.x,作为小鸡的朝向,利用随机函数,使得self.y和self.x在-1到1之间随机选取,这样,便达到让小鸡自动的往四个方向随机移动的目的了:最后利用pygame画圆的功能pygame.draw.circle,,我们便有了一只活蹦乱跳的小鸡了。
def chicken_move(self):
x=1
y=1
self.x=1
self.y=1
if self.x*x>0 and self.y*y>0:
self.x = random.randint(-1, 1)
self.y = random.randint(-1, 1)
x = self.x
y = self.y
self.item.pop()
chichken = (self.item[0][0] + self.x, self.item[0][1] + self.y)
if chichken[0]==BOARDWIDTH or chichken[0]==0 or chichken[1]==BOARDHEIGHT or chichken[1]==0:
chichken = np.random.randint(1, BOARDWIDTH - 2), np.random.randint(1, BOARDHEIGHT - 2)
self.item.insert(0, chichken)
def _draw(self,screen,q,w):
color=255,255,0
radius=8
width=8
position=10+20*q,10+20*w
pygame.draw.circle(screen,color,position,radius,width)