Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_Tetris.py
- import random,time
- from Tkinter import *
- t=time.time()
- score,bw,bh,H,W,speed=0,10,20,30,30,300
- blk={0xf:"red",0x2e:"#0f0",0x27:"blue",0x47:"#ff0",0x66:"#0ff",0xC6:"#38f",0x6C:"#f0f"}
- board=[ [0xf if j==bh else 0]*bw+[0xf]*2 for j in range(bh+2+1) ]
- new_piece=lambda pc: ( [((z>>2)+1,z&3) for z in range(16) if (pc>>z)&1],3,-2,pc )
- collide=lambda piece,px,py: [1 for (i,j) in piece if board[j+py][i+px]]
- BALANCE=blk.keys()*5
- bal=BALANCE[:]
- random.shuffle(bal)
- piece,px,py,pc=new_piece(bal.pop())
- def Score():
- scr.create_text(12,18,text="SCORE: %i"%(score),font=('Verdana 18 bold'),fill='white',anchor='w')
- scr.create_text(12,36,text="SPEED: %i"%(int(300-speed)/6+1),font=('Verdana 10'),fill='white',anchor='w')
- def tick(e=None):
- global piece,px,py,pc,tickcnt,board,score,speed,bal
- if not speed: return
- keys=e.keysym if e else "" # get key event
- npx=px+(-1 if keys=="Left" else (1 if keys=="Right" else 0))
- npiece=[(j,3-i) for (i,j) in piece] if keys=="Up" else piece #rotate
- if not collide(npiece,npx,py): piece,px=npiece,npx
- if keys=="Down": py=(j for j in range(py,bh) if collide(piece,px,j+1)).next()
- if e==None:
- if collide(piece,px,py+1):
- if py<0: # game over
- h=400
- scr.create_rectangle(0,0,W*10,50,fill='darkred')
- scr.create_rectangle(0,h-30,W*10,h+30,fill='purple')
- scr.create_text(12,h,text="GAME OVER",font=('Verdana 34 italic'),fill='white',anchor='w')
- Score()
- speed=0
- return
- for i,j in piece: board[j+py][i+px]=pc
- if not bal:
- bal=BALANCE[:]
- random.shuffle(bal)
- piece,px,py,pc=new_piece(bal.pop())
- score+=1
- else: py+=1
- nb=[l for l in board[:bh] if 0 in l]+board[bh:]
- s=len(board)-len(nb)
- if s: score,board=score+((2**s)*50),[board[-1][:] for j in range(s)]+nb
- ttt=(time.time()-t)/30
- speed = max(50,speed-0.25)
- scr.after(int(speed-ttt),tick)
- scr.delete("all")
- for i,j,c in [(i,j,blk.get(board[j][i],"#000")) for i in range(bw) for j in range(bh)]:
- scr.create_rectangle(i*W,j*H,(i+1)*W,(j+1)*H,fill=blk[pc] if (i-px,j-py) in piece else c)
- Score()
- root=Tk()
- root.geometry("{}x{}+10+10".format(bw*W,bh*H))
- scr=Canvas(width=bw*W,height=bh*H,bg="#000")
- scr.after(speed,tick)
- scr.bind_all("<Key>",tick)
- scr.pack()
- scr.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement