def test_botMoveTakeOppositeCorner(self):
     testBoard = TicTacToeBoard()
     testAI = TicTacToeAI('O')
     testBoard.putTac('X', 1)
     testBoard.putTac('O', 5)
     testAI.botMove(testBoard)
     self.assertTrue(testBoard.TTTBoard[8], 'O')
示例#2
0
    def makesTwoInARow(tacToCheck, board, position):
        enemyTac = 'X'
        if tacToCheck == 'X':
            enemyTac = 'O'
        testBoard = TicTacToeBoard()
        testBoard.TTTBoard = board.TTTBoard[:]
        row = math.floor((position - 1) / 3)
        col = ((position - 1) % 3)
        friendlyCount = 0
        enemyCount = 0

        # Checks if the row has any enemy tacs or friendly tacs
        for i in range(row * 3, row + 3):
            if testBoard.TTTBoard[i] == enemyTac:
                enemyCount = enemyCount + 1
            elif testBoard.TTTBoard[i] == tacToCheck:
                friendlyCount = friendlyCount + 1

        if enemyCount == 0 and friendlyCount == 1:
            return True

        enemyCount = 0
        friendlyCount = 0

        # Checks if the column has any enemy tacs or friendly tacs
        for i in range(col, col + 7, 3):
            if testBoard.TTTBoard[i] == enemyTac:
                enemyCount = enemyCount + 1
            elif testBoard.TTTBoard[i] == tacToCheck:
                friendlyCount = friendlyCount + 1

        if enemyCount == 0 and friendlyCount == 1:
            return True
        else:
            return False
示例#3
0
	def newGame(self):
		""" This method is called by the new game button and clears the canvas and board, resets the turn, and creates the GUI again. """
		self.gameCanvas.delete(ALL)
		self.gameBoard = TicTacToeBoard()
		self.turn = 0
		self.gameOver = False
		self.createGame()
示例#4
0
 def isWinningMove(tacToCheck, board, position):
     """A function that detects whether or not a given position with a given tac makes a win on a given board."""
     testBoard = TicTacToeBoard()
     testBoard.TTTBoard = board.TTTBoard[:]
     if testBoard.putTac(tacToCheck, position):
         if testBoard.checkWin():
             return True
         else:
             return False
     else:
         return False
 def test_CheckFull(self):
     testBoard = TicTacToeBoard()
     for i in range(1, 10):
         testBoard.putTac('X', i)
     self.assertTrue(testBoard.checkFull())
     testBoard = TicTacToeBoard()
     self.assertFalse(testBoard.checkFull())
    def test_botMovePreventFork(self):
        testBoard = TicTacToeBoard()
        testAI = TicTacToeAI('O')
        testBoard.putTac('X', 6)
        testBoard.putTac('X', 8)
        testAI.botMove(testBoard)
        self.assertTrue(testBoard.TTTBoard[8], 'O')

        testBoard = TicTacToeBoard()
        testBoard.putTac('X', 1)
        testBoard.putTac('X', 9)
        testBoard.putTac('O', 5)
        testAI.botMove(testBoard)
        self.assertTrue(testBoard.TTTBoard[1], 'O')
示例#7
0
 def makesFork(board, tacToCheck, position):
     """A function that detects whether or not a given position and given tac makes a fork on a given board."""
     numOfWinningMoves = 0
     testBoard = TicTacToeBoard()
     testBoard.TTTBoard = board.TTTBoard[:]
     if testBoard.putTac(tacToCheck, position):
         # Looks for two or more possible winning moves created by placing a tac at position in question
         for i in range(1, 10):
             if TicTacToeAI.isWinningMove(tacToCheck, testBoard, i):
                 numOfWinningMoves = numOfWinningMoves + 1
         if numOfWinningMoves > 1:
             return True
         else:
             return False
     else:
         return False
示例#8
0
	def __init__(self, master):
		""" This method takes a given Tkinter root and sets up the GUI """
		Frame.__init__(self, master)
		self.width = 600
		self.height = 600
		self.canvasWidth = self.width - 100
		self.canvasHeight = self.height - 100
		self.root = master
		self.root.geometry(str(self.width)+"x"+str(self.height))
		
		self.numPlayers = 1
		self.turn = 0
		self.gameOver = False
		self.TTTAI = TicTacToeAI('O')
		self.gameBoard = TicTacToeBoard()
		
		self.createGame()
    def test_botMoveWin(self):
        testBoard = TicTacToeBoard()
        testAI = TicTacToeAI('O')
        testBoard.putTac('O', 1)
        testBoard.putTac('O', 2)
        testAI.botMove(testBoard)
        self.assertTrue(testBoard.TTTBoard[2], 'O')

        testBoard = TicTacToeBoard()
        testBoard.putTac('O', 1)
        testBoard.putTac('O', 5)
        testAI.botMove(testBoard)
        self.assertTrue(testBoard.TTTBoard[8], 'O')
