Tetris in 14 lines of python code without exec and zip
Posted by tjwei on 星期日, 4月 29, 2007 with No comments
Improved version of my tetris in 15 lines. (python 2.5/pygame)
from pygame import *;R=range;W,H=10,20;E={198:0x7fff,46:0xff00,39:255,102:0xffff
,71:0xffff00,108:0xff00ff,15:0xff0000};B=[[15 if j==H else 0]*W+[15]*3 for j in
R(H+3)];S=n=0;import sys,random as C;C=C.choice;e=[1];O=lambda:(lambda Z:([(z/4+
1,z&3)for z in R(8)if(Z>>z)&1],3,-2,Z))(C(E.keys()));P,X,Y,Z=O();T=USEREVENT+1
L=lambda P,X,Y:[1 for(i,j)in P if B[j+Y][i+X]];d=display;init();F=d.set_mode((
400,800));time.set_timer(T,100);w=key.get_pressed;a="GAME OVER, score "
while(d.flip()or e.__setitem__(0,event.wait().type)or e[0])!=QUIT:
if e[0]==T:K=w();U=X+(-1 if K[K_LEFT]else(1 if K[K_RIGHT]else 0));V=Y+1 if K[
K_DOWN]else Y;Q=[(j,3-i)for i,j in P]if K[K_UP]else P;(P,X,Y)=(P,X,Y)if L(Q,U,V
)else(Q,U,V);n%5 or L(P,X,Y+1)and(Y<0 and sys.exit(a+`S`)or[B[j+Y].__setitem__(i
+X,Z)for i,j in P]);(P,X,Y,Z)=(P,X,Y,Z)if n%5 else(O()if L(P,X,Y+1)else(P,X,Y+1,
Z));n+=1;D=[z for z in B[:H]if 0 in z]+B[H:];l=len;s=l(B)-l(D);(S,B)=(S+2**s,[B[
-1][:]for j in R(s)]+D)if s else(S,B);[draw.rect(F,E[Z]if(i-X,j-Y)in P else c,((
i*40,j*40),(40,40)))for i,j,c in[(z%W,z/W,E.get(B[z/W][z%W],0))for z in R(W*H)]]
Categories: python
0 意見:
張貼留言