Python Forum
[WxPython] Polishing an Othello game I wrote in wx
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[WxPython] Polishing an Othello game I wrote in wx
#6
This is old code. I've made further changes and updated my original post at the top of the thread.
I've implemented all the changes suggested here.
The updated code:
import wx
import time
import os

# The wxPython implementation of an Othello game I wrote for my mother.
# These are displayed in help windows when an item from the help menu is selected:
gameRules = """Game Rules

Othello is a game played on a board with an 8x8 grid on it. There are 2 players and 64 gamepieces, enough to fill the entire gameboard. Each piece has a black side and a white side and each player plays as either black or white. The goal is when either the board is filled or their is no valid move available to either player for the majority of the pieces on the board to have your color upturned.

The application will automatically assess whether an attempted move is valid but to alleviate the frustration of guessing where one can place a gamepiece, here is a brief explanation:

If a space is already occupied, the move is invalid.

If there are no adjacent pieces, the move is invalid.

When there are adjacent pieces, their must be at least one vertical, horizontal or diagonal row of your opponents pieces with another of your pieces on the other end.

When you place a gamepiece, all adjacent vertical, horizontal or diagonal rows of your opponents pieces with another of your pieces at the other end will be flipped.

You may occaisionally find yourself in a situation in which there is no valid move available to you but your opponent has a valid move. You can give your opponent your move by clicking their player button. The text in their button will turn red, indicating that it is their turn. If there are no valid moves available to you, it will say so in the status bar.
"""

applicationHelp = """Application Help

Options Menu:

    The options menu provides options for starting a new game,
    saving a game, opening an existing game, saving and quitting and
    quit without saving. A single player gamemode is also listed in
    this menu, but it is not yet implemented.

Give Move to Opponent:

    There are situations in which the current player has no valid
    move, but their opponent does. In this situation, you give your
    move to your opponent by clicking their player button (one of the
    large buttons at the top or bottom of the window.) The text in
    their button will turn red indicating that it's their move.

Options Menu Items:

    New Game -- Start a new game.

    New Single Player Game -- coming soon

    Save Game -- Displays a file navigator to locate and select a save
        file to save the current game. The destination file must be a
        text file (*.txt). The application will remember the path of a
        current saved game until it is closed, so you won't be prompted
        for a save file if you have specified one already. When 'new
        game' is clicked, the path of any previously specified save file is
        forgotten to avoid overwriting a pre-existing saved game.

    Save Game As -- Allows you to save a previously saved game
        under a different name. This feature can be used for among
        other things, creating back-ups of your saves.

    Open Game -- Displays a file navigator to locate the a save file
        (*.txt) to open a pre-existing game. The filepath of the
        selected game is remembered until the application is closed,
        so you won't be prompted to re-select the file when saving.

    Save and Quit -- Automatically saves the game before exiting. If
        no file has been previously specified, the user will be prompted
        for a save file.

    Quit Without Saving -- Quits the game without saving.
"""

# The program itself is implemented inside a class for encapsulation and to allow import,
# ease of implementation, and readability.

