Esempio n. 1
0
def performFirstMove():
    # Stores a randomly generated number (either 1 or 2), and if it is 1 skips to the human's turn otherwise allows the
    #  AI to make a move
    randomPlayerGeneration = random.randrange(1, 3)
    if randomPlayerGeneration == 1:
        pass
    elif randomPlayerGeneration == 2:
        backend.getAiMove()
Esempio n. 2
0
def addGhostPiecesToBoard():
    # Gets the array containing all the valid moves the player can perform, and the board array, and adds ghost pieces
    #  into unoccupied valid move spots
    playerValidMoves = backend.findValids(True)
    currentBoardState = backend.getBoard()
    for rowCounter in range(8):
        for columnCounter in range(8):
            if playerValidMoves[rowCounter][columnCounter] == 1 and currentBoardState[rowCounter][columnCounter] == 0:
                teleAddPieceToBoard(rowCounter, columnCounter, 3)
Esempio n. 3
0
def saveGameStateToFile():
    try:
        # Gets the board from the backend, initializes a new save file to write to (overwrites any existing one),
        #  and loops through the board matrix and writes it to the file
        gameBoard = backend.getBoard()
        saveGameFile = open("Reversi Save Game", "w")
        for rowCounter in range(8):
            for columnCounter in range(8):
                saveGameFile.write(str(gameBoard[rowCounter][columnCounter]))
        saveGameFile.write(str(backend.getDifficulty()))
        saveGameFile.close()
    except Exception:
        pass
Esempio n. 4
0
def performInitialSetup():
    # Resets the display overlay & all the turtles & the click listeners & the piece data & the board matrix
    displayOut.reset()
    boardTurtle.reset()
    pieceTurtle.reset()
    ghostPieceTurtle.reset()
    displayOut.onclick(None)
    displayOut.onkey(None, "l")
    displayOut.onkey(None, "s")
    displayOut.bgcolor(BOARD_BACKGROUND_COLOUR)
    displayOut.title("Reversi By Group Reversi02")
    blankBoard = [[0 for i in range(8)] for i in range(8)]

    # Populates the board with the initial starting pieces & sends it off to the backend
    blankBoard[3][3] = 1
    blankBoard[3][4] = 2
    blankBoard[4][3] = 2
    blankBoard[4][4] = 1
    backend.writeBoard(blankBoard)

    # Scales the display overlay window based on the specified size of the board
    # Takes half the width of the board (global constant) and multiplies it by 2 to get the entire board's width
    # Then calculates 1/8th of the board's width and subtracts it from the total width to have empty spaces on the sides
    # Then does the same calculation for the board's height
    displayOut.setup(abs(((HALF_BOARD_WIDTH * 2) + (HALF_BOARD_WIDTH * 0.25))),
                     abs(((HALF_BOARD_HEIGHT * 2) + (HALF_BOARD_HEIGHT * 0.25))))

    # Hides the turtles & makes the animation speed / delay instantaneous
    pieceTurtle.hideturtle()
    pieceTurtle.speed(0)
    boardTurtle.hideturtle()
    boardTurtle.speed(0)
    ghostPieceTurtle.hideturtle()
    ghostPieceTurtle.speed(0)
    displayOut.delay(0)

    # Calls the functions to print out the intro & board
    printOutIntro()
    printOutTable()

    # Gets the game's difficulty, determine and performs the first random move, and updates the board & ghost pieces
    backend.setDifficulty(getGameDifficulty())
    performFirstMove()
    updateBoardPieces(backend.getBoard())
    addGhostPiecesToBoard()

    # Sets the function that will be called when the user clicks on the screen + for L is pressed + for S is pressed
    displayOut.onkey(importGameStateFromFile, "l")
    displayOut.onkey(saveGameStateToFile, "s")
    displayOut.onclick(graphicalOverlayClicked)
    displayOut.listen()
Esempio n. 5
0
 def selectSpace(self, x, y):
     """置けるマスをクリックしたときに実行"""
     self.state.put_stone(self.state.turn, x, y)
     board = self.state.getPieces()
     turn = self.state.getTrun()
     self.state = rb.ReversiBoard(board, turn)
     self.updateBoard()
Esempio n. 6
0
 def newGame(self):
     """初期化して始める"""
     for s in self.squares.values():
         if s.pieceId:
             self.canvas.delete(s.pieceId)
             s.pieceId = 0
     """再描画"""
     self.state = rb.ReversiBoard()
     self.updateBoard()
