def over():
	currentBoard = request.form["board"]
	gameOver = tictactoe.gameOver(currentBoard)
	tieGame = tictactoe.tie(currentBoard)

	data = json.dumps({"over": gameOver, "tie": tieGame})
	return data
def batch():
	# Parse data
	numGames = int(request.form["num-games"])

	# Run simulations
	for i in range(numGames):
		# Clear previous histories
		session["previousBoard"] = {"x": None, "o": None}
		gamevars.setPreviousBoard(session)

		# Restart game
		compSymbol = "x"
		currentBoard = "---------"

		while True:
			currentBoard = tictactoe.computerTurn(currentBoard, compSymbol)
			if tictactoe.gameOver(currentBoard):
				break
			else:
				opponent = compSymbol
				compSymbol = [player for i, player in enumerate(gamevars.players) if player != compSymbol][0]
		
		if tictactoe.win(currentBoard, compSymbol):
			tictactoe.learnFromLoss(opponent)
		elif tictactoe.tie(currentBoard):
			tictactoe.learnFromTie(opponent)

	return json.dumps({})
def next():
	# Parse data
	currentBoard = request.form["board"]
	compSymbol = request.form["comp-symbol"]
	simulation = request.form["simulation"]
	erase = request.form["erase"]

	# Erase previous board history if new simulation game
	if erase == "true":
		session["previousBoard"] = {"x": None, "o": None}

	# Get new board after computer's move
	gamevars.setPreviousBoard(session)
	newBoard = tictactoe.computerTurn(currentBoard, compSymbol)
	newProb = gamevars.boardTree[compSymbol].search(newBoard).prob
	gameOver = tictactoe.gameOver(newBoard)

	# Save previous board into session cookie
	session["previousBoard"] = gamevars.previousBoard

	# If simulated game, update other computer's last probability
	if simulation == "true" and gameOver:
		opponent = [player for i, player in enumerate(gamevars.players) if player != compSymbol][0]

		if tictactoe.win(newBoard, compSymbol):
			tictactoe.learnFromLoss(opponent)
		elif tictactoe.tie(newBoard):
			tictactoe.learnFromTie(opponent)

	# If not a simulation, send back game status and computer's probability of winning 
	if gameOver and simulation == "false":
		gamevars.setPlayerSymbols(session)
		msg = tictactoe.result(newBoard)
	elif simulation =="false":
		msg = newProb
	else:
		msg = ""

	data = json.dumps({"board": newBoard, "over": gameOver, "msg": msg})
	return data
 def test_game_over8(self):
     board8 = [[0, 0, 0], [1, None, 1], [1, 1, 0]]
     self.assertEqual(tictactoe.gameOver(board8), (True, 0),
                      "Win for o vertically")
 def test_game_over0(self):
     board0 = [[0, 1, 0], [1, 1, 0], [1, 0, 1]]
     self.assertEqual(tictactoe.gameOver(board0), (True, None),
                      "Should be a tie")
 def test_game_over6(self):
     board6 = [[1, 0, 0], [0, 1, 1], [1, 1, 0]]
     self.assertEqual(tictactoe.gameOver(board6), (True, None),
                      "It's a tie")
 def test_game_over7(self):
     board7 = [[0, None, 0], [1, None, 1], [1, 1, 0]]
     self.assertEqual(tictactoe.gameOver(board7), (False, None),
                      "Game not over")
 def test_game_over5(self):
     board5 = [[1, 0, 0], [0, 1, 1], [1, 0, 1]]
     self.assertEqual(tictactoe.gameOver(board5), (True, 1),
                      "Win for x diagonally")
 def test_game_over3(self):
     board3 = [[None, 1, 0], [1, None, 0], [1, 1, 0]]
     self.assertEqual(tictactoe.gameOver(board3), (True, 0),
                      "Win for o horizontally")
 def test_game_over2(self):
     board2 = [[1, 1, 1], [0, None, 0], [None, 1, 0]]
     self.assertEqual(tictactoe.gameOver(board2), (True, 1),
                      "Win for x vertically")
 def test_game_over1(self):
     board1 = [[0, 1, 0], [1, 1, 0], [0, 1, 1]]
     self.assertEqual(tictactoe.gameOver(board1), (True, 1),
                      "Win for x horizontally")
Exemple #12
0
def main():

    tao.initBoard()

    print("\nTIC TAC TOE")
    print("created By Shienny Mendeline Hadi")
    print("===========")
    #ask input character
    player = input(
        "choose your character (X, O or other character): ").upper()[0]

    #set pawn AI
    ai = tao.getPawn(player)

    print("You : ", player, "\nAI : ", ai)

    #show loading progress
    print("randoming who will be the first..")

    #random the turn
    turn = random.choice([ai, player])

    #show who is the first
    print("it's {n}'s turn".format(n=turn))

    print("\nGAME START NOW")
    print("================")
    #for the first time I add random position, so user can have a chance win at some case
    if turn == ai:
        selected_square = int(random.random() * (tao.length - 1))
        print(ai, " choose ", (selected_square + 1))

        tao.addPawnToSquare(selected_square, ai)
        turn = player

    #game stops when somebody wins or all squares are filled
    while (not tao.gameOver()):
        tao.drawMap()

        if turn == ai:
            tao.findBestPosition(ai)
            turn = player
        else:
            while True:
                try:
                    #ask for user input, and then -1 so match with indexing array that starts from 0
                    selected_square = input(
                        "choose slot (1-{last}): ".format(last=tao.length))
                    selected_square = int(selected_square) - 1

                    #make sure the input is not out of range
                    if selected_square >= 0 and selected_square < tao.length:
                        #make sure the selected square is empty, and add the pawn to the square
                        if tao.isEmptySlot(selected_square):
                            break
                        else:
                            print("this slot already filled")
                    else:
                        print(
                            "Invalid Number, Please Type Numeric only (1-{last})"
                            .format(last=tao.length))
                except ValueError:
                    print("Invalid input, Please Type Numeric only (1-{last})".
                          format(last=tao.length))

            tao.addPawnToSquare(selected_square, player)
            turn = ai

    #the display for game over
    print("\nGAME OVER")
    print("=========")
    tao.drawMap()
    print("=========")
    print(tao.getWinStatus())
    print("created By Shienny Mendeline Hadi")