php贪吃蛇程序代码,50⾏代码实现贪吃蛇(具体思路及代码)import sys, pygame
from pygame.locals import *
from random import randrange
up =lambda x:(x[0]-1,x[1])
down = lambda x :(x[0]+1,x[1])贪吃蛇的编程代码
left = lambda x : (x[0],x[1]-1)
right = lambda x : (x[0],x[1]+1)
tl = lambda x :x<3 and x+1 or 0
tr = lambda x :x==0 and 3 or x-1
dire = [up,left,down,right]
move = lambda x,y:[y(x[0])]+x[:-1]
grow = lambda x,y:[y(x[0])]+x
s = [(5,5),(5,6),(5,7)]
d = up
food = randrange(0,30),randrange(0,40)
FPSCLOCK=pygame.time.Clock()
pygame.init()
pygame.display.set_mode((800,600))
screen = _surface()
screen.fill((0,0,0))
times=0.0
while True:
time_passed = FPSCLOCK.tick(30)
if times>=150:
times =0.0
s = move(s,d)
else:
times +=time_passed
for event in ():
pe == QUIT:
pe == KEYDOWN and event.key == K_UP:
s = move(s,d)
pe == KEYDOWN and event.key == K_LEFT:
d=dire[tl(dire.index(d))]
pe == KEYDOWN and event.key == K_RIGHT:
d=dire[tr(dire.index(d))]
if s[0]==food:
s = grow(s,d)
food =randrange(0,30),randrange(0,40)
if s[0] in s[1:] or s[0][0]<0 or s[0][0] >= 30 or s[0][1]<0 or s[0][1]>=40:
break
screen.fill((0,0,0))
for r,c in s:
(screen,(255,0,0),(c*20,r*20,20,20))
(screen,(0,255,0),(food[1]*20,food[0]*20,20,20))
pygame.display.update()
游戏截图:
说明:
1.其实不⽤pygame,在把⼀些条件判断改改,估计可以再短⼀半。。等以后⾃⼰python⽔平⾼了再回来试试。。
2.但是50⾏的贪吃蛇代码,还是有可读性的,写的太短就真没有了。。
3.关键是把旋转,移动,等等这些算法⽤lamda表达式实现,还有函数对象。。
4.哪位“⾏者”能写的更短,⼩弟愿意赐教....
作者:aiqier
相关标签:贪吃蛇
本⽂原创发布php中⽂⽹,转载请注明出处,感谢您的尊重!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论