Python Forum

Full Version: Adding a single player mode to my wxOthello game
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
Below is the source code to an Othello game I've written for my mother. I would like to add a single player game mode to this game but I know next to nothing about AI, including game AI. I don't even know how to begin. Maybe I could use a neural network, but for an Othello game that may be a bit overkill. If not a neural network, what? I've had my heart set on adding a single player mode to this game since the beginning of this project. Any help would be greatly appreciated.
import wx
import os
from functools import partial

# 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):
    """
    The Othello game proper. Almost all of the code that makes this app work is in here.
    It uses a pretty standard constructor for a class inheriting from Frame:

    __init__(self, *args, **kwArgs) Passing in the size parameter is recommended.
    """
    # 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)
    # 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)
        """
        OthelloGameFrame.__init__(self, *args, *kwArgs)
        Returns an object representing the main window of the Othello game app.
        Specifying the size parameter in the arg list is recommended. Otherwise, it
        works just like a normal wx.Frame.
        """
        # non-GUI related instance variables:
        self.saveFile = ""
        self.firstPlayersMove = True
        self.gameAltered = False

        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)

        # You should see what this code looked like before I put this in!
        # Thank you, yoriz!
        buttonGrid = wx.GridSizer(8, 8, 0, 0)
        buttonGrid.SetHGap(2)
        buttonGrid.SetVGap(2)
        
        self.gameboard = []
        for row in range(8):
            board_columns = []
            for col in range(8):
                btn = wx.Button(self, style=wx.NO_BORDER)
                btn.SetFont(gameboardButtonFont)
                btn.SetBackgroundColour(self.bgAndBoardColor)
                btn.SetForegroundColour(wx.Colour(0xFF, 0x00, 0x00))
                btn.Bind(wx.EVT_BUTTON,
                         partial(self.gameboardButtonClicked, row=row, col=col))
                buttonGrid.Add(btn, 0, wx.EXPAND)
                board_columns.append(btn)
            self.gameboard.append(board_columns)

        # 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 all close events to self.quitWithoutSaving to ensure the user is always
        # asked whether they're sure they want to quit without saving their game.
        self.Bind(wx.EVT_CLOSE, self.quitWithoutSaving)

        self.Show(True)
        self.newGame()


    def newGame (self, event = None):
        """
        OthelloGameFrame.newGame(self, event = None)
        Resets the gameboard and resets the saveFile field to prevent an existing game from being overwritten.
        """
        self.saveFile = ""
        self.gameAltered = False
        for row in range(8):
            for col in range(8):
                self.gameboard[row][col].SetBackgroundColour(self.bgAndBoardColor)

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

        # 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):
        """
        OthelloGameFrame.newSinglePlayer(self, event = None)
        This feature is not yet implemented.
        """
        print("I am a computer. A smart, handsome programmer has to teach me Othello.")

    def saveGame (self, event = None):
        """
        OthelloGameFrame.saveGame(self, event = None)
        Prompt the user for a file in which to save the game if none has been selected yet
        and save the game
        """
        saveList = [[]]
        for row in range(8):
            for col in range(8):
                # Map each gameboard color to a number: 0 for empty space, 1 for player 1 (black), and 2 for player 2.
                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} # Save everything in a dictionary.

        # If no file has been previously selected, use a wx.FileDialog to get the
        # path of the file in which the user wants to save their game.
        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()

        # Save the game as a string representation of saveDict.
        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 = ""
        self.gameAltered = False

    def saveAs (self, event = None):
        """
        OthelloGameFrame.saveAs(self, event = None)
        Save a previously saved game under a different filename.
        """
        self.saveFile = ""
        self.saveGame()

    def openGame (self, event = None):
        """
        OthelloGameFrame.openGame(self, event = None)
        Open a previously saved game stored in the format described in the saveGame method
        {"saveList": [Nested lists containing integers mapped to gameboard colors], "firstPlayersMove": True/False}
        """
        # Use wx.FileDialog to get the save file to open.
        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()

        # Open the save file and convert its contents into a dictionary.
        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 = ""
                return
            # If the files contents are incompatible with the attempted parse into a dictionary, inform the user.
            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 = ""
                return

        # Load the dictionarys data into the relevant instance variables. When single player mode is implemented,
        # a check for the key "isSinglePlayer" will also need to be added here.
        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]])
        self.Refresh()
        self.gameAltered = False

    def saveAndQuit (self, event = None):
        """
        OthelloGameFrame.saveAndQuit(self, event = None)
        Saves the game and quits.
        """
        self.saveGame()
        self.Destroy()
        exit()

    def quitWithoutSaving (self, event = None):
        """
        OthelloGameFrame.quitWithoutSaving(self, event = None)
        If the game has been altered since last save, this function
        asks the user via messageBox whether they are sure they don't
        want to save. It exits the game if they answer yes, calls
        saveGame if they answer no and returns if they click cancel.
        """
        if self.gameAltered:
            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
        else:
            self.Destroy()
            exit()

    def showGameRules (self, event = None):
        """
        OthelloGameFrame.showGameRules(self, event = None)
        This callback displays an instance of HelpWindow that
        displays the rules of Othello as its help text with
        a call to showHelp.
        """
        global gameRules
        self.showHelp(gameRules)

    def showAppHelp (self, event = None):
        """
        OthelloGameFrame.showAppHelp(self, event = None)
        This callback displays an instance of HelpWindow that
        displays help information for this application with
        a call to showHelp.
        """
        global applicationHelp
        self.showHelp(applicationHelp)

    def showHelp(self, helpText):
        """
        OthelloGameFrame.showHelp(self, helpText)
        Displays an instance of HelpWindow displaying
        the value of helpText.
        """
        with HelpWindow(self, helpText) as hdlg:
            hdlg.ShowModal()

    def player1ButtonClicked (self, event = None):
        """
        OthelloGameFrame.player1ButtonClicked(self, event = None)
        Gives the next move to player 1. This feature is
        intended for use when it is player 2s turn and there are
        no moves available to player 2.
        """
        self.firstPlayersMove = True
        self.player1Butt.SetForegroundColour("RED")
        self.player2Butt.SetForegroundColour("BLACK")

    def player2ButtonClicked (self, event = None):
        """
        OthelloGameFrame.player2ButtonClicked(self, event = None)
        Gives the next move to player 2. This feature is
        intended for use when it is player 1s turn and there are
        no moves available to player 1.
        """
        self.firstPlayersMove = False
        self.player1Butt.SetForegroundColour("WHITE")
        self.player2Butt.SetForegroundColour("RED")

    def gameboardButtonClicked (self, event = None, row = 0, col = 0):
        """
        OthelloGameFrame.gameboardButtonClicked(self, event = None, row = 0, col = 0)
        This method is called through lambdas bound to the gameboard buttons generated
        in __init__. It displays an error message in the space where the move is
        attempted and returns if a move is invalid. Otherwise, it executes the move,
        checks whether somebody has won, gives the next move to the other player, and
        informs the next player if there is no move available to them in the status bar.
        """
        # 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 if their move is invalid and
        # the reason their move is invalid and return from the function.
        moveIsValid, message = self.isValidMove(row, col, me, opponent)
        if not moveIsValid:
            self.gameboard[row][col].SetLabel(message)
            wx.MilliSleep(1000)
            self.gameboard[row][col].SetLabel("")
            return

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

        # 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)[0]: return True
        return False

    def isValidMove (self, row, col, me, opponent):
        """
        OthelloGameFrame.isValidMove(self, row, col, me, opponent)
        This method returns the tuple (isValidMove, messaage). It tests
        whether a move at a specified position on the gameboard is valid
        for a specific player and if the move is invalid, returns a
        message explaining why the move is invalid.
        """
        # Check whether the grid space is empty
        if self.gameboard[row][col].GetBackgroundColour() != self.bgAndBoardColor:
            return False, "This Space\nIs Occupied!"

        # 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))

        # Iterate over the diffetent scanning directions, return True if the move is valid and set message to a message string
        # that explains why the move is invalid, if the move is invalid.
        message = "No Adjacent\nGamepieces!"
        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
                else:
                    message = "No Pieces\nTo Flip!"
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == opponent: sawOpponent = True
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and sawOpponent:
                    return True, "You won't see this message!"
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and not sawOpponent: break

                currentRow += SDRow
                currentCol += SDCol
        
        return False, message

    def makeMove (self, row, col, me, opponent):
        """
        OthelloGameFrame.makeMove(self, row, col, me, opponent)
        Performs a move for a specified player at a specified position.
        """
        # 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))

        # Iterate over the scanning vectors.
        for SDRow, SDCol in scanningDirections:
            currentRow = row + SDRow
            currentCol = col + SDCol
            sawOpponent = False
            canFlipPieces = False
            # Check whether gamepieces can be flipped in the current scanning direction.
            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

            # If gamepieces can be flipped in the current scanning direction, flip the pieces.
            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):
        """
        OthelloGameFrame.detectWin(self)
        This method returns a the tuple (noValidMoves, message), where noValidMoves is a boolean indicating whether there are no more valid moves
        available to either player and message is one of the the strings "The winner is player 1!", if the majority of the pieces on the board are
        black, "This game is a draw!" if player 1 and player 2 have equal numbers of pieces on the board, or "The winner is player 2!" if the
        majority of the pieces on the board are white.
        """
        noValidMoves = True # We begin by assuming that neither player has a valid move available to them.
        player1Count = 0    # Counters for the number of spaces each player has captured.
        player2Count = 0
        # Iterate over the gameboard. Check whether there is a valid move available to either player and
        # count the number of spaces captured by each player.
        for row in range(8):
            for col in range(8):
                if self.isValidMove(row, col, self.player1Color, self.player2Color)[0] or self.isValidMove(row, col, self.player2Color, self.player1Color)[0]: noValidMoves = False
                if self.gameboard[row][col].GetBackgroundColour() == self.player1Color: player1Count += 1
                if self.gameboard[row][col].GetBackgroundColour() == self.player2Color: player2Count += 1

        if noValidMoves:
            # Return True and a message indicating who won
            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):
    """
    A simple dialog class for displaying help information to the user.
    """
    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()