class OthelloGameFrame(wx.Frame):

    # I know it is not recommended to create custom IDs but I didn't find wx IDs which
    # corresponded to the actions of these four menu items.
    ID_NEW_SINGLE_PLAYER = wx.NewIdRef(1)
    ID_SAVE_AND_QUIT = wx.NewIdRef(1)
    ID_GAMERULES = wx.NewIdRef(1)
    ID_QUIT_WITHOUT_SAVING = wx.NewIdRef(1)
    # Constants for buttons:
    PLAYER1BUTT = wx.NewIdRef(1)
    PLAYER2BUTT = wx.NewIdRef(1)
    GAMEBOARDBUTTS_LOWER = 5929 # GAMEBOARDBUTTS_UPPER - 64
    GAMEBOARDBUTTS_UPPER = 5993
    # Color Constants:
    bgAndBoardColor = wx.Colour(0x41, 0xA1, 0x23)
    player1Color = wx.Colour(0x00, 0x00, 0x00)
    player2Color = wx.Colour(0xFF, 0xFF, 0xFF)
    def __init__ (self, *args, **kwArgs):
        wx.Frame.__init__(self, *args, **kwArgs)
        # non-GUI related instance variables:
        self.saveFile = ""
        self.firstPlayersMove = True

        self.SetBackgroundColour(wx.Colour(0x30, 0x30, 0x30))
        self.CreateStatusBar()

        # Creating an options menu with all the non-gameplay related options
        # I want to make available to the user.
        self.optionsMenu = wx.Menu()
        menuNewGame = self.optionsMenu.Append(wx.ID_NEW, "&New Game", "Start a new game.")
        menuNewSinglePlayer = self.optionsMenu.Append(self.ID_NEW_SINGLE_PLAYER, "New Single &Player Game (Not yet implemented)", "Start a game against the AI. This feature is currently unavailable.")
        self.optionsMenu.AppendSeparator()
        menuSaveGame = self.optionsMenu.Append(wx.ID_SAVE, "&Save Game", "Save the current game and remember the filename for future saves.")
        menuSaveAs = self.optionsMenu.Append(wx.ID_SAVEAS, "Save Game &As...", "Save a previously save game under a new name.")
        menuOpenGame = self.optionsMenu.Append(wx.ID_OPEN, "&Open Game", "Open a previously saved game.")
        menuSaveAndQuit = self.optionsMenu.Append(self.ID_SAVE_AND_QUIT, "Sa&ve and Quit", "Save the game and quit.")
        menuQuitWithoutSaving = self.optionsMenu.Append(self.ID_QUIT_WITHOUT_SAVING, "Quit &Without Saving", "Close the application without saving the game.")

        # The help menu will display instances of HelpWindow containing a helptext
        # appropriate to the menu item selected.
        self.helpMenu = wx.Menu()
        menuShowGamerules = self.helpMenu.Append(self.ID_GAMERULES, "Game&rules", "Explains Othello game rules.")
        menuShowAppHelp = self.helpMenu.Append(wx.ID_HELP, "Application &Help", "How to use this software")

        # Create the toolbar.
        self.toolbar = wx.MenuBar()
        self.toolbar.Append(self.optionsMenu, "&Options")
        self.toolbar.Append(self.helpMenu, "&Help")
        self.SetMenuBar(self.toolbar)

        # Add Widgets
        player1ButtonFont = wx.Font(30, wx.ROMAN, wx.NORMAL, wx.NORMAL)
        player2ButtonFont = wx.Font(30, wx.ROMAN, wx.NORMAL, wx.NORMAL)
        gameboardButtonFont = wx.Font(12, wx.ROMAN, wx.NORMAL, wx.NORMAL)
        # The gameboard buttons are added iteratively. (There are 64 of them. If anybody
        # knows a better way to do this, I'm all ears. This code is rather messy.)
        throwaway = []
        for i in range(64):
            # That's a tuple being appended to the list. I know a tuple literal as the
            # single argument to a function is a little unreadable.
            gameboardButton = wx.Button(self, self.GAMEBOARDBUTTS_UPPER - i, "", style = wx.NO_BORDER)
            gameboardButton.SetFont(gameboardButtonFont)
            gameboardButton.SetBackgroundColour(self.bgAndBoardColor)
            gameboardButton.SetForegroundColour(wx.Colour(0xFF, 0x00, 0x00))
            throwaway.append(  (gameboardButton, 0, wx.EXPAND)  )

        buttonGrid = wx.GridSizer(8, 8, 0, 0)
        buttonGrid.SetHGap(2)
        buttonGrid.SetVGap(2)
        buttonGrid.AddMany(throwaway)
        self.gameboard = [[]]
        thrIndex = 0
        for row in range(8):
            for col in range(8):
                self.gameboard[-1].append(throwaway[thrIndex][0])
                thrIndex += 1
            self.gameboard.append([])
        del self.gameboard[-1]

        # Creating the layout:
        self.player1Butt = wx.Button(self, self.PLAYER1BUTT, "Player 1", style = wx.NO_BORDER)
        self.player1Butt.SetFont(player1ButtonFont)
        self.player1Butt.SetBackgroundColour(self.player1Color)
        self.player1Butt.SetForegroundColour(wx.Colour(0xFF, 0x00, 0x00))
        self.player2Butt = wx.Button(self, self.PLAYER2BUTT, "Player 2", style = wx.NO_BORDER)
        self.player2Butt.SetFont(player2ButtonFont)
        self.player2Butt.SetBackgroundColour(self.player2Color)
        self.layout = wx.BoxSizer(wx.VERTICAL)
        self.layout.Add(self.player1Butt, 1, wx.EXPAND)
        self.layout.Add(buttonGrid, 8, wx.CENTRE)
        self.layout.Add(self.player2Butt, 1, wx.EXPAND)

        self.SetSizer(self.layout)

        # Bind the menu events to their respective callbacks.
        self.Bind(wx.EVT_MENU, self.newGame, menuNewGame)
        self.Bind(wx.EVT_MENU, self.newSinglePlayer, menuNewSinglePlayer)
        
        self.Bind(wx.EVT_MENU, self.saveGame, menuSaveGame)
        self.Bind(wx.EVT_MENU, self.saveAs, menuSaveAs)
        self.Bind(wx.EVT_MENU, self.OpenGame, menuOpenGame)
        self.Bind(wx.EVT_MENU, self.saveAndQuit, menuSaveAndQuit)
        self.Bind(wx.EVT_MENU, self.quitWithoutSaving, menuQuitWithoutSaving)

        self.Bind(wx.EVT_MENU, self.showGameRules, menuShowGamerules)
        self.Bind(wx.EVT_MENU, self.showAppHelp, menuShowAppHelp)

        # Bind the player buttons to callbacks
        self.Bind(wx.EVT_BUTTON, self.player1ButtonClicked, id = self.PLAYER1BUTT)
        self.Bind(wx.EVT_BUTTON, self.player2ButtonClicked, id = self.PLAYER2BUTT)

        # Bind the gameboard button events to lambdas which pass row and col values to
        # self.gameboardButtonClicked appropriate to their position on the board.
        for row in range(8):
            for col in range(8):
                callbackLambda = eval(
                    "lambda evt: self.gameboardButtonClicked(evt, {}, {})".format(row, col),
                    {"self": self})
                self.Bind(wx.EVT_BUTTON, callbackLambda, self.gameboard[row][col])
        
        self.Show(True)
        self.newGame()

    def newGame (self, event = None):
        self.saveFile = ""
        for row in range(8):
            for col in range(8):
                self.gameboard[row][col].SetBackgroundColour(self.bgAndBoardColor)

        self.gameboard[3][3].SetBackgroundColour(self.player1Color)
        self.gameboard[3][4].SetBackgroundColour(self.player2Color)
        self.gameboard[4][3].SetBackgroundColour(self.player2Color)
        self.gameboard[4][4].SetBackgroundColour(self.player1Color)

        # For testing purposes:
        #self.gameboard[2][2].SetBackgroundColour(self.player2Color)
        #self.gameboard[2][5].SetBackgroundColour(self.player1Color)
        self.firstPlayersMove = True
        self.player1Butt.SetForegroundColour("RED")
        self.player2Butt.SetForegroundColour("BLACK")

    def newSinglePlayer (self, event = None):
        print("I am a computer. A smart, handsome programmer has to teach me Othello.")

    def saveGame (self, event = None):

        saveList = [[]]
        for row in range(8):
            for col in range(8):
                saveList[-1].append(
                    {str(self.bgAndBoardColor): 0, str(self.player1Color): 1, str(self.player2Color):2}[str(self.gameboard[row][col].GetBackgroundColour())])
            if row != 7: saveList.append([])

        saveDict = {"saveList": saveList, "firstPlayersMove": self.firstPlayersMove}

        if self.saveFile == "":

            fd = wx.FileDialog(self, "Select a file", os.getcwd(), "", "*.txt", wx.FD_OPEN)
            if fd.ShowModal() == wx.ID_OK:
                self.saveFile = fd.GetPath()
            else:
                fd.Destroy()
                return
            fd.Destroy()

        with open(self.saveFile, "w") as f:
            try:
                f.write(repr(saveDict))
            except FileNotFoundError:
                mdlg = wx.MessageDialog(self, "The currently selected file could not be accessed at this time. Please try again.", "wxOthello", wx.OK)
                mdlg.ShowModal()
                mdlg.Destroy()
                self.saveFile = ""

    def saveAs (self, event = None):
        self.saveFile = ""
        self.saveGame()

    def OpenGame (self, event = None):

        fd = wx.FileDialog(self, "Select a file", os.getcwd(), "", "*.txt", wx.FD_OPEN)
        if fd.ShowModal() == wx.ID_OK:
            self.saveFile = fd.GetPath()
        else:
            fd.Destroy()
            return
        fd.Destroy()

        with open(self.saveFile, "r") as f:
            try:
                saveDict = eval(f.read())
            except FileNotFoundError:
                mdlg = wx.MessageDialog(self, "The currently selected file could not be accessed at this time. Please try again.", "wxOthello", wx.OK)
                mdlg.ShowModal()
                mdlg.Destroy()
                self.saveFile = ""
            except SyntaxError:
                mdlg = wx.MessageDialog(self, "The currently selected file is either corrupted or its contents incompatible with opening in this game.", "wxOthello", wx.OK)
                mdlg.ShowModal()
                mdlg.Destroy()
                self.saveFile = ""

        self.firstPlayersMove = saveDict["firstPlayersMove"]
        for row in range(8):
            for col in range(8):
                self.gameboard[row][col].SetBackgroundColour([self.bgAndBoardColor, self.player1Color, self.player2Color][saveDict["saveList"][row][col]])

    def saveAndQuit (self, event = None):
        self.saveGame()
        self.Destroy()
        exit()

    def quitWithoutSaving (self, event = None):
        usersFinalDecision = wx.MessageBox("All progress you've made in this game will be lost. Are you sure you want to quit without saving? Answering 'no' will open a save dialog if no file was selected previously then exit the game.",
                                           "wxOthello", wx.YES_NO | wx.CANCEL, self)
        if usersFinalDecision == wx.YES:
            self.Destroy()
            exit()
        elif usersFinalDecision == wx.NO:
            self.saveGame()
        elif usersFinalDecision == wx.CANCEL:
            return

    def showGameRules (self, event = None):
        global gameRules
        self.showHelp(gameRules)

    def showAppHelp (self, event = None):
        global applicationHelp
        self.showHelp(applicationHelp)

    def showHelp(self, helpText):
        with HelpWindow(self, helpText) as hdlg:
            hdlg.ShowModal()

    def player1ButtonClicked (self, event = None):
        self.firstPlayersMove = True
        self.player1Butt.SetForegroundColour("RED")
        self.player2Butt.SetForegroundColour("BLACK")

    def player2ButtonClicked (self, event = None):
        self.firstPlayersMove = False
        self.player1Butt.SetForegroundColour("WHITE")
        self.player2Butt.SetForegroundColour("RED")

    def gameboardButtonClicked (self, event = None, row = 0, col = 0):

        # self,firstPlayersMove is a boolean indicating whether it's player 1s turn.
        if self.firstPlayersMove:
            me = self.player1Color
            opponent = self.player2Color

        else:
            me = self.player2Color
            opponent = self.player1Color

        # Detect invalid move attempts, inform the user that their move is invalid, and
        # return from the function.
        if not self.isValidMove(row, col, me, opponent):
            self.gameboard[row][col].SetLabel("Invalid\nMove!")
            time.sleep(1)
            self.gameboard[row][col].SetLabel("")
            return

        # Make the move selected by the player.
        self.makeMove(row, col, me, opponent)

        # The method detectWin returns a tuple with a boolean indicating whether there
        # are no valid moves available to either player and a message string appropriate to
        # the situation of 1: A player 1 victory, 2: A draw, or 3: A player 2 victory.
        winDetected, message = self.detectWin()
        if winDetected:
            m = wx.MessageDialog(self, message, "wxOthello")
            m.ShowModal()
            m.Destroy()

        # Invert the value of the self.firstPlayersMove flag and change the color of the
        # text in the player 1 and player 2 buttons in a manner according to whose turn it
        # is.
        self.firstPlayersMove = not self.firstPlayersMove

        if self.firstPlayersMove:
            self.player1Butt.SetForegroundColour("RED")
            self.player2Butt.SetForegroundColour("BLACK")
        else:
            self.player1Butt.SetForegroundColour("WHITE")
            self.player2Butt.SetForegroundColour("RED")

        # Inform the next player if there is no valid move available to them.
        if not self.moveAvailableToPlayer(opponent, me):

            if opponent == self.player1Color:
                self.SetStatusText("No move available to player 1.")
            else:
                self.SetStatusText("No move available to player 2.")
        else:
            self.SetStatusText("")

    def moveAvailableToPlayer(self, me, opponent):
        for row in range(8):
            for col in range(8):
                if self.isValidMove(row, col, me, opponent): return True
        return False

    def isValidMove (self, row, col, me, opponent):
        # Check whether the grid space is empty
        if self.gameboard[row][col].GetBackgroundColour() != self.bgAndBoardColor:
            return False

        # A series of scanning vectors for the 8 scanning directions: up, down, left, right and the four diagonal directions
        scanningDirections = ((-1, 0), (0, 1), (1, 0), (0, -1),
                              (-1, -1), (-1, 1), (1, 1), (1, -1))

        for SDRow, SDCol in scanningDirections:
            currentRow = row + SDRow
            currentCol = col + SDCol
            sawOpponent = False
            while currentRow in range(0, 8) and currentCol in range(0, 8):
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == self.bgAndBoardColor: break
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == opponent: sawOpponent = True
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and sawOpponent: return True
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and not sawOpponent: break
                currentRow += SDRow
                currentCol += SDCol
        
        return False

    def makeMove (self, row, col, me, opponent):
        # Put down the players gamepiece
        self.gameboard[row][col].SetBackgroundColour(me)

        # A series of scanning vectors for the 8 scanning directions: up, down, left, right and the four diagonal directions
        scanningDirections = ((-1, 0), (0, 1), (1, 0), (0, -1),
                              (-1, -1), (-1, 1), (1, 1), (1, -1))

        for SDRow, SDCol in scanningDirections:
            currentRow = row + SDRow
            currentCol = col + SDCol
            sawOpponent = False
            canFlipPieces = False
            while currentRow in range(0, 8) and currentCol in range(0, 8):
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == self.bgAndBoardColor: break
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == opponent: sawOpponent = True
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and sawOpponent:
                    canFlipPieces = True
                    break
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and not sawOpponent: break
                currentRow += SDRow
                currentCol += SDCol

            currentRow = row + SDRow
            currentCol = col + SDCol
            while canFlipPieces and currentRow in range(0, 8) and currentCol in range(0, 8):
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == opponent:
                    self.gameboard[currentRow][currentCol].SetBackgroundColour(me)
                elif self.gameboard[currentRow][currentCol].GetBackgroundColour() == me:
                    break
                else:
                    print("Kyle, you have some debugging to do! This else clause is never supposed to execute. Something has gone horribly wrong!")
                currentRow += SDRow
                currentCol += SDCol

    def detectWin (self):

        noValidMoves = True
        player1Count = 0
        player2Count = 0
        for row in range(8):
            for col in range(8):
                if self.isValidMove(row, col, self.player1Color, self.player2Color) or self.isValidMove(row, col, self.player2Color, self.player1Color): noValidMoves = False
                if self.gameboard[row][col].GetBackgroundColour() == self.player1Color: player1Count += 1
                if self.gameboard[row][col].GetBackgroundColour() == self.player2Color: player2Count += 1

        if noValidMoves:
            if player1Count > player2Count:
                return True, "The winner is player 1!"
            elif player1Count == player2Count:
                return True, "This game is a draw!"
            elif player1Count < player2Count:
                return True, "The winner is player 2!"
            
        else:
            return False, "You're not supposed to see this message."

