python 实现贪吃蛇
使用键盘上下左右进行控制
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.colors import ListedColormap
import sys,argparse
import keyboard
cmap = ListedColormap(('purple','yellow'))
fig, ax = plt.subplots()
nmap = np.array(np.zeros([100,100]))
nmap[1,1]=1
img = ax.imshow(nmap,cmap=cmap,interpolation='nearest')
id = [2,[1,2],[2,2],[3,2]] #蛇 1左2右3上4下
nfood = 3
food = [] #食物
for i in range(nfood):
while True:
a = [np.random.randint(0,100),np.random.randint(0,100)]
if a in id:
continue
else:
food.append(a)
break
def up():
id[0] = 3
def down():
id[0] = 4
def left():
id[0] = 1
def right():
id[0] = 2
def move(id):
keyboard.add_hotkey('up', up)
keyboard.add_hotkey('down', down)
keyboard.add_hotkey('left', left)
keyboard.add_hotkey('right', right)
if id[len(id)-1] in food:
food.remove(id[len(id)-1])
while True:
a = [np.random.randint(0, 100), np.random.randint(0, 100)]
if a in id:
continue
else:
food.append(a)
break
else:
del id[1]
if id[0] == 1:
new = [id[len(id)-1][0],id[len(id)-1][1]-1]
id.append(new)
if id[0] == 2:
new = [id[len(id)-1][0],id[len(id)-1][1]+1]
id.append(new)
if id[0] == 3:
new = [id[len(id)-1][0]-1,id[len(id)-1][1]]
id.append(new)
if id[0] == 4:
new = [id[len(id)-1][0]+1,id[len(id)-1][1]]
id.append(new)
return id
def updata(frame,img,nmap,id):
print(id)
id = move(id)
nmap = np.zeros([100,100])
for i in id[1::]:
nmap[i[0],i[1]] = 1
for i in food:
nmap[i[0],i[1]] = 1
img.set_array(nmap)
return img,
ani = FuncAnimation(fig=fig,func=updata,fargs=(img,nmap,id),frames=10,blit=True)
plt.show()