from pygame import*;import random as r;R,E,d,z,s,m=range,enumerate,display,[],0,mouse;S=d.set_mode((600,500)).fill
A=[[r.choice((2631,420,4095,4025,1064))**2 for y in R(25)]for x in R(30)]
while event.wait().type!=QUIT:
 X,Y=m.get_pos();X,Y=X/20,24-Y/20
 if not(X,Y)in z:
  z=[(X,Y)]if A[X][Y]else[]
  [z.append((a,b))for x,y in z for a,b in(x-1,y),(x,y-1),(x+1,y),(x,y+1)if(0<=a<30)&(0<=b<25)and(A[a][b]==A[X][Y])&((a,b)not in z)]
  [S((len(z)>1)&((x,y)in z)and-1 or c,(x*20,480-y*20,18,18))for x,l in E(A)for y,c in E(l)];d.flip()
 if m.get_pressed()[0]&(len(z)>1):
  #uncomment for anim#[d.update([S(0,Rect(x*20,480-y*20,18,18).inflate(-e,-e))for x,y in z])for e in R(18,-4,-2)if time.wait(50)]
  for x,y in sorted(z,reverse=1):A[x].pop(y);A[x]+=[0]
  A.sort(None,any,1);s+=(len(z)-1)**2;z=[]
  d.set_caption((not any([j==i[e]for i in A+zip(*A)for e,j in E(i[1:])if j])and"c'est fini, "or"")+"score = "+str(s))