class HelpWindow(wx.Dialog):
    def __init__ (self, parent, helpText):
        wx.Dialog.__init__(self, parent, -1, helpText.split("\n")[0])
        self.SetMinSize(wx.Size(400, 400))
        self.topExitButton = wx.Button(self, wx.ID_CLOSE, "Close Help")
        self.helpDisplay = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = helpText,
                                       style = wx.TE_MULTILINE | wx.TE_READONLY)
        self.bottomExitButton = wx.Button(self, wx.ID_CLOSE, "Close Help")
        self.layout = wx.BoxSizer(wx.VERTICAL)
        self.layout.Add(self.topExitButton, 1, wx.EXPAND)
        self.layout.Add(self.helpDisplay, 10, wx.EXPAND)
        self.layout.Add(self.bottomExitButton, 1, wx.EXPAND)
        self.SetSizer(self.layout)

        self.Fit()
        self.Bind(wx.EVT_BUTTON, self.closeHelp, id = wx.ID_CLOSE)

    def closeHelp(self, event = None):
        self.EndModal(wx.ID_ANY)

if __name__ == "__main__":
    app = wx.App()
    theApp = OthelloGameFrame(parent = None, id = wx.ID_ANY, size = (700, 800), title = "wxOthello")
    app.MainLoop()
'OthelloGameFrame' I like it. I'm going to browse the wxPython docs for information on how to display the 'Invalid Move' text on the buttons without freezing the event loop.

I've changed time.sleep to wx.MilliSleep. I don't know whether that also halts the event loop. Maybe.
Reply


Messages In This Thread
Polishing an Othello game I wrote in wx - by keames - Apr-18-2019, 08:48 PM
RE: Polishing an Othello game I wrote in wx - by keames - Apr-19-2019, 09:48 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020