Though our game is fully functional, let's add two small features to it.
Let's add a top menu item by navigating to File | New Game. When clicked, it should reset the board to a new game.
Additionally, let's add a small frame at the bottom to display game-related information, such as the last move, next turn, check, draw, and checkmate.
Our Canvas widget was set up in the the __init__
method of our GUI
class.
Let's modify it to include the top menu, as follows (see code 4.06: gui.py):
def __init__(self, parent, chessboard): self.chessboard = chessboard self.parent = parent self.menubar = Menu(parent) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="New Game", command=self.new_game) self.menubar.add_cascade(label="File", menu=self.filemenu) self.parent.config(menu=self.menubar)
Let's also add a bottom frame to display game statistics to the same __init__
method, as follows:
self.btmfrm = Frame(parent, height=64) self.info_label = Label(self.btmfrm, text=" White to Start the Game ", fg=self.color2) self.info_label.pack(side=RIGHT, padx=8, pady=5) self.btmfrm.pack(fill="x", side=BOTTOM)
The modification to existing init method is highlighted. The code is self-explanatory. We have done similar things in all our previous projects.
The File | New game menu item calls on our method, new_game()
. The code for new_game()
is as follows (see code 4.06: gui.py):
def new_game(self): self.chessboard.show(chessboard.START_PATTERN) self.draw_board() self.draw_pieces() self.info_label.config(text="White to Start the Game", fg='red')
Finally, after every move, we want to update the label with details of the move and information about the next players turn. We also want to update the frame to display any error or exception that may have occurred during the move attempt. We accordingly modify the shift
method of our GUI
class to do this update for us as follows:
def shift(self, p1, p2): piece = self.chessboard[p1] try: dest_piece = self.chessboard[p2] except: dest_piece = None if dest_piece is None or dest_piece.color != piece.color: try: self.chessboard.shift(p1,p2) exceptchessboard.ChessError as error: self.info_label["text"] = error.__class__.__name__ else: turn = ('white' if piece.color == 'black' else 'black') self.info_label["text"] = '' + piece.color.capitalize() +" : "+ p1 + p2 + '' + turn.capitalize() + ''s turn'
The description of the code is listed as follows:
shift
method are highlighted. We have simply included the shift
method of our Board
class in a try except block. If the shift is successful, the Label widget is updated to show the current move and the next players turn.error.__class__.__name__
.3.138.204.186