A tutorial on using Python to write a simple Tetris game

Source: Internet
Author: User
Tetris game, the use of Python implementation, a total of 350+ lines of code, the implementation of the basic functions of Tetris game, but also recorded the time spent, the total number of rows eliminated, the overall score, including a leaderboard, you can view the highest record.

The leaderboard contains a series of statistical functions, such as the number of rows eliminated per unit time, the unit time score, and so on.

Attached Source:


From Tkinter Import * from tkmessagebox Import * Import random import time #俄罗斯方块界面的高度 HEIGHT = #俄罗斯方块界面的宽度     WIDTH = Ten ACTIVE = 1 PASSIVE = 0 TRUE = 1 FALSE = 0 root=tk (); Root.title (' Russia ') class App (Frame): def __init__ (self,master): frame.__init__ (self) master.bind ('
 
  ', self. UP) Master.bind ('
  
   ', self. left) Master.bind ('
   
    ', self. right) Master.bind ('
    
     ', self. Down) #master. Bind ('
     
      ', self. Space) Master.bind ('
      
       ', self. Space) Master.bind ('
       
        ', self. Play) Master.bind ('
        
          ', self. Pause) self.backg= "#%02x%02x%02x"% (120,150,30) self.frontg= "#%02x%02x%02x"% (40,120,150) self.nextg= "#%02x%02x%02x "% (150,100,100) self.flashg=" #%02x%02x%02x "% (210,130,100) self. Linedisplay=label (master,text= ' Lines: ', bg= ' black ', fg= ' red ') self. Line=label (master,text= ' 0 ', bg= ' black ', fg= ' red ') self. Scoredisplay=label (master,text= ' score: ', bg= ' black ', fg= ' red ') self. Score=label (master,text= ' 0 ', bg= ' black ', fg= ' red ') #Display time self. Spendtimedisplay=label (master,text= ' time: ', bg= ' black ', fg= ' red ') self. Spendtime=label (master,text= ' 0.0 ', bg= ' black ', fg= ' red ') self. Linedisplay.grid (row=height-2,column=width,columnspan=2) self. Line.grid (row=height-2,column=width+2,columnspan=3) self. Scoredisplay.grid (row=height-1,column=width,columnspan=2) self. Score.grid (row=height-1,column=width+2,columnspan=3) #Display time self. Spendtimedisplay.grid (row=height-4,column=width,columnspan=2) self. Spendtime.grid (row=height-4,column=width+2,columnspan=3) self. totaltime=0.0 self. Totalline=0;self. TotalScore=0 #Game over Self.isgameover=false #Pause the Self.ispause=false #Start self.isstart=false self. Nextlist=[];self. Nextrowlist=[] r=0;c=0 for K in range (4*4): Ln=label (master,text= ", Bg=str (SELF.NEXTG), fg= ' White ', relief=flat,bd=4) Ln.grid (row=r,column=width+c,sticky=n+e+s+w) self. Nextrowlist.append (LN) c=c+1 if c>=4:r=r+1;c=0 self. Nextlist.append (self. Nextrowlist) self. Nextrowlist=[] Self. Blocklist=[];self. Labellist=[] Self. Blockrowlist=[];self. Labelrowlist=[] Row=0;col=0 for I in Range (height*width): L=label (master,text= ", Bg=str (self.backg), fg= ' white ', relief=flat,bd=4) L.grid (row=row,column=col,sticky=n+e+s+w) L.row=row; L.col=col; L.isactive=passive self. Blockrowlist.append (0); self. Labelrowlist.append (L) col=col+1 if col>=width:row=row+1;col=0 self. Blocklist.append (self. Blockrowlist) self. Labellist.append (self. Labelrowlist) self. Blockrowlist=[];self. Labelrowlist=[] #file fw=open (' text.txt ', ' a ') fw.close () hashead=false f=open (' Text.txt ', ' r ') if F.read (5) = = ' Score ': Hashead=trUE f.close () self.file=open (' Text.txt ', ' r+a ') if Hashead==false:self.file.write (' score line time Scoreptime Lineptime Scorepline date/n ') Self.file.flush () self.time=1000 self. OnTimer () def __del__ (self): #self. File.close () Pass def Pause (self,event): Self.ispause=1-self.ispause def up (self, Event): Bl=self. Blocklist; Ll=self. Labellist moveable=true xtotal=0;ytotal=0;count=0 for I in Range (HEIGHT): for J in Range (WIDTH): If Ll[i][j].isactive==act Ive:xtotal=xtotal+i;ytotal=ytotal+j;count=count+1 sourcelist=[];D estlist=[] for I in range (HEIGHT): for J in Range ( WIDTH): If ll[i][j].isactive==active:x0= (xtotal+ytotal)/count;y0= (ytotal-xtotal)/count xr= (xtotal+ytotal)%count; Yr= (ytotal-xtotal)%count x=x0-j;y=y0+i if xr>=count/2:x=x+1 if yr>=count/2:y=y+1 SourceList.append ([i,j]);D Estlist.append ([x, y]) if x<0 or X>=height or y<0 or Y>=width:moveable=false if x>=0 and X
         
          =0 and Y
          
           =0 and Bl[i][j-1]==1 and Ll[i][j-1].isactive==passive:moveable=false if moveable==true:for I in range (HEIGHT): for J in R Ange (WIDTH): If J-1>=0 and Ll[i][j].isactive==active and bl[i][j-1]==0:self. Fill (i,j-1); Empty (I,J) def right (self,event): Bl=self. Blocklist; Ll=self. Labellist moveable=true for I in Range (HEIGHT): for J in Range (WIDTH): If Ll[i][j].isactive==active and J+1>=width:move Able=false if Ll[i][j].isactive==active and j+1
           
            =1000:self.time=900 if self. totalscore>=2000:self.time=750 if self. totalscore>=3000:self.time=600 if self. totalscore>=4000:self.time=400 Self.after (self.time,self. OnTimer) def Down (self,event): Bl=self. Blocklist; Ll=self. Labellist moveable=true for I in Range (HEIGHT): for J in Range (WIDTH): If Ll[i][j].isactive==active and I+1>=height:mov Eable=false if Ll[i][j].isactive==active and i+1
             
             



) def Nextfill (self,i,j): self. Nextlist[i][j].config (Relief=raised,bg=str (SELF.FRONTG)) def nextempty (self,i,j): self. Nextlist[i][j].config (Relief=flat,bg=str (SELF.NEXTG)) def Distroy (self): #save if self. Totalscore!=0:savestr= '%-9u%-8u%-8.2f%-14.2f%-13.2f%-14.2f%s/n '% (self. Totalscore,self. Totalline,self. TotalTime, self. Totalscore/self. TotalTime, self. Totalline/self. TotalTime, float (self. Totalscore)/self. Totalline, Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime ())) Self.file.seek (0,2) self.file.write (SAVESTR) Self.file.flush () for I in Range (HEIGHT): for J in Range (WIDTH): self. Empty (i,j) self. Totalline=0;self. Totalscore=0;self. totaltime=0.0 self. Line.config (Text=str (self). Totalline)) self. Score.config (Text=str (self). Totalscore)) self. Spendtime.config (Text=str (self). totaltime)) Self.isgameover=false Self.isstart=false self.time=1000 for I in range (4): for J in Range (4): Self. Nextempty (I,J) def Start (self): if self.x==1:self. Fill (0,width/2-2); Fill (0,width/2-1); Fill (0,WIDTH/2); self. Fill (0,width/2+1) if self.x==2:self. Fill (0,width/2-1); Fill (0,WIDTH/2); Fill (1,width/2-1); Fill (1,WIDTH/2) if self.x==3:self. Fill (0,WIDTH/2); Fill (1,width/2-1); Fill (1,WIDTH/2); Fill (1,width/2+1) if self.x==4:self. Fill (0,width/2-1); Fill (1,width/2-1); Fill (1,WIDTH/2); Fill (1,width/2+1) if self.x==5:self. Fill (0,width/2+1); Fill (1,width/2-1); Fill (1,WIDTH/2); Fill (1,width/2+1) if self.x==6:self. Fill (0,width/2-1); Fill (0,WIDTH/2); Fill (1,WIDTH/2); Fill (1,width/2+1) if self.x==7:self. Fill (0,WIDTH/2); Fill (0,width/2+1); Fill (1,width/2-1); Fill (1,WIDTH/2) self.isstart=true def Rnd (self): Self.x=random.randint (1,7) if self.x==1:self. Nextfill (0,0); Nextfill (0,1); Nextfill (0,2); Nextfill (0,3) if self.x==2:self. Nextfill (0,1); Nextfill (0,2); Nextfill (a); Nextfill if self.x==3:self. Nextfill (0,2); Nextfill (a); Nextfill, self. Nextfill (1,3) if self.x==4:self. Nextfill (0,1); NExtfill (a); Nextfill, self. Nextfill (1,3) if self.x==5:self. Nextfill (0,3); Nextfill (a); Nextfill, self. Nextfill (1,3) if self.x==6:self. Nextfill (0,1); Nextfill (0,2); Nextfill, self. Nextfill (1,3) if self.x==7:self. Nextfill (0,2); Nextfill (0,3); Nextfill (a); Nextfill def rndfirst (self): Self.x=random.randint (1,7) def Show (self): Self.file.seek (0) strheadline= Self.file.readline () dictline={} strtotalline= "for Oneline in Self.file.readlines (): Temp=int (Oneline[:5]) dictline[ Temp]=oneline list=sorted (Dictline.items (), Key=lambda d:d[0]) ii=0 for Onerecord in Reversed (list): ii=ii+1 if ii<11: STRTOTALLINE+=ONERECORD[1] Showinfo (' Ranking ', strheadline+strtotalline) def Start (): App. Rndfirst (); app. Start (); app. Rnd () def End (): App. Distroy () def Set (): Pass Def Show (): App. Show () Mainmenu=menu (root) root[' Menu ']=mainmenu gamemenu=menu (MainMenu) mainmenu.add_cascade (label= ' game ', menu= Gamemenu) Gamemenu.add_command (label= ' Start ', Command=start) Gamemenu.add_command (label= ' End ', command=end) Gamemenu.add_separator () Gamemenu.add_command (label= ' exit ', Command=root.quit) Setmenu=menu (MainMenu) mainmenu.add_cascade (label= ' Set ', Menu=setmenu) Setmenu.add_command ( Label= ' Set ', Command=set) Showmenu=menu (MainMenu) mainmenu.add_cascade (label= ' show ', Menu=showmenu) showmenu.add_ Command (label= ' show ', command=show) App=app (Root) Root.mainloop ()
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.