示例#10
0
 def runGame(self):
     playing = True
     while (playing):
         #Set up game....
         players = self.getNumPlayers()
         symbolChoice = self.getSymbolChoice()
         enemyChoice = 'O'
         if symbolChoice == 'X':
             enemyChoice = 'O'
         else:
             enemyChoice = 'X'
         gameRunning = True
         turn = 0
         gameAI = TicTacToeAI(enemyChoice)
         self.GameBoard.printBoard()
         while (not self.GameBoard.checkWin()
                and not self.GameBoard.checkFull()):
             if turn == 0:
                 if symbolChoice == 'O' and players == 1:
                     gameAI.botMove(self.GameBoard)
                 else:
                     self.makeMovePrompt('X')
                 turn = 1
             else:
                 if symbolChoice == 'X' and players == 1:
                     gameAI.botMove(self.GameBoard)
                 else:
                     self.makeMovePrompt('O')
                 turn = 0
             self.GameBoard.printBoard()
         if self.GameBoard.checkWin():
             if turn == 1:
                 print("X wins!")
             else:
                 print("O wins!")
         else:
             print("Game draw!")
         playAgain = self.getPlayAgainChoice()
         if playAgain == 'N':
             playing = False
         self.GameBoard = TicTacToeBoard()
示例#11
0
    def test_botMoveTakeCenter(self):
        testBoard = TicTacToeBoard()
        testAI = TicTacToeAI('O')
        testAI.botMove(testBoard)
        self.assertTrue(testBoard.TTTBoard[4], 'O')

        testBoard = TicTacToeBoard()
        testBoard.putTac('X', 1)
        testAI.botMove(testBoard)
        self.assertTrue(testBoard.TTTBoard[4], 'O')
示例#12
0
 def test_CheckWin(self):
     testBoard = TicTacToeBoard()
     testBoard.putTac('X', 1)
     testBoard.putTac('O', 4)
     testBoard.putTac('X', 2)
     testBoard.putTac('O', 5)
     testBoard.putTac('X', 3)
     self.assertTrue(testBoard.checkWin())
     testBoard = TicTacToeBoard()
     testBoard.putTac('X', 1)
     testBoard.putTac('O', 4)
     testBoard.putTac('X', 5)
     testBoard.putTac('O', 7)
     testBoard.putTac('X', 9)
     self.assertTrue(testBoard.checkWin())
示例#13
0
 def test_PutTac(self):
     testBoard = TicTacToeBoard()
     testBoard.putTac('X', 1)
     self.assertEqual(testBoard.TTTBoard[0], 'X')
示例#14
0
 def test_isWinningMove(self):
     testBoard = TicTacToeBoard()
     testBoard.putTac('X', 1)
     testBoard.putTac('X', 2)
     self.assertTrue(TicTacToeAI.isWinningMove('X', testBoard, 3))
     self.assertFalse(TicTacToeAI.isWinningMove('X', testBoard, 8))