The most I could help with is telling you how to start. I would start by making an AI class and adding similar functions as the player, but run by what the player is doing. I've made a game with enemies, nothing this complicated, but i'll give you an example. To move the enemy I found the pos of the player and moved the bot towards the pos. I hope this gives you a place to start.

I literally can't understand a lot of the code because I use pygame when I make games.

I'll see if I can familiarize myself with functool and wx
That's good advice. I haven't used pygame since 2014! How is it over there in pygamia? I'd be surprised if they didn't update it since then. Do you still have to write the event loop yourself or did they implement mainloop and bind functions?
Well you can do this -
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key = pygame.key.K_LEFT
            print('left arrow key pressed')
or you can do -
keyed = pygame.event.get_pressed()
if keyed[K_LEFT]:
        print('left arrow key pressed')

So they still have event loops but they also have the one at the bottom. But to see if someone needs to exit the game it's back to event loops
One way is to create a value for each play area.
You can have many values.
Corners would have best place value.
Change value. How many would change to your color.
And whatever else you can think of.

Then you can have computer choose the best option or second best option.
Depends how smart you want the computer to be.

(Apr-20-2019, 03:41 AM)keames Wrote: [ -> ]That's good advice. I haven't used pygame since 2014! How is it over there in pygamia? I'd be surprised if they didn't update it since then. Do you still have to write the event loop yourself or did they implement mainloop and bind functions?
Why would they need to change to widget event system. If you wanted that in pygame. It really easy to do.
Here one way of doing it.
import pygame

