Python 2.7:869 816 818 817 816个字符
在过去的几个小时里,我一起破解了这个。它应该满足要求,并且比mjgpy3的解决方案短几个字符(尝试过,但无法缩短很多。现在我很累)。令人惊讶的是,使用像pygame这样的游戏开发库并没有使python-snake变得更短。高度赞赏如何缩短时间的建议和技巧。我希望它不太神秘。
结果如下:
import pygame as p
from random import randint as r
p.init();l=20
c=p.time.Clock()
dp=p.display;w=p.display.set_mode((500,)*2)
C=p.Color;b=C(0,0,0);g=C(0,99,0)
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)
S=[R];d=R;n=[]
O=lambda t:{U:D,R:L,D:U,L:R}[t]
def Q(e):print "Score: %i"%(len(S)-1);p.quit()
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]
def M():n=(r(0,24),r(0,24));return n not in S and n or M()
A=lambda s,o:tuple(x+y for x,y in zip(s,o))
n=[M()]
while True:
w.fill(b);[{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]
if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)
if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]
else: S.append(A(S[-1],d));S.pop(0)
N(S);dp.update();c.tick(6)
编辑:我可以将其减少到816字节,是的!:)固定分数
EDIT2:意外粘贴了错误的版本
这是一个评论版本:
import pygame as p
from random import randint as r
# initialize pygame
p.init()
# the game consists of 25*25 blocks,with each block 20*20 pixels
l=20
# initialize the main loop clock
c=p.time.Clock()
# open the window
dp=p.display;w=p.display.set_mode((500,)*2)
# define black and green colors
C=p.Color;b=C(0,0,0);g=C(0,99,0)
# Directions of the snake: down, up, left, right
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)
# S is the snake, d is the current direction and n is the array of foods
S=[R];d=R;n=[]
# get the opposite direction of a direction to forbid double backing
O=lambda t:{U:D,R:L,D:U,L:R}[t]
# print the score and quit
def Q(e):print "Score: %i"%(len(S)-1);p.quit()
# update the direction (this is a key press handler)
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d
# draw the snake and food boxes
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]
# place new food on the map not colliding with the snake
def M():n=(r(0,24),r(0,24));return n not in S and n or M()
# A((1,1), (-2, 1)) -> (-1,2)
A=lambda s,o:tuple(x+y for x,y in zip(s,o))
# initialize food array
n=[M()]
while True:
# fill the screen black
w.fill(b)
# get quit or key press events and execute the event handlers
[{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]
# check if snake hits map boundaries or itself
if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)
# check if snake is eating food at the moment and append one to the snake's length
if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]
# move the snake in the current direction
else: S.append(A(S[-1],d));S.pop(0)
# draw the map and limit the main loop to 6 frames per second
N(S);dp.update();c.tick(6)