前面生成了运动、生成食物的算法。这次增加吃食物的算法:
1、创建生成食物的标志build_food_state,在主程序中判断,如果标志需要创建食物,则生成。如果食物还存在,就不生成食物。
2、吃到食物的判断:如果生成下一个食物的坐标数组与食物的坐标数组相等,则不消除最后尾的块,同时更新生成食物的标志为真。如果没有吃到食物,则消除尾部块。
if disp_List[-1] == disp_food:
buid_food_state = 1
else:
del disp_List[0]
整体程序如下:
import os
import tqs1
import tqmain
import tqmath
myItem =[[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]]
state = True
disp_List = [[0,0]]
disp_food = []
time_state = 0
move_state = 0
buid_food_state = 1
def disp_tq():
global state,myItem
state = False
mystr =[]
for j in range(0,6):
strit = ''.join(str(i) for i in myItem[j])
mystr.append(strit)
print(mystr)
value = ','.join(mystr)
tqmain.matri_strfill_display(value)
state = False
def get_key():
global state,move_state
key_value1 = tqs1.key_get_status(2)
if key_value1 == 0:
move_state = move_state +1
if move_state > 3:
move_state = 0
print("KeyB changed,move_state:" + str(move_state))
state = True
key_value2 = tqs1.key_get_status(1)
if key_value2 == 0:
move_state = move_state -1
if move_state < 0:
move_state = 3
print("KeyA changed,move_state:" + str(move_state))
state = True
def move():
global move_state,myItem,disp_List,disp_food,buid_food_state
fisrt = disp_List[0]
myItem[fisrt[0]][fisrt[1]]=0
if move_state == 0:
tail = disp_List[-1]
print(tail)
x=tail[0]
y=tail[1]+1
if(y>6):
y=0
disp_List.append([x,y])
elif move_state == 1:
tail = disp_List[-1]
print(tail)
x=tail[0]+1
y=tail[1]
if(x>5):
x=0
disp_List.append([x,y])
elif move_state == 2:
tail = disp_List[-1]
print(tail)
x=tail[0]
y=tail[1]-1
if(y<0):
y=6
disp_List.append([x,y])
elif move_state == 3:
tail = disp_List[-1]
print(tail)
x=tail[0]-1
y=tail[1]
if(x<0):
x=5
disp_List.append([x,y])
if disp_List[-1] == disp_food:
buid_food_state = 1
else:
del disp_List[0]
for item in disp_List:
myItem[item[0]][item[1]]=1
if len(disp_food) == 2:
myItem[disp_food[0]][disp_food[1]] = 1
def build_food():
global disp_List,disp_food,buid_food_state
disp_food=[]
disp_food.append(tqmath.random(0, 5))
disp_food.append(tqmath.random(0, 6))
if disp_food in disp_List:
print(disp_food)
buid_food_state = 0
while True:
get_key()
if state == True:
move()
if buid_food_state == 1:
build_food()
disp_tq()
os.sleep(0.1)
else:
time_state = time_state + 1
if time_state == 5:
move()
if buid_food_state == 1:
build_food()
disp_tq()
time_state = 0
os.sleep(0.1)
效果见视频。