class State:
    def __init__(self):
        self._bind_event = {}

    def bind(self, event, callback):
        if self._bind_event.get(event, False):
            self._bind_event[event].append(callback)
        else:
            self._bind_event[event] = [callback]

    def draw(self, surface): pass
    def _event(self, event):
        group = self._bind_event.get(event.type, False)
        if group:
            for callback in group:
                callback(event)

    def update(self): pass

class StateMachine:
    @classmethod
    def setup(cls, caption, width, height):
        # Basic Pygame Setup
        pygame.display.set_caption(caption)
        cls.surface = pygame.display.set_mode((width, height))
        cls.rect = cls.surface.get_rect()
        cls.clock = pygame.time.Clock()
        cls.running = False
        cls.delta = 0
        cls.fps = 30

        # State Interface
        cls.states = {}
        cls.state = State()

    @classmethod
    def mainloop(cls):
        cls.running = True
        while cls.running:
            for event in pygame.event.get():
                cls.state._event(event)

            cls.state.update()
            cls.state.draw(cls.surface)
            pygame.display.flip()
            cls.delta = cls.clock.tick(cls.fps)

class Scene(State):
    def __init__(self):
        State.__init__(self)
        self.bind(pygame.MOUSEBUTTONDOWN, self.on_mousebuttondown)
        self.bind(pygame.QUIT, self.on_quit)

    def draw(self, surface):
        surface.fill(pygame.Color("navy"))

    def on_mousebuttondown(self, event):
        print(event.button)

    def on_quit(self, event):
        StateMachine.running = False

def main():
    pygame.init()
    StateMachine.setup("Example", 400, 300)
    StateMachine.state = Scene()
    StateMachine.mainloop()
    pygame.quit()

main()
So, basically assign priority codes to each coordinate based on its strategic value and then when it's the bots turn to make a move, it picks the highest priority space which is also a valid move. I can even add in a difficulty setting which allows the user to vary the probability of the bot making a random move, a 'mistake.' I'll write something and post it on the thread. This will take a little time...
I took you guys' advice and created the player bot. It works...kinda.
Here's the updated code. I just finished writing the internal documentation and docstrings.
import wx
import os
from functools import partial
import random