示例#15
0
class TicTacToeGUI(Frame):
	def __init__(self, master):
		""" This method takes a given Tkinter root and sets up the GUI """
		Frame.__init__(self, master)
		self.width = 600
		self.height = 600
		self.canvasWidth = self.width - 100
		self.canvasHeight = self.height - 100
		self.root = master
		self.root.geometry(str(self.width)+"x"+str(self.height))
		
		self.numPlayers = 1
		self.turn = 0
		self.gameOver = False
		self.TTTAI = TicTacToeAI('O')
		self.gameBoard = TicTacToeBoard()
		
		self.createGame()
		
	def createGame(self):
		""" This method sets or resets the canvas and GUI and is used for creating a new game or for initializing the GUI. """
		self.columnconfigure(0, pad = 5)
		self.columnconfigure(1, pad = 5)
		self.rowconfigure(0, pad = 10)
		self.rowconfigure(1, pad = 10)
		self.numPlayersField = Entry(self)
		self.numPlayersField.insert(0,"1")
		self.setPlayersButton = Button(self, text = "Set number of players", command = self.setPlayers)
		self.numPlayersField.grid(row=0, column = 0)
		self.setPlayersButton.grid(row=0, column = 1)
		self.gameCanvas = Canvas(self, bg = "black", height = self.canvasHeight, width = self.canvasWidth)
		self.gameCanvas.grid(row = 1, column = 0, columnspan = 2)
		self.newGameButton = Button(self, text="New game", command = self.newGame)
		self.quitGameButton = Button(self, text="Quit", command = self.quit)
		self.newGameButton.grid(row = 2, column = 0)
		self.quitGameButton.grid(row = 2, column = 1)
		self.pack()
		self.createRectangles()
	
	def setPlayers(self):
		""" This method is called by the set players button to set the number of players. """
		tempNum = int(self.numPlayersField.get())
		if tempNum == 1 or tempNum == 2:
			self.numPlayers = int(self.numPlayersField.get())
			
	def createRectangles(self):
		""" This method creates the rectangles where tacs are placed. """
		rectangleWidth = (self.canvasHeight / 3)
		rectangleHeight = (self.canvasHeight / 3)
		index = 0
		for p in range(3):
			for i in range(3):
				currentRect = self.gameCanvas.create_rectangle(i * rectangleWidth, p*rectangleHeight, (i * rectangleWidth) + rectangleWidth, (p * rectangleHeight) + rectangleHeight, fill = "black", tag=str(index), outline = 'white')
				self.gameCanvas.tag_bind(currentRect, "<ButtonRelease-1>", self.tacClick)
				index = index + 1
				
	def tacClick(self, event):
		""" Handles placing tacs and swapping the turn when the canvas is clicked. """
		if self.gameOver == False:
			# Determines which rectangle was clicked and gets tac position from that
			rect = self.gameCanvas.find_closest(event.x, event.y)
			tacPosition = int(self.gameCanvas.gettags(rect)[0])
			placed = False
			# Determines where to put tac based on turn, then lets TicTacToe methods handle the rest and calls updateCanvas
			if self.turn == 0:
				placed = self.gameBoard.putTac('X', tacPosition + 1 )
			else:
				placed = self.gameBoard.putTac('O', tacPosition + 1 )
				
			if placed == True:
				self.updateCanvas()
				if not self.gameBoard.checkWin() and not self.gameBoard.checkFull():
					if self.turn == 1:
						self.turn = 0
					else:
						self.turn = 1
					if self.numPlayers == 1:
						self.gameBotMove()
				else:
					self.gameOver = True
					self.drawEndGame()
					
	def gameBotMove(self):
		""" This method wraps the TicTacToeAI botMove method and calls the canvas update method and switches turn. """
		self.TTTAI.botMove(self.gameBoard)
		self.updateCanvas()
		if self.gameBoard.checkWin() or self.gameBoard.checkFull():
			self.gameOver = True
			self.drawEndGame()
		self.turn = 0

		
	def newGame(self):
		""" This method is called by the new game button and clears the canvas and board, resets the turn, and creates the GUI again. """
		self.gameCanvas.delete(ALL)
		self.gameBoard = TicTacToeBoard()
		self.turn = 0
		self.gameOver = False
		self.createGame()
		
	def quit(self):
		""" This is the method called by the quit button to end the game. """
		self.root.quit()
		
	def updateCanvas(self):
		""" Updates the Tkinter canvas based on the TicTacToeBoard object's state"""
		# Checks each board position on TicTacToe board, then sets cooresponding canvas rectangle
		for i in range(9):
			row = math.floor((i ) / 3)
			col = ((i) % 3)
			changeRect = self.gameCanvas.find_withtag(str(i+1))
			if self.gameBoard.TTTBoard[i] == 'X':
				self.gameCanvas.itemconfig(changeRect, fill = "red")
				positionX = (col * 166) + 83
				positionY = (row * 166) + 83
				self.gameCanvas.create_text(positionX, positionY, font=("Arial", 20), text="X", fill="black" )
			elif self.gameBoard.TTTBoard[i] == 'O':
				self.gameCanvas.itemconfig(changeRect, fill = "blue")
				positionX = (col * 166) + 83
				positionY = (row * 166) + 83
				self.gameCanvas.create_text(positionX, positionY, font=("Arial", 20), text="O", fill="white"  )
			else:
				self.gameCanvas.itemconfig(changeRect, fill = "black") 

	def drawEndGame(self):
		""" Draws a status to the board depending on how the game ended. """
		if self.gameBoard.checkWin():
			if self.turn == 1:
				self.gameCanvas.create_text((math.floor(self.canvasWidth/2), math.floor(self.canvasHeight / 2)), font=("Arial", 30), fill = 'green', text="Blue wins!")
			else: 
				self.gameCanvas.create_text((math.floor(self.canvasWidth/2), math.floor(self.canvasHeight / 2)), font=("Arial", 30), fill = 'green', text="Red wins!")
		elif self.gameBoard.checkFull():
			self.gameCanvas.create_text((math.floor(self.canvasWidth/2), math.floor(self.canvasHeight / 2)), font=("Arial", 30), fill = 'green', text="Game Draw!")
