Python write Tetris

The examples in this article share the specific code for implementing Tetris in python for your reference. The specific content is as follows

# coding=utf-8from tkinter import*from random import*import threading
from tkinter.messagebox import showinfo
from tkinter.messagebox import askquestion
import threading
from time import sleep
classBrickGame(object): 
# Whether to start
start = True; 
# Whether to reach the bottom
isDown = True; 
isPause = False; 
# Form
window = None; 
# frame 
frame1 = None; 
frame2 = None; 
# Button
btnStart = None; 
# Drawing class
canvas = None; 
canvas1 = None; 
# title
title ="BrickGame"; 
# Width and height
width =450; 
height =670; 
# Rows and Columns
rows =20; 
cols =10; 
# Thread of falling cube
downThread = None; 
# Several squares
brick =[[[[0,1,1],[1,1,0],[0,0,0]],[[1,0,0],[1,1,0],[0,1,0]],[[0,1,1],[1,1,0],[0,0,0]],[[1,0,0],[1,1,0],[0,1,0]]],[[[1,1,1],[1,0,0],[0,0,0]],[[0,1,1],[0,0,1],[0,0,1]],[[0,0,0],[0,0,1],[1,1,1]],[[1,0,0],[1,0,0],[1,1,0]]],[[[1,1,1],[0,0,1],[0,0,0]],[[0,0,1],[0,0,1],[0,1,1]],[[0,0,0],[1,0,0],[1,1,1]],[[1,1,0],[1,0,0],[1,0,0]]],[[[0,0,0],[0,1,1],[0,1,1]],[[0,0,0],[0,1,1],[0,1,1]],[[0,0,0],[0,1,1],[0,1,1]],[[0,0,0],[0,1,1],[0,1,1]]],[[[1,1,1],[0,1,0],[0,0,0]],[[0,0,1],[0,1,1],[0,0,1]],[[0,0,0],[0,1,0],[1,1,1]],[[1,0,0],[1,1,0],[1,0,0]]],[[[0,1,0],[0,1,0],[0,1,0]],[[0,0,0],[1,1,1],[0,0,0]],[[0,1,0],[0,1,0],[0,1,0]],[[0,0,0],[1,1,1],[0,0,0]]],[[[1,1,0],[0,1,1],[0,0,0]],[[0,0,1],[0,1,1],[0,1,0]],[[0,0,0],[1,1,0],[0,1,1]],[[0,1,0],[1,1,0],[1,0,0]]]]; 
# Current square
curBrick = None; 
# Current block array
arr = None; 
arr1 = None; 
# Current square shape
shape =-1; 
# The row and column of the current square (top left corner)
curRow =-10; 
curCol =-10; 
# background
back =list(); 
# lattice
gridBack =list(); 
preBack =list(); 
# initialization
def init(self):for i inrange(0,self.rows): 
self.back.insert(i,list()); 
self.gridBack.insert(i,list());for i inrange(0,self.rows):for j inrange(0,self.cols): 
self.back[i].insert(j,0); 
self.gridBack[i].insert(j,self.canvas.create_rectangle(30*j,30*i,30*(j+1),30*(i+1),fill="black"));for i inrange(0,3): 
self.preBack.insert(i,list());for i inrange(0,3):for j inrange(0,3): 
self.preBack[i].insert(j,self.canvas1.create_rectangle(30*j,30*i,30*(j+1),30*(i+1),fill="black")); 
# Draw the grid of the game
def drawRect(self):for i inrange(0,self.rows):for j inrange(0,self.cols):if self.back[i][j]==1: 
self.canvas.itemconfig(self.gridBack[i][j],fill="blue",outline="white"); 
elif self.back[i][j]==0: 
self.canvas.itemconfig(self.gridBack[i][j],fill="black",outline="white"); 
# Draw preview box
for i inrange(0,len(self.arr1)):for j inrange(0,len(self.arr1[i])):if self.arr1[i][j]==0: 
self.canvas1.itemconfig(self.preBack[i][j],fill="black",outline="white"); 
elif self.arr1[i][j]==1: 
self.canvas1.itemconfig(self.preBack[i][j],fill="orange",outline="white"); 
# Draw the currently moving block
if self.curRow!=-10 and self.curCol!=-10:for i inrange(0,len(self.arr)):for j inrange(0,len(self.arr[i])):if self.arr[i][j]==1:   
self.canvas.itemconfig(self.gridBack[self.curRow+i][self.curCol+j],fill="blue",outline="white"); 
# Determine whether the block has moved to the bottom
if self.isDown:for i inrange(0,3):for j inrange(0,3):if self.arr[i][j]!=0: 
self.back[self.curRow+i][self.curCol+j]= self.arr[i][j]; 
# Judge the entire line to eliminate
self.removeRow(); 
# Judge whether it is dead
self.isDead(); 
# Get the next block
self.getCurBrick(); 
# Determine whether there is an entire line that needs to be eliminated
def removeRow(self): 
count=0for i inrange(0,self.rows): 
tag1 = True;for j inrange(0,self.cols):if self.back[i][j]==0: 
tag1 = False;break;if tag1==True: 
# Move from top to bottom
count=count+1for m inrange(i-1,0,-1):for n inrange(0,self.cols): 
self.back[m+1][n]= self.back[m][n]; 
scoreValue =eval(self.scoreLabel2['text'])
scoreValue +=5*count*(count+3)
self.scoreLabel2.config(text=str(scoreValue))
# Get the current square
def getCurBrick(self): 
self.curBrick =randint(0,len(self.brick)-1); 
self.shape =0; 
# Current block array
self.arr = self.brick[self.curBrick][self.shape]; 
self.arr1 = self.arr; 
self.curRow =0; 
self.curCol =1; 
# Whether to the bottom is False
self.isDown = False; 
# Monitor keyboard input
def onKeyboardEvent(self,event): 
# Not started, no need to monitor keyboard input
if self.start == False:return;if self.isPause == True:return;
# Record the original value
tempCurCol = self.curCol; 
tempCurRow = self.curRow; 
tempShape = self.shape; 
tempArr = self.arr; 
direction =-1;if event.keycode==37: 
# Shift left
self.curCol-=1; 
direction =1; 
elif event.keycode==38: 
# Change the shape of the square
self.shape+=1; 
direction =2;if self.shape =4: 
self.shape=0; 
self.arr = self.brick[self.curBrick][self.shape]; 
elif event.keycode==39: 
direction =3; 
# Shift right
self.curCol+=1; 
elif event.keycode==40: 
direction =4; 
# Move down
self.curRow+=1;if self.isEdge(direction)==False: 
self.curCol = tempCurCol; 
self.curRow = tempCurRow; 
self.shape = tempShape; 
self.arr = tempArr; 
self.drawRect();return True; 
# Determine whether the current square reaches the boundary
def isEdge(self,direction): 
tag = True; 
# To the left, judge the boundary
if direction==1:for i inrange(0,3):for j inrange(0,3):if self.arr[j][i]!=0and(self.curCol+i<0 or self.back[self.curRow+j][self.curCol+i]!=0): 
tag = False;break; 
# To the right, judge the boundary
elif direction==3:for i inrange(0,3):for j inrange(0,3):if self.arr[j][i]!=0and(self.curCol+i =self.cols or self.back[self.curRow+j][self.curCol+i]!=0): 
tag = False;break; 
# Down, judge the bottom
elif direction==4:for i inrange(0,3):for j inrange(0,3):if self.arr[i][j]!=0and(self.curRow+i =self.rows or self.back[self.curRow+i][self.curCol+j]!=0): 
tag = False; 
self.isDown = True;break; 
# Perform deformation and determine the boundary
elif direction==2:if self.curCol<0: 
self.curCol=0;if self.curCol+2=self.cols: 
self.curCol = self.cols-3;if self.curRow+2=self.rows: 
self.curRow = self.curRow-3;return tag; 
# Box moves down
def brickDown(self):while True:if self.start==False:print("exit thread");break;if self.isPause==False: 
tempRow = self.curRow; 
self.curRow+=1;if self.isEdge(4)==False: 
self.curRow = tempRow; 
self.drawRect(); 
# Decrease by one frame every second
sleep(1); 
# Click to start
def clickStart(self): 
self.start = True;for i inrange(0,self.rows):for j inrange(0,self.cols): 
self.back[i][j]=0; 
self.canvas.itemconfig(self.gridBack[i][j],fill="black",outline="white");for i inrange(0,len(self.arr)):for j inrange(0,len(self.arr[i])): 
self.canvas1.itemconfig(self.preBack[i][j],fill="black",outline="white"); 
self.getCurBrick(); 
self.drawRect(); 
self.downThread = threading.Thread(target=self.brickDown,args=()); 
self.downThread.start();
def clickPause(self):
self.isPause=not self.isPause
print(self.isPause)if not self.isPause:
self.btnPause["text"]="time out"else:
self.btnPause["text"]="restore"
def clickReStart(self):
ackRestart =askquestion("Restart","你确定要Restart吗?")if ackRestart =='yes':
self.clickStart()else:return
def clickQuit(self):
ackQuit =askquestion("drop out","你确定要drop out吗?")if ackQuit =='yes':
self.window.destroy()exit()
# Judge whether it is dead
def isDead(self):for j inrange(0,len(self.back[0])):if self.back[0][j]!=0:showinfo("prompt","You hang up, let&#39;s have another one!"); 
self.start = False;break; 
# run
def __init__(self): 
self.window =Tk(); 
self.window.title(self.title); 
self.window.minsize(self.width,self.height); 
self.window.maxsize(self.width,self.height);   
self.frame1 =Frame(self.window,width=300,height=600,bg="black"); 
self.frame1.place(x=20,y=30); 
self.scoreLabel1 =Label(self.window,text="Score:",font=(30))
self.scoreLabel1.place(x=340,y=60)
self.scoreLabel2 =Label(self.window,text="0",fg='red',font=(30))
self.scoreLabel2.place(x=410,y=60)
self.frame2 =Frame(self.window,width=90,height=90,bg="black"); 
self.frame2.place(x=340,y=120); 
self.canvas =Canvas(self.frame1,width=300,height=600,bg="black"); 
self.canvas1 =Canvas(self.frame2,width=90,height=90,bg="black"); 
self.btnStart =Button(self.window,text="Start",command=self.clickStart); 
self.btnStart.place(x=340,y=400,width=80,height=25); 
self.btnPause =Button(self.window,text="time out",command=self.clickPause); 
self.btnPause.place(x=340,y=450,width=80,height=25);
self.btnReStart =Button(self.window,text="Restart",command=self.clickReStart); 
self.btnReStart.place(x=340,y=500,width=80,height=25);
self.btnQuit =Button(self.window,text="drop out",command=self.clickQuit); 
self.btnQuit.place(x=340,y=550,width=80,height=25);
self.init(); 
# Get the current square
self.getCurBrick(); 
# According to the array, draw the grid
self.drawRect();
self.canvas.pack();
self.canvas1.pack(); 
# Listen to keyboard events
self.window.bind("<KeyPress ",self.onKeyboardEvent); 
# Start the cube drop thread
self.downThread = threading.Thread(target=self.brickDown,args=()); 
self.downThread.start();  
self.window.mainloop(); 
self.start=False; 
pass;if __name__=='__main__': 
brickGame =BrickGame();

For more exciting articles on Tetris, please click on the topic: Tetris Game Collection to learn.

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python write Tetris
Python implements Tetris game
Write gui in python
Python open read and write
Python write breakpoint download software
Python file read and write operations
Use C++ to write Python3 extensions
How to write python configuration file
How to write classes in python
How to write return in python
Actual combat | Python write port scanner
Python CookBook
Python FAQ
Python3 module
python (you-get)
Python string
Python basics
Python basics 2
How to write win programs in python
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python multithreading
How to write try statement in python
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5
Teach you how to write games in python
Python memory mapped file read and write method
How to write a confession program in python
How to read and write files with Python