# 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):
    """
    The Othello game proper. Almost all of the code that makes this app work is in here.
    It uses a pretty standard constructor for a class inheriting from Frame:

    __init__(self, *args, **kwArgs) Passing in the size parameter is recommended.
    """
    # 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)
    # 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)
        """
        OthelloGameFrame.__init__(self, *args, *kwArgs)
        Returns an object representing the main window of the Othello game app.
        Specifying the size parameter in the arg list is recommended. Otherwise, it
        works just like a normal wx.Frame.
        """
        # non-GUI related instance variables:
        self.saveFile = ""
        self.firstPlayersMove = True
        self.gameAltered = False
        self.robot = False # All instances of classes evaluate to True unless __bool__ is defined and can return False.
                           # Basically, whether the game is single player or 2 player is indicated by whether this object,
                           # whatever its type evaluates to 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)

        # You should see what this code looked like before I put this in!
        # Thank you, yoriz!
        buttonGrid = wx.GridSizer(8, 8, 0, 0)
        buttonGrid.SetHGap(2)
        buttonGrid.SetVGap(2)
        
        self.gameboard = []
        for row in range(8):
            board_columns = []
            for col in range(8):
                btn = wx.Button(self, style=wx.NO_BORDER)
                btn.SetFont(gameboardButtonFont)
                btn.SetBackgroundColour(self.bgAndBoardColor)
                btn.SetForegroundColour(wx.Colour(0xFF, 0x00, 0x00))
                btn.Bind(wx.EVT_BUTTON,
                         partial(self.gameboardButtonClicked, row=row, col=col))
                buttonGrid.Add(btn, 0, wx.EXPAND)
                board_columns.append(btn)
            self.gameboard.append(board_columns)

        # 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 all close events to self.quitWithoutSaving to ensure the user is always
        # asked whether they're sure they want to quit without saving their game.
        self.Bind(wx.EVT_CLOSE, self.quitWithoutSaving)

        self.Show(True)
        self.newGame()

    def newGame (self, event = None):
        """
        OthelloGameFrame.newGame(self, event = None)
        Resets the gameboard and resets the saveFile field to prevent an existing game from being overwritten.
        """
        self.saveFile = ""
        self.gameAltered = False
        for row in range(8):
            for col in range(8):
                self.gameboard[row][col].SetBackgroundColour(self.bgAndBoardColor)

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

        # 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):
        """
        OthelloGameFrame.newSinglePlayer(self, event = None)
        This feature is not yet implemented.
        """
        with SelectDifficultyDialog(self) as dlg:
            if dlg.ShowModal() == wx.ID_OK:
                self.newGame()
                self.robot = PlayerBot(self, dlg.getCurrentDifficulty())
                self.SetStatusText("")
            else:
                self.SetStatusText("New single player aborted.")
                return

    def saveGame (self, event = None):
        """
        OthelloGameFrame.saveGame(self, event = None)
        Prompt the user for a file in which to save the game if none has been selected yet
        and save the game
        """
        saveList = [[]]
        for row in range(8):
            for col in range(8):
                # Map each gameboard color to a number: 0 for empty space, 1 for player 1 (black), and 2 for player 2.
                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([])

        isSinglePlayer = False;
        if self.robot: isSinglePlayer = True
        saveDict = {"saveList": saveList, "firstPlayersMove": self.firstPlayersMove, "isSinglePlayer": isSinglePlayer} # Save everything in a dictionary.
        if self.robot: saveDict["difficulty"] = self.robot.difficulty

        # If no file has been previously selected, use a wx.FileDialog to get the
        # path of the file in which the user wants to save their game.
        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()

        # Save the game as a string representation of saveDict.
        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 = ""
        self.gameAltered = False

    def saveAs (self, event = None):
        """
        OthelloGameFrame.saveAs(self, event = None)
        Save a previously saved game under a different filename.
        """
        self.saveFile = ""
        self.saveGame()

    def openGame (self, event = None):
        """
        OthelloGameFrame.openGame(self, event = None)
        Open a previously saved game stored in the format described in the saveGame method
        {"saveList": [Nested lists containing integers mapped to gameboard colors], "firstPlayersMove": True/False}
        """
        # Use wx.FileDialog to get the save file to open.
        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()

        # Open the save file and convert its contents into a dictionary.
        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 = ""
                return
            # If the files contents are incompatible with the attempted parse into a dictionary, inform the user.
            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 = ""
                return

        # Load the dictionarys data into the relevant instance variables. When single player mode is implemented,
        # a check for the key "isSinglePlayer" will also need to be added here.
        self.firstPlayersMove = saveDict["firstPlayersMove"]
        if "isSinglePlayer" in saveDict:
            if saveDict["isSinglePlayer"]:
                self.robot = PlayerBot(self, saveDict["difficulty"])
        
        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]])
        self.Refresh()
        self.gameAltered = False

    def saveAndQuit (self, event = None):
        """
        OthelloGameFrame.saveAndQuit(self, event = None)
        Saves the game and quits.
        """
        self.saveGame()
        self.Destroy()
        exit()

    def quitWithoutSaving (self, event = None):
        """
        OthelloGameFrame.quitWithoutSaving(self, event = None)
        If the game has been altered since last save, this function
        asks the user via messageBox whether they are sure they don't
        want to save. It exits the game if they answer yes, calls
        saveGame if they answer no and returns if they click cancel.
        """
        if self.gameAltered:
            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
        else:
            self.Destroy()
            exit()

    def showGameRules (self, event = None):
        """
        OthelloGameFrame.showGameRules(self, event = None)
        This callback displays an instance of HelpWindow that
        displays the rules of Othello as its help text with
        a call to showHelp.
        """
        global gameRules
        self.showHelp(gameRules)

    def showAppHelp (self, event = None):
        """
        OthelloGameFrame.showAppHelp(self, event = None)
        This callback displays an instance of HelpWindow that
        displays help information for this application with
        a call to showHelp.
        """
        global applicationHelp
        self.showHelp(applicationHelp)

    def showHelp(self, helpText):
        """
        OthelloGameFrame.showHelp(self, helpText)
        Displays an instance of HelpWindow displaying
        the value of helpText.
        """
        with HelpWindow(self, helpText) as hdlg:
            hdlg.ShowModal()

    def player1ButtonClicked (self, event = None):
        """
        OthelloGameFrame.player1ButtonClicked(self, event = None)
        Gives the next move to player 1. This feature is
        intended for use when it is player 2s turn and there are
        no moves available to player 2.
        """
        self.firstPlayersMove = True
        self.player1Butt.SetForegroundColour("RED")
        self.player2Butt.SetForegroundColour("BLACK")

    def player2ButtonClicked (self, event = None):
        """
        OthelloGameFrame.player2ButtonClicked(self, event = None)
        Gives the next move to player 2. This feature is
        intended for use when it is player 1s turn and there are
        no moves available to player 1.
        """
        self.firstPlayersMove = False
        self.player1Butt.SetForegroundColour("WHITE")
        self.player2Butt.SetForegroundColour("RED")
        if self.robot:
            self.robot.makeMove()

    def gameboardButtonClicked (self, event = None, row = 0, col = 0):
        """
        OthelloGameFrame.gameboardButtonClicked(self, event = None, row = 0, col = 0)
        This method is called through lambdas bound to the gameboard buttons generated
        in __init__. It displays an error message in the space where the move is
        attempted and returns if a move is invalid. Otherwise, it executes the move,
        checks whether somebody has won, gives the next move to the other player, and
        informs the next player if there is no move available to them in the status bar.
        """
        # 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 if their move is invalid and
        # the reason their move is invalid and return from the function.
        moveIsValid, message = self.isValidMove(row, col, me, opponent)
        if not moveIsValid:
            self.gameboard[row][col].SetLabel(message)
            wx.MilliSleep(1000)
            self.gameboard[row][col].SetLabel("")
            return

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

        # 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()
            self.gameAltered = False

        # 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("")

        # If in single player mode, let the bot make a move and then return.
        if self.robot and not self.firstPlayersMove:
            self.robot.makeMove()
            return

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

    def isValidMove (self, row, col, me, opponent):
        """
        OthelloGameFrame.isValidMove(self, row, col, me, opponent)
        This method returns the tuple (isValidMove, messaage). It tests
        whether a move at a specified position on the gameboard is valid
        for a specific player and if the move is invalid, returns a
        message explaining why the move is invalid.
        """
        # Check whether the grid space is empty
        if self.gameboard[row][col].GetBackgroundColour() != self.bgAndBoardColor:
            return False, "This Space\nIs Occupied!"

        # 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))

        # Iterate over the diffetent scanning directions, return True if the move is valid and set message to a message string
        # that explains why the move is invalid, if the move is invalid.
        message = "No Adjacent\nGamepieces!"
        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
                else:
                    message = "No Pieces\nTo Flip!"
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == opponent: sawOpponent = True
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and sawOpponent:
                    return True, "You won't see this message!"
                if self.gameboard[currentRow][currentCol].GetBackgroundColour() == me and not sawOpponent: break

                currentRow += SDRow
                currentCol += SDCol
        
        return False, message

    def makeMove (self, row, col, me, opponent):
        """
        OthelloGameFrame.makeMove(self, row, col, me, opponent)
        Performs a move for a specified player at a specified position.
        """
        # 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))

        # Iterate over the scanning vectors.
        for SDRow, SDCol in scanningDirections:
            currentRow = row + SDRow
            currentCol = col + SDCol
            sawOpponent = False
            canFlipPieces = False
            # Check whether gamepieces can be flipped in the current scanning direction.
            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

            # If gamepieces can be flipped in the current scanning direction, flip the pieces.
            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):
        """
        OthelloGameFrame.detectWin(self)
        This method returns a the tuple (noValidMoves, message), where noValidMoves is a boolean indicating whether there are no more valid moves
        available to either player and message is one of the the strings "The winner is player 1!", if the majority of the pieces on the board are
        black, "This game is a draw!" if player 1 and player 2 have equal numbers of pieces on the board, or "The winner is player 2!" if the
        majority of the pieces on the board are white.
        """
        noValidMoves = True # We begin by assuming that neither player has a valid move available to them.
        player1Count = 0    # Counters for the number of spaces each player has captured.
        player2Count = 0
        # Iterate over the gameboard. Check whether there is a valid move available to either player and
        # count the number of spaces captured by each player.
        for row in range(8):
            for col in range(8):
                if self.isValidMove(row, col, self.player1Color, self.player2Color)[0] or self.isValidMove(row, col, self.player2Color, self.player1Color)[0]: noValidMoves = False
                if self.gameboard[row][col].GetBackgroundColour() == self.player1Color: player1Count += 1
                if self.gameboard[row][col].GetBackgroundColour() == self.player2Color: player2Count += 1

        if noValidMoves:
            # Return True and a message indicating who won
            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 PlayerBot:

    """
    Instances of this class play as player 2 in single player mode.
    class PlayerBot:
        __init__(self, parent, difficulty)
        parent - and OthelloGameFrame instance
        difficulty - an integer between 0 and 100
    """
    # Zero and above are indicate levels of desireability: 0 for most desireable,
    # 1 less desireable than 0 and so on. 4 is least desireable and -2 is
    # guaranteed impossible.
    priorityMap = [[0,4,1, 2, 2,1,4,0],
                   [4,4,3, 2, 2,3,4,4],
                   [1,3,1, 2, 2,1,3,1],
                   [2,2,2,-2,-2,2,2,2],
                   [2,2,2,-2,-2,2,2,2],
                   [1,3,1, 2, 2,1,3,1],
                   [4,4,3, 2, 2,3,4,4],
                   [0,4,1, 2, 2,1,4,0]]

    # Those 1s and 0s in there are actually booleans; more accurately, they evaluate
    # to True and False. I used 1s and 0s for readability but they are actually True
    # and False. Don't be fooled. Each boolean flag indicates whether the priority
    # given to the corresponding grid space can be altered. I will add logic for
    # varying the priority of certain moves later.
    variabilityMap = [[0,1,1,1,1,1,1,0],
                      [1,0,1,1,1,1,0,1],
                      [1,1,0,1,1,0,1,1],
                      [1,1,1,0,0,1,1,1],
                      [1,1,1,0,1,1,1,1],
                      [1,1,0,1,1,0,1,1],
                      [1,0,1,1,1,1,0,1],
                      [0,1,1,1,1,1,1,0]]

    def __init__ (self, parent, difficulty):
        self.parent = parent
        self.difficulty = difficulty

    def makeMove(self):
        """
        PlayerBot.makeMove(self)
        This method tries to make its best to make thepossible move given the current state
        of the game. It can be a bit of a numty sometimes, but I still love it :)
        """
        # Create a list of all currently valid moves as a list of tuples with the row at index 0
        # and the column at index 1 in each tuple.
        validMoves = []
        for row in range(8):
            for col in range(8):
                if self.parent.isValidMove(row, col, self.parent.player2Color, self.parent.player1Color)[0]:
                    validMoves.append( (row, col) )

        # If no valid move is available to the bot, give the next move to player 1.
        if validMoves == []:
            self.parent.player1ButtonClicked()
            return

        # The difficulty setting varies the probability of the bot making a 'mistake' That is,
        # making a purely random move from the set of all possible moves. Here, we just make a
        # 'mistake' if random.randint(0, 100) returns a number greater than the set difficulty.
        if random.randint(0, 100) < self.difficulty:
            # This code is pretty ugly. If anybody write a more elegant solution to the problem this code solves,
            # I would greatly appreciate it. Here, we get only the most desirable move from the set of all possible
            # moves and select randomly from them.
            highestPriorityMoves = [validMoves[0]]
            for i in validMoves:
                if self.priorityMap[i[0]][i[1]] < self.priorityMap[highestPriorityMoves[0][0]][highestPriorityMoves[0][1]] and self.priorityMap[i[0]][i[1]] not in range(-2, 0):
                    highestPriorityMoves = [ i ]
                elif self.priorityMap[i[0]][i[1]] == self.priorityMap[highestPriorityMoves[0][0]][highestPriorityMoves[0][1]]:
                    highestPriorityMoves.append(i)
            randomMove = highestPriorityMoves[random.randint(0, len(highestPriorityMoves) - 1)]
            self.parent.gameboardButtonClicked(row = randomMove[0], col = randomMove[1])
        
        else:
            # Make a purely random move; a 'mistake.'
            randomMove = validMoves[random.randint(0, len(validMoves) - 1)]
            self.parent.gameboardButtonClicked(row = randomMove[0], col = randomMove[1])

