Today, I will share the source code of go . Let's see the effect first . The default game is nine way play , Of course, you can also choose the 13th route or the 19th route .
tkinter:ttk Cover tkinter Some objects ,ttk Yes tkinter optimized
copy: Deep copy requires copy modular
tkinter.messagebox: Go application object definition
If there is no module above , stay pycharm The terminal enters the following command :
pip install The corresponding module -i https://pypi.douban.com/simple
from tkinter import *
from tkinter.ttk import *
import copy
import tkinter.messagebox
Initialize the chessboard and set the buttons on the right side of the chessboard , And control of the chess pieces .
class Application(Tk):
# Initialize chessboard , Default nine way chessboard
def __init__(self,my_mode_num=9):
Tk.__init__(self)
# Pattern , Nine way chess :9, Thirteen way chess :13, 19 way chess :19
self.mode_num=my_mode_num
# Window size settings , Default :1.8
self.size=1.8
# The side length of each space of the chessboard
self.dd=360*self.size/(self.mode_num-1)
# The correction ratio relative to the nine way chessboard
self.p=1 if self.mode_num==9 else (2/3 if self.mode_num==13 else 4/9)
# Define a checkerboard array , Beyond the boundary :-1, No son :0, Black chess :1, White chess :2
self.positions=[[0 for i in range(self.mode_num+2)] for i in range(self.mode_num+2)]
# Initialize chessboard , All values beyond the boundary are set to -1
for m in range(self.mode_num+2):
for n in range(self.mode_num+2):
if (m*n==0 or m==self.mode_num+1 or n==self.mode_num+1):
self.positions[m][n]=-1
# Three copies of the chessboard “ snapshot ”, Repentance and judgment “ Looting ” It needs to be used as a reference
self.last_3_positions=copy.deepcopy(self.positions)
self.last_2_positions=copy.deepcopy(self.positions)
self.last_1_positions=copy.deepcopy(self.positions)
# Record where the mouse passes , Used for display shadow when
self.cross_last=None
# The current player's turn , black :0, white :1, Black first
self.present=0
# Initial shutdown , Click on “ Start the game ” Run the game
self.stop=True
# Repentance times , More times than 0 To repent , Initial setting 0( You can't repent at first ), After repentance 0, Return to... When playing chess or abandoning your hand 1, To prohibit continuous repentance
self.regretchance=0
# Image resources , Stored in the current directory /Pictures/ in
self.photoW=PhotoImage(file = "./Pictures/W.png")
self.photoB=PhotoImage(file = "./Pictures/B.png")
self.photoBD=PhotoImage(file = "./Pictures/"+"BD"+"-"+str(self.mode_num)+".png")
self.photoWD=PhotoImage(file = "./Pictures/"+"WD"+"-"+str(self.mode_num)+".png")
self.photoBU=PhotoImage(file = "./Pictures/"+"BU"+"-"+str(self.mode_num)+".png")
self.photoWU=PhotoImage(file = "./Pictures/"+"WU"+"-"+str(self.mode_num)+".png")
# List for black and white chess picture switching
self.photoWBU_list=[self.photoBU,self.photoWU]
self.photoWBD_list=[self.photoBD,self.photoWD]
# Window size
self.geometry(str(int(600*self.size))+'x'+str(int(400*self.size)))
# Canvas controls , As a container
self.canvas_bottom=Canvas(self,bg='#369',bd=0,width=600*self.size,height=400*self.size)
self.canvas_bottom.place(x=0,y=0)
# Several function buttons
self.startButton=Button(self,text=' Start the game ',command=self.start)
self.startButton.place(x=480*self.size,y=200*self.size)
self.passmeButton=Button(self,text=' Give up ',command=self.passme)
self.passmeButton.place(x=480*self.size,y=225*self.size)
self.regretButton=Button(self,text=' Repentance ',command=self.regret)
self.regretButton.place(x=480*self.size,y=250*self.size)
# The initial regret button is disabled
self.regretButton['state']=DISABLED
self.replayButton=Button(self,text=' restart ',command=self.reload)
self.replayButton.place(x=480*self.size,y=275*self.size)
self.newGameButton1=Button(self,text=(' 13、 ... and ' if self.mode_num==9 else ' Nine ')+' Lu Qi ',command=self.newGame1)
self.newGameButton1.place(x=480*self.size,y=300*self.size)
self.newGameButton2=Button(self,text=(' 13、 ... and ' if self.mode_num==19 else ' nineteen ')+' Lu Qi ',command=self.newGame2)
self.newGameButton2.place(x=480*self.size,y=325*self.size)
self.quitButton=Button(self,text=' Quit the game ',command=self.quit)
self.quitButton.place(x=480*self.size,y=350*self.size)
# Drawing board , Fill color
self.canvas_bottom.create_rectangle(0*self.size,0*self.size,400*self.size,400*self.size,fill='#c51')
# Depict the chessboard line and nine points
# First draw the thick line of the outer frame
self.canvas_bottom.create_rectangle(20*self.size,20*self.size,380*self.size,380*self.size,width=3)
# Nine anchor points on the chessboard , Take... As the midpoint of the model , Mobile location , To make the remaining eight points
for m in [-1,0,1]:
for n in [-1,0,1]:
self.oringinal=self.canvas_bottom.create_oval(200*self.size-self.size*2,200*self.size-self.size*2,
200*self.size+self.size*2,200*self.size+self.size*2,fill='#000')
self.canvas_bottom.move(self.oringinal,m*self.dd*(2 if self.mode_num==9 else (3 if self.mode_num==13 else 6)),
n*self.dd*(2 if self.mode_num==9 else (3 if self.mode_num==13 else 6)))
# Draw the line in the middle
for i in range(1,self.mode_num-1):
self.canvas_bottom.create_line(20*self.size,20*self.size+i*self.dd,380*self.size,20*self.size+i*self.dd,width=2)
self.canvas_bottom.create_line(20*self.size+i*self.dd,20*self.size,20*self.size+i*self.dd,380*self.size,width=2)
# Place the initial picture on the right
self.pW=self.canvas_bottom.create_image(500*self.size+11, 65*self.size,image=self.photoW)
self.pB=self.canvas_bottom.create_image(500*self.size-11, 65*self.size,image=self.photoB)
# Add... To every picture image label , convenient reload Function to delete the picture
self.canvas_bottom.addtag_withtag('image',self.pW)
self.canvas_bottom.addtag_withtag('image',self.pB)
# When the mouse moves , call shadow function , Show the pieces moving with the mouse
self.canvas_bottom.bind('<Motion>',self.shadow)
# Click with the left mouse button , call getdown function , Put down the pieces
self.canvas_bottom.bind('<Button-1>',self.getDown)
# Set the exit shortcut <Ctrl>+<D>, Exit the game quickly
self.bind('<Control-KeyPress-d>',self.keyboardQuit)
def start(self):
# Delete the Tai Chi diagram on the right
self.canvas_bottom.delete(self.pW)
self.canvas_bottom.delete(self.pB)
# Use the pattern on the right to indicate who will fall first at the beginning
if self.present==0:
self.create_pB()
self.del_pW()
else:
self.create_pW()
self.del_pB()
# Start sign , relieve stop
self.stop=None
Click to discard , You can skip the current round to settle .
def passme(self):
# Repentance is restored
if not self.regretchance==1:
self.regretchance+=1
else:
self.regretButton['state']=NORMAL
# Copy chessboard status , Record the first three chess games
self.last_3_positions=copy.deepcopy(self.last_2_positions)
self.last_2_positions=copy.deepcopy(self.last_1_positions)
self.last_1_positions=copy.deepcopy(self.positions)
self.canvas_bottom.delete('image_added_sign')
# It's the next player's turn
if self.present==0:
self.create_pW()
self.del_pB()
self.present=1
else:
self.create_pB()
self.del_pW()
self.present=0
If the current turn repents , Then you can't repent in the next two rounds .
def regret(self):
# Decide whether you can repent
if self.regretchance==1:
self.regretchance=0
self.regretButton['state']=DISABLED
list_of_b=[]
list_of_w=[]
self.canvas_bottom.delete('image')
if self.present==0:
self.create_pB()
else:
self.create_pW()
for m in range(1,self.mode_num+1):
for n in range(1,self.mode_num+1):
self.positions[m][n]=0
for m in range(len(self.last_3_positions)):
for n in range(len(self.last_3_positions[m])):
if self.last_3_positions[m][n]==1:
list_of_b+=[[n,m]]
elif self.last_3_positions[m][n]==2:
list_of_w+=[[n,m]]
self.recover(list_of_b,0)
self.recover(list_of_w,1)
self.last_1_positions=copy.deepcopy(self.last_3_positions)
for m in range(1,self.mode_num+1):
for n in range(1,self.mode_num+1):
self.last_2_positions[m][n]=0
self.last_3_positions[m][n]=0
Click restart , Restore chessboard .
def reload(self):
if self.stop==1:
self.stop=0
self.canvas_bottom.delete('image')
self.regretchance=0
self.present=0
self.create_pB()
for m in range(1,self.mode_num+1):
for n in range(1,self.mode_num+1):
self.positions[m][n]=0
self.last_3_positions[m][n]=0
self.last_2_positions[m][n]=0
self.last_1_positions[m][n]=0
def create_pW(self):
self.pW=self.canvas_bottom.create_image(500*self.size+11, 65*self.size,image=self.photoW)
self.canvas_bottom.addtag_withtag('image',self.pW)
def create_pB(self):
self.pB=self.canvas_bottom.create_image(500*self.size-11, 65*self.size,image=self.photoB)
self.canvas_bottom.addtag_withtag('image',self.pB)
def del_pW(self):
self.canvas_bottom.delete(self.pW)
def del_pB(self):
self.canvas_bottom.delete(self.pB)
def shadow(self,event):
if not self.stop:
# Find the nearest grid , Display the picture of chess pieces in the grid near the current position , And delete the picture of the chess piece in the previous position
if (20*self.size<event.x<380*self.size) and (20*self.size<event.y<380*self.size):
dx=(event.x-20*self.size)%self.dd
dy=(event.y-20*self.size)%self.dd
self.cross=self.canvas_bottom.create_image(event.x-dx+round(dx/self.dd)*self.dd+22*self.p, event.y-dy+round(dy/self.dd)*self.dd-27*self.p,image=self.photoWBU_list[self.present])
self.canvas_bottom.addtag_withtag('image',self.cross)
if self.cross_last!=None:
self.canvas_bottom.delete(self.cross_last)
self.cross_last=self.cross
# Move later , And drive players to play chess in turn
def getDown(self,event):
if not self.stop:
# Find the nearest grid first
if (20*self.size-self.dd*0.4<event.x<self.dd*0.4+380*self.size) and (20*self.size-self.dd*0.4<event.y<self.dd*0.4+380*self.size):
dx=(event.x-20*self.size)%self.dd
dy=(event.y-20*self.size)%self.dd
x=int((event.x-20*self.size-dx)/self.dd+round(dx/self.dd)+1)
y=int((event.y-20*self.size-dy)/self.dd+round(dy/self.dd)+1)
# Determine whether the position has been occupied
if self.positions[y][x]==0:
# Not occupied , Try to occupy , Get the list of pieces that can be killed after occupying
self.positions[y][x]=self.present+1
self.image_added=self.canvas_bottom.create_image(event.x-dx+round(dx/self.dd)*self.dd+4*self.p, event.y-dy+round(dy/self.dd)*self.dd-5*self.p,image=self.photoWBD_list[self.present])
self.canvas_bottom.addtag_withtag('image',self.image_added)
# The chess piece is bound to the position tag , convenient “ Kill ”
self.canvas_bottom.addtag_withtag('position'+str(x)+str(y),self.image_added)
deadlist=self.get_deadlist(x,y)
self.kill(deadlist)
# Determine whether to repeat the chess game
if not self.last_2_positions==self.positions:
# Judge whether it belongs to one of Qi and kill each other
if len(deadlist)>0 or self.if_dead([[x,y]],self.present+1,[x,y])==False:
# When you don't repeat the game , And it belongs to one of being angry and killing each other , Falling pieces are effective
if not self.regretchance==1:
self.regretchance+=1
else:
self.regretButton['state']=NORMAL
self.last_3_positions=copy.deepcopy(self.last_2_positions)
self.last_2_positions=copy.deepcopy(self.last_1_positions)
self.last_1_positions=copy.deepcopy(self.positions)
# Delete last tag , Recreate the tag
self.canvas_bottom.delete('image_added_sign')
self.image_added_sign=self.canvas_bottom.create_oval(event.x-dx+round(dx/self.dd)*self.dd+0.5*self.dd, event.y-dy+round(dy/self.dd)*self.dd+0.5*self.dd,event.x-dx+round(dx/self.dd)*self.dd-0.5*self.dd, event.y-dy+round(dy/self.dd)*self.dd-0.5*self.dd,width=3,outline='#3ae')
self.canvas_bottom.addtag_withtag('image',self.image_added_sign)
self.canvas_bottom.addtag_withtag('image_added_sign',self.image_added_sign)
if self.present==0:
self.create_pW()
self.del_pB()
self.present=1
else:
self.create_pB()
self.del_pW()
self.present=0
else:
# It doesn't belong to killing each other or being angry , Then it is judged as no gas , Warn and pop up the warning box
self.positions[y][x]=0
self.canvas_bottom.delete('position'+str(x)+str(y))
self.bell()
self.showwarningbox(' No gas '," You're surrounded !")
else:
# Repeat the game , Warning robbery
self.positions[y][x]=0
self.canvas_bottom.delete('position'+str(x)+str(y))
self.recover(deadlist,(1 if self.present==0 else 0))
self.bell()
self.showwarningbox(" Looting "," That the road is blocked !")
else:
# Cover , Sound warning
self.bell()
else:
# Beyond the border , Sound warning
self.bell()
def if_dead(self,deadList,yourChessman,yourPosition):
for i in [-1,1]:
if [yourPosition[0]+i,yourPosition[1]] not in deadList:
if self.positions[yourPosition[1]][yourPosition[0]+i]==0:
return False
if [yourPosition[0],yourPosition[1]+i] not in deadList:
if self.positions[yourPosition[1]+i][yourPosition[0]]==0:
return False
if ([yourPosition[0]+1,yourPosition[1]] not in deadList) and (self.positions[yourPosition[1]][yourPosition[0]+1]==yourChessman):
midvar=self.if_dead(deadList+[[yourPosition[0]+1,yourPosition[1]]],yourChessman,[yourPosition[0]+1,yourPosition[1]])
if not midvar:
return False
else:
deadList+=copy.deepcopy(midvar)
if ([yourPosition[0]-1,yourPosition[1]] not in deadList) and (self.positions[yourPosition[1]][yourPosition[0]-1]==yourChessman):
midvar=self.if_dead(deadList+[[yourPosition[0]-1,yourPosition[1]]],yourChessman,[yourPosition[0]-1,yourPosition[1]])
if not midvar:
return False
else:
deadList+=copy.deepcopy(midvar)
if ([yourPosition[0],yourPosition[1]+1] not in deadList) and (self.positions[yourPosition[1]+1][yourPosition[0]]==yourChessman):
midvar=self.if_dead(deadList+[[yourPosition[0],yourPosition[1]+1]],yourChessman,[yourPosition[0],yourPosition[1]+1])
if not midvar:
return False
else:
deadList+=copy.deepcopy(midvar)
if ([yourPosition[0],yourPosition[1]-1] not in deadList) and (self.positions[yourPosition[1]-1][yourPosition[0]]==yourChessman):
midvar=self.if_dead(deadList+[[yourPosition[0],yourPosition[1]-1]],yourChessman,[yourPosition[0],yourPosition[1]-1])
if not midvar:
return False
else:
deadList+=copy.deepcopy(midvar)
return deadList
# Warning message box , Accept titles and warnings
def showwarningbox(self,title,message):
self.canvas_bottom.delete(self.cross)
tkinter.messagebox.showwarning(title,message)
# After falling , Judge whether there are chess pieces around in turn , And return to the dead chess position list
def get_deadlist(self,x,y):
deadlist=[]
for i in [-1,1]:
if self.positions[y][x+i]==(2 if self.present==0 else 1) and ([x+i,y] not in deadlist):
killList=self.if_dead([[x+i,y]],(2 if self.present==0 else 1),[x+i,y])
if not killList==False:
deadlist+=copy.deepcopy(killList)
if self.positions[y+i][x]==(2 if self.present==0 else 1) and ([x,y+i] not in deadlist):
killList=self.if_dead([[x,y+i]],(2 if self.present==0 else 1),[x,y+i])
if not killList==False:
deadlist+=copy.deepcopy(killList)
return deadlist
# Restore location list list_to_recover by b_or_w Designated pieces
def recover(self,list_to_recover,b_or_w):
if len(list_to_recover)>0:
for i in range(len(list_to_recover)):
self.positions[list_to_recover[i][1]][list_to_recover[i][0]]=b_or_w+1
self.image_added=self.canvas_bottom.create_image(20*self.size+(list_to_recover[i][0]-1)*self.dd+4*self.p, 20*self.size+(list_to_recover[i][1]-1)*self.dd-5*self.p,image=self.photoWBD_list[b_or_w])
self.canvas_bottom.addtag_withtag('image',self.image_added)
self.canvas_bottom.addtag_withtag('position'+str(list_to_recover[i][0])+str(list_to_recover[i][1]),self.image_added)
# Kill location list killList Chess pieces in the game , That is, delete the picture , The position value is set to 0
def kill(self,killList):
if len(killList)>0:
for i in range(len(killList)):
self.positions[killList[i][1]][killList[i][0]]=0
self.canvas_bottom.delete('position'+str(killList[i][0])+str(killList[i][1]))
Description of exit game and global variables .
def keyboardQuit(self,event):
self.quit()
# The following two functions modify the global variable value ,newApp Loop the main function , To create objects with different parameters
def newGame1(self):
global mode_num,newApp
mode_num=(13 if self.mode_num==9 else 9)
newApp=True
self.quit()
def newGame2(self):
global mode_num,newApp
mode_num=(13 if self.mode_num==19 else 19)
newApp=True
self.quit()
# Declare global variables , For new Application Object when switching to different modes of the game
global mode_num,newApp
mode_num=9
newApp=False
if __name__=='__main__':
# loop , Until you don't switch game mode
while True:
newApp=False
app=Application(mode_num)
app.title(' go ')
app.mainloop()
if newApp:
app.destroy()
else:
break
All the files and pictures are on the web disk : Extraction code 0524, Click extract