Esempio n. 7
0
def importGameStateFromFile():
    try:
        # Initialize a new list & the save game file reader utility & specifies that it is to be imported from
        saveGameFile = open("Reversi Save Game", "r")
        importedBoard = [[0 for importedMatrixIndex in range(8)] for importedMatrixIndex in range(8)]
        currentIndex = 0
        fileData = saveGameFile.read()
        # Loops through the entire file except last spot & imports it into the temp board matrix, then sets the
        #  game difficulty and closes the save file reader
        for rowCounter in range(8):
            for columnCounter in range(8):
                importedBoard[rowCounter][columnCounter] = int(fileData[currentIndex:currentIndex + 1])
                currentIndex += 1
        backend.setDifficulty(int(fileData[len(fileData) - 1]))
        saveGameFile.close()
        # Sends the newly populated game board to the backend and updates the GUI's game state as well by
        #  first resetting the current board's pieces
        backend.writeBoard(importedBoard)
        pieceTurtle.clear()
        ghostPieceTurtle.clear()
        updateBoardPieces(backend.getBoard())
        addGhostPiecesToBoard()
    except Exception:
        pass
Esempio n. 8
0
def graphicalOverlayClicked(inputX, inputY):
    # Calculates the tile clicked, gets the number of valid moves possible for the player & the AI, and stores the
    #  current board's status (to keep track of updated pieces)
    calculatedCoordinates = coordinatesCalculateTile(inputX, inputY)
    numberOfValidMoves = checkForRemainingValidMoves(recursiveListDeepCopy(backend.findValids(True)),
                                                     recursiveListDeepCopy(backend.findValids(False)))
    oldBoardState = recursiveListDeepCopy(backend.getBoard())
    # Checks to see if the human can perform a move, otherwise skips to the AI, otherwise runs the end game function
    if numberOfValidMoves[0] > 0:
        if 7 >= calculatedCoordinates[0] >= 0 and 7 >= calculatedCoordinates[1] >= 0:
            if (recursiveListDeepCopy(backend.findValids(True))[calculatedCoordinates[0]][calculatedCoordinates[1]]) == 1:
                # Feeds the backend with the user's inputted piece row & column values, and updates the board's pieces,
                #  while removing the now outdated ghost pieces
                backend.playerMove(calculatedCoordinates[0], calculatedCoordinates[1])
                updateBoardPieces(backend.getBoard(), oldBoardState)
                ghostPieceTurtle.clear()

                # Stores the current board's status (to keep track of updated pieces), allows the AI to make a move,
                #  and updates the board based on the changes, and adds new ghost pieces
                oldBoardState = recursiveListDeepCopy(backend.getBoard())
                backend.getAiMove()
                updateBoardPieces(backend.getBoard(), oldBoardState)
                addGhostPiecesToBoard()
    elif numberOfValidMoves[1] > 0:
        # Removes the current ghost pieces, allows the AI to make a move, and updates the board based on the changes,
        #  and adds new ghost pieces
        ghostPieceTurtle.clear()
        backend.getAiMove()
        updateBoardPieces(backend.getBoard(), oldBoardState)
        addGhostPiecesToBoard()
    elif numberOfValidMoves[0] == 0 and numberOfValidMoves[1] == 0:
        pieceCount = [0, 0]
        for rowCounter in range(8):
            for columnCounter in range(8):
                if backend.getBoard()[rowCounter][columnCounter] == 1:
                    pieceCount[0] += 1
                elif backend.getBoard()[rowCounter][columnCounter] == 2:
                    pieceCount[1] += 1
        if pieceCount[0] > pieceCount[1]:
            endGame("Player Has Won By " + str(pieceCount[0] - pieceCount[1]) + " Pieces!")
        elif pieceCount[1] > pieceCount[0]:
            endGame("AI Has Won By " + str(pieceCount[1] - pieceCount[0]) + " Pieces!")
        elif pieceCount[0] == pieceCount[1]:
            endGame("Draw, No One Has Won!")
Esempio n. 9
0
import copy
from math import *
import ReversiGraphics as graphics
import ReversiBoard as rboard

testwin = graphics.Window()
board = rboard.Board(8, 8)
display = testwin.setup_display(board)


class ValuedMove():
    def __init__(self, value, move):
        self.value = value
        self.move = move

    def __lt__(self, other):
        return self.value < other

    def __le__(self, other):
        return self.value <= other

    def __gt__(self, other):
        return self.value > other

    def __ge__(self, other):
        return self.value >= other

    def __eq__(self, other):
        return self.value == other

    def __neg__(self):