class SelectDifficultyDialog (wx.Dialog):
    """
    class SelectDifficultyDialog (wx.Dialog):
        __init__(self, parent)
        This object displays a dialog which prompts the user to set the difficulty
        using a slider. ShowModal returns wx.ID_OK if the user clicks the button
        labeled 'set difficulty' and wx.ID_CANCEL if the user closes the dialog.
        The getCurrentDifficulty method returns the difficulty selected by the user.
    """
    ID_DIFFICULTY_SLIDER = wx.NewIdRef(1) # An ID constant for the difficulty slider used to bind a callback to motion of the slider.

    def __init__(self, parent):
        # Create all the widgets
        wx.Dialog.__init__(self, parent = parent, id = -1, title = "Please Select Difficulty")
        self.SetMinSize(wx.Size(400, 290))
        self.prompt = wx.StaticText(self, -1, "Please Use the slider to select difficulty. The further to the right, the harder the game.")
        self.difficultyDescriptor = wx.StaticText(self, -1, "Game Difficulty: 75 - A little challenging")
        self.difficultySlider = wx.Slider(self, self.ID_DIFFICULTY_SLIDER, 75)
        self.okButton = wx.Button(self, wx.ID_OK, "Set Difficulty")

        # Insert all the widgets into a BoxSizer to lay them out neatly on the screen.
        self.layout = wx.BoxSizer(wx.VERTICAL)
        self.layout.Add(self.prompt, 1, wx.EXPAND)
        self.layout.Add(self.difficultyDescriptor, 1, wx.EXPAND)
        self.layout.Add(self.difficultySlider, 3, wx.EXPAND)
        self.layout.Add(self.okButton, 2, wx.EXPAND)
        self.SetSizer(self.layout)
        self.Fit()

        # Event bindings. For those who aren't familiar with wxPython, wx includes built in ID constants.
        # One of these was assigned to the button: wx.ID_OK. It wasn't created here.
        self.Bind(wx.EVT_COMMAND_SCROLL, self.diffSelectionChanged, id = self.ID_DIFFICULTY_SLIDER)
        self.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.ID_OK), id = wx.ID_OK)
        self.Bind(wx.EVT_CLOSE, lambda evt: self.EndModal(wx.ID_CANCEL))

    def diffSelectionChanged (self, event = None):
        """
        SelectDifficultyDialog.diffSelectionChanged(self, event = None)
        This callback displays the selected difficulty in self.difficultyDescriptor, a StaticText widget
        along with a brief description of the difficulty currently selected.
        """
        currentDifficulty = self.difficultySlider.GetValue()

        if self.currentDifficulty in range(0, 26):
            self.difficultyDescriptor.SetLabel("Game Difficulty: {} - Childs play".format(currentDifficulty))
        elif self.currentDifficulty in range(25, 51):
            self.difficultyDescriptor.SetLabel("Game Difficulty: {} - My cat could do it.".format(currentDifficulty))
        elif self.currentDifficulty in range(50, 76):
            self.difficultyDescriptor.SetLabel("Game Difficulty: {} - A little challenging".format(currentDifficulty))
        elif self.currentDifficulty in range(75, 101):
            self.difficultyDescriptor.SetLabel("Game Difficulty: {} - Only you can win!".format(currentDifficulty))
        else:
            self.difficultyDescriptor.SetLabel("Kyle, you have some debugging to do! Unexpected output: {}".format(currentDifficulty))

    def getCurrentDifficulty (self):
        return self.difficultySlider.GetValue()

class HelpWindow(wx.Dialog):
    """
    A simple dialog class for displaying help information to the user.
    """
    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_OK)

if __name__ == "__main__":
    app = wx.App()
    theApp = OthelloGameFrame(parent = None, id = wx.ID_ANY, size = (700, 800), title = "wxOthello")
    app.MainLoop()
I don't know why, but my player bot is a bit of a numty. Even on the hardest difficulty setting, a setting in which it isn't supposed to make any purely random moves, I beat it easily. If anybody can offer some ideas, that would be greatly appreciated. Also, this code in the PlayerBot.makeMove method is basically unreadable. Is there a better way to do this?
    def makeMove (self):
        ...
        ...
        # The difficulty setting varies the probability of the bot making a 'mistake' That is,
        # making a purely random move from the set of all possible moves. Here, we just make a
        # 'mistake' if random.randint(0, 100) returns a number greater than the set difficulty.
        if random.randint(0, 100) < self.difficulty:
            # This code is pretty ugly. If anybody write a more elegant solution to the problem this code solves,
            # I would greatly appreciate it. Here, we get only the most desirable move from the set of all possible
            # moves and select randomly from them.
            highestPriorityMoves = [validMoves[0]]
            for i in validMoves:
                if self.priorityMap[i[0]][i[1]] < self.priorityMap[highestPriorityMoves[0][0]][highestPriorityMoves[0][1]] and self.priorityMap[i[0]][i[1]] not in range(-2, 0):
                    highestPriorityMoves = [ i ]
                elif self.priorityMap[i[0]][i[1]] == self.priorityMap[highestPriorityMoves[0][0]][highestPriorityMoves[0][1]]:
                    highestPriorityMoves.append(i)
            randomMove = highestPriorityMoves[random.randint(0, len(highestPriorityMoves) - 1)]
            self.parent.gameboardButtonClicked(row = randomMove[0], col = randomMove[1])
I hope this is the only ugly code in this thing...
i don't knwo whether or not you did this but try using a for loop or something to find how many pieces each valid move would make and choose depending on the bot difficulty

So let's say you have 5 valid moves.
move 1 will get the computer - 2 pieces
move 2 will get the computer - 3 pieces
move 3 will get the computer - 3 pieces
move 4 will get the computer - 4 pieces
move 5 will get the computer - 6 pieces
If the difficulty is easy, pick move 2. If the difficulty is medium, choose move 4, if the difficulty is hard, pick move 5
I like your idea, SheeppOSU. I'll try to find a way to implement it. In the mean time, I created a desirability/priority map that was able to win in a game against me. I don't know if that's saying much since I'm a little rusty and may have picked up a few bad habits play testing the game, but here is the new priority map:
# These nested lists map various levels of desirability to different areas of the gameboard
# where 0 is most desirable, 1 is more desirable than 0 and so on. The nines in the center are
# already occupied at the start of the game and their values aren't relevant here. The center
# spaces (early game) are marked with desirability values 0 and 1. Midgame is 2, 3 and 4 with
# the approches to the corners set to 1 to make the bot take those areas if at all possible
# regardless of circumstances, and the corners being most desirable are marked with 0, with
# 5 and 6 used for the buffers with the edge buffer given a value of 5 and the middle buffer
# given a value of 6. This is actually the map that beat me.
priorityMap = [[0,5,1,2,2,1,5,0],
               [5,6,4,3,3,4,6,5],
               [1,4,0,1,1,0,4,1],
               [2,3,1,9,9,1,3,2],
               [2,3,1,9,9,1,3,2],
               [1,4,0,1,1,0,4,1],
               [5,6,4,3,3,4,6,5],
               [0,5,1,2,2,1,5,0]]
Maybe the feature that SheeppOSU suggested is what would give the bot the edge needed to defeat even a master of the game. However, It would just make the capture that got it the most pieces possible with the most strategically valuable move. The way difficulty is determined is by varying the likelihood of the bot making a 'mistake;' a randomly selected move from the set of all possible valid moves. The more mistakes it makes, the easier it is to beat. I just want to make the max difficulty or better yet, something slightly lower than max difficulty to always be a challenge for my mom; even when she gets good at the game. I don't know how familiar any of you are with Othello game strategy, but it's much more than just selecting the move that gets you the most pieces in the short term. The player that gets control of the edges and a corner can turn a board covered in their opponents color against their opponent as 1) they are practically guaranteed to have a move available to them and 2) they can start capturing their opponents pieces en masse in a huge cascade where a single move could well capture dozens of pieces.

The reason occasional random moves are such an effective way to control difficulty is because just one mistake by the bot; especially in the early to mid game can lose it the game while still keeping the rest of the gameplay challenging--provided it uses good strategy.
Ok that makes sense. I only played Othello when I was younger.

Probably why i keep losing
Pages: 1 2 3