Python3+ Tkinter is used to create a small project – black and white
Tkinter is a graphical module built into Python. It is simple and easy to use. General small UI programs can be quickly implemented with it
Let’s look at the black and white game first
I. Project demonstration
Second, the code
The complete code is as follows, use material (pictures, etc.) to download address is: www.itprojects.cn/detail.html…
from tkinter import *
from tkinter.messagebox import *
import random
root = Tk('Black and white')
root.title("Black and White (for more project examples visit www.itprojects.cn)")
# loading images
imgs = [PhotoImage(file='black.png'), PhotoImage(file='white.png'), PhotoImage(file='board.png'), PhotoImage(file='info2.png')]
def resetBoard(board) :
""" Reset board """
for x in range(8) :for y in range(8):
board[x][y] = 'none'
# Starting pieces:
board[3] [3] = 'black'
board[3] [4] = 'white'
board[4] [3] = 'white'
board[4] [4] = 'black'
def getNewBoard() :
""" Create a new board at the opening. ""
board = []
for i in range(8):
board.append(['none'] * 8)
return board
def isValidMove(board, tile, xstart, ystart) :
""" Is it a legal move and if it is, returns a list of pieces to flip """
# If the position is already occupied or out of bounds, return False
if not isOnBoard(xstart, ystart) orboard[xstart][ystart] ! ='none':
return False
# temporarily place tile in the specified position
board[xstart][ystart] = tile
if tile == 'black':
otherTile = 'white'
else:
otherTile = 'black'
# The piece to be flipped
tilesToFlip = []
for xdirection, ydirection in [[0.1], [1.1], [1.0], [1, -1], [0, -1], [...1, -1], [...1.0], [...1.1]]:
x, y = xstart, ystart
x += xdirection
y += ydirection
if isOnBoard(x, y) and board[x][y] == otherTile:
x += xdirection
y += ydirection
if not isOnBoard(x, y):
continue
# Go all the way to a position that is out of bounds or not the opponent's piece
while board[x][y] == otherTile:
x += xdirection
y += ydirection
if not isOnBoard(x, y):
break
# out of bounds, no pieces to flip OXXXXX
if not isOnBoard(x, y):
continue
# is their own piece OXXXXXXO
if board[x][y] == tile:
while True:
x -= xdirection
y -= ydirection
# End when you come back to the beginning
if x == xstart and y == ystart:
break
# Pieces to be flipped
tilesToFlip.append([x, y])
# Remove the pieces temporarily placed in front of you, that is, restore the board
board[xstart][ystart] = 'none' # restore the empty space
# If there are no pieces to be flipped, the move is illegal. Flip the rules of chess.
if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
return False
return tilesToFlip
def isOnBoard(x, y) :
""" Out of bounds """
return x >= 0 and x <= 7 and y >= 0 and y <= 7
def getValidMoves(board, tile) :
""" Get the locatable position """
validMoves = []
for x in range(8) :for y in range(8) :ifisValidMove(board, tile, x, y) ! =False:
validMoves.append([x, y])
return validMoves
def getScoreOfBoard(board) :
""" Gets the number of pieces on the board between black and white. ""
xscore = 0
oscore = 0
for x in range(8) :for y in range(8) :if board[x][y] == 'black':
xscore += 1
if board[x][y] == 'white':
oscore += 1
return {'black': xscore, 'white': oscore}
def whoGoesFirst() :
""" Decide who goes first """
if random.randint(0.1) = =0:
return 'computer'
else:
return 'player'
def makeMove(board, tile, xstart, ystart) :
"" Place a tile into (xstart, ystart)""
tilesToFlip = isValidMove(board, tile, xstart, ystart)
if tilesToFlip == False:
return False
board[xstart][ystart] = tile
for x, y in tilesToFlip: # tilesToFlip is a list of pieces to flip
board[x][y] = tile # Flip pieces
return True
def getBoardCopy(board) :
""" Copy the checkerboard """
dupeBoard = getNewBoard()
for x in range(8) :for y in range(8):
dupeBoard[x][y] = board[x][y]
return dupeBoard
def isOnCorner(x, y) :
""" Is it on the corner? """
return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7)
def getComputerMove(board, computerTile) :
""" Computer moves, AI"""
Get all legal moves
possibleMoves = getValidMoves(board, computerTile)
if not possibleMoves: # If there is no legal way to go
print("Computer has no legal way to move.")
return None
Break up all legal moves
random.shuffle(possibleMoves)
# [x, y] is in the Angle, then go first, because the Angle will not be flipped again
for x, y in possibleMoves:
if isOnCorner(x, y):
return [x, y]
bestScore = -1
for x, y in possibleMoves:
dupeBoard = getBoardCopy(board)
makeMove(dupeBoard, computerTile, x, y)
# select the move with the most points after flipping
score = getScoreOfBoard(dupeBoard)[computerTile]
if score > bestScore:
bestMove = [x, y]
bestScore = score
return bestMove
def isGameOver(board) :
""" Is the game over """
for x in range(8) :for y in range(8) :if board[x][y] == 'none':
return False
return True
def drawQiPan() :
""" Draw a checkerboard """
img1 = imgs[2]
cv.create_image((360.360), image=img1)
cv.pack()
def callback(event) :
"" "moves "" "
global turn
# print ("clicked at", event.x, event.y,turn)
# x=(event.x)//40 # convert checkerboard coordinates
# y=(event.y)//40
if (gameOver == False and turn == 'computer') :# It is not the player's turn to move
return
col = int((event.x - 40) / 80) # Convert checkerboard coordinates
row = int((event.y - 40) / 80)
ifmainBoard[col][row] ! ="none":
showinfo(title="Tip", message="Existing pieces")
if makeMove(mainBoard, playerTile, col, row) == True: # Place a player piece on (col, row)
ifgetValidMoves(mainBoard, computerTile) ! = []: turn ='computer'
# Computer moves
if getComputerMove(mainBoard, computerTile) == None:
turn = 'player'
showinfo(title="Player continues", message="Player continues")
else:
computerGo()
# Redraw all the pieces and boards
drawAll()
drawCanGo()
if isGameOver(mainBoard): # Game over, display the number of pieces on both sides
scorePlayer = getScoreOfBoard(mainBoard)[playerTile]
scoreComputer = getScoreOfBoard(mainBoard)[computerTile]
outputStr = gameoverStr + "Players." + str(scorePlayer) + ":" + "Computer." + str(scoreComputer)
showinfo(title="Game over hint", message=outputStr)
def computerGo() :
""" Computer moves """
global turn
if (gameOver == False and turn == 'computer'):
x, y = getComputerMove(mainBoard, computerTile) # Computer AI moves
makeMove(mainBoard, computerTile, x, y)
savex, savey = x, y
# Player runs out of possible moves, the computer continues, otherwise switch to player moves
ifgetValidMoves(mainBoard, playerTile) ! = []: turn ='player'
else:
ifgetValidMoves(mainBoard, computerTile) ! = []: showinfo(title="Computer continues", message="Computer continues")
computerGo()
def drawAll() :
""" Redraw all the pieces and boards """
drawQiPan()
for x in range(8) :for y in range(8) :if mainBoard[x][y] == 'black':
cv.create_image((x * 80 + 80, y * 80 + 80), image=imgs[0])
cv.pack()
elif mainBoard[x][y] == 'white':
cv.create_image((x * 80 + 80, y * 80 + 80), image=imgs[1])
cv.pack()
def drawCanGo() :
""" Draw the prompt position """
list1 = getValidMoves(mainBoard, playerTile)
for m in list1:
x = m[0]
y = m[1]
cv.create_image((x * 80 + 80, y * 80 + 80), image=imgs[3])
cv.pack()
if __name__ == '__main__':
# initialization
gameOver = False
gameoverStr = 'Game Over Score '
mainBoard = getNewBoard()
resetBoard(mainBoard)
turn = whoGoesFirst()
showinfo(title="Game start prompt", message=turn + "先走!")
print(turn, "先走!")
if turn == 'player':
playerTile = 'black'
computerTile = 'white'
else:
playerTile = 'white'
computerTile = 'black'
computerGo()
# Setup window
cv = Canvas(root, bg='green', width=720, height=780)
# Redraw all the pieces and boards
drawAll()
drawCanGo()
cv.bind("<Button-1>", callback)
cv.pack()
root.mainloop()
Copy the code