示例#16
0
 def test_makesTwoInARow(self):
     testBoard = TicTacToeBoard()
     testBoard.putTac('X', 2)
     self.assertTrue(TicTacToeAI.makesTwoInARow('X', testBoard, 3))
示例#17
0
 def __init__(self):
     """ Instantiates the game's TicTacToeBoard when first initialized. """
     self.GameBoard = TicTacToeBoard()
示例#18
0
class TicTacToeCLI:
    def __init__(self):
        """ Instantiates the game's TicTacToeBoard when first initialized. """
        self.GameBoard = TicTacToeBoard()

    """This method runs a pair of nested while loops that runs and resets the game. 
	
	This method makes use of makeMovePrompt(), getNumPlayers(), getSymbolChoice(), and getPlayAgainChoice() to shorten
	the method and make it more readable.
	
	"""

    def runGame(self):
        playing = True
        while (playing):
            #Set up game....
            players = self.getNumPlayers()
            symbolChoice = self.getSymbolChoice()
            enemyChoice = 'O'
            if symbolChoice == 'X':
                enemyChoice = 'O'
            else:
                enemyChoice = 'X'
            gameRunning = True
            turn = 0
            gameAI = TicTacToeAI(enemyChoice)
            self.GameBoard.printBoard()
            while (not self.GameBoard.checkWin()
                   and not self.GameBoard.checkFull()):
                if turn == 0:
                    if symbolChoice == 'O' and players == 1:
                        gameAI.botMove(self.GameBoard)
                    else:
                        self.makeMovePrompt('X')
                    turn = 1
                else:
                    if symbolChoice == 'X' and players == 1:
                        gameAI.botMove(self.GameBoard)
                    else:
                        self.makeMovePrompt('O')
                    turn = 0
                self.GameBoard.printBoard()
            if self.GameBoard.checkWin():
                if turn == 1:
                    print("X wins!")
                else:
                    print("O wins!")
            else:
                print("Game draw!")
            playAgain = self.getPlayAgainChoice()
            if playAgain == 'N':
                playing = False
            self.GameBoard = TicTacToeBoard()

    def makeMovePrompt(self, tac):
        """ Method used for prompting for a move from either player """
        valid = False
        while valid == False:
            try:
                position = int(
                    input(tac +
                          ", please select a position to place your tac."))
            except ValueError:
                print("Input is not an integer, please try again.")
                continue
            else:
                if (self.GameBoard.putTac(tac, position)):
                    valid = True
                else:
                    print("That move is entirely invalid. Please, try again: ")

        return position

    def getNumPlayers(self):
        """ Method used for prompting for the number of players """
        print(
            "Are there one or two players? Enter 1 for one player, or 2 for two players. \n"
        )
        numPlayers = input()
        while (numPlayers != '1' and numPlayers != '2'):
            numPlayers = input(
                "That is an altogether unacceptable number of players. Please try again: "
            )
        return int(numPlayers)

    def getSymbolChoice(self):
        """ Method used for prompting for player one's choice of tac """
        print(
            "Player one, please enter your choice of X or O. X goes first.\n")
        symbolChoice = input("").upper()
        while (symbolChoice != 'X' and symbolChoice != 'O'):
            symbolChoice = input(
                "That is an altogether unacceptable choice. Please try again: "
            ).upper()
        return symbolChoice

    def getPlayAgainChoice(self):
        """ Method used for prompting for whether or not the player or players will play again. """
        print("Do you want to play again? Y/N")
        playAgain = input("").upper()
        while (playAgain != 'Y' and playAgain != 'N'):
            playAgain = input(
                "That is an altogether unacceptable choice. Please try again: "
            ).upper()
        return playAgain
示例#19
0
 def test_makesFork(self):
     testBoard = TicTacToeBoard()
     testBoard.putTac('X', 2)
     testBoard.putTac('X', 4)
     self.assertTrue(TicTacToeAI.makesFork(testBoard, 'X', 1))
     self.assertFalse(TicTacToeAI.makesFork(testBoard, 'O', 1))