DEV Community

erickwithack
erickwithack

Posted on

Tic Tac Toe game

using classes

class TTTBoard:
def init(self):
self.cells = ["", "", "", "", "", "", "", "", "*"]

def __str__(self):
    s = self.cells[0] + self.cells[1] + self.cells[2] + "\n"
    s += self.cells[3] + self.cells[4] + self.cells[5] + "\n"
    s += self.cells[6] + self.cells[7] + self.cells[8] + "\n"
    return s

def make_move(self, player, posn):
    posn = int(posn)
    player = str(player)

    if 0 <= posn <= 8 and self.cells[posn] == "*":
        self.cells[posn] = player
        return ("True: move made")
    elif posn > 8 or posn < 0:
        return ("False: posn should be between 1 and 8")

    elif self.cells[posn] != "*":
        return ("posn occupied")

def has_won(self, player):
    # 3 in a row/column/diagonal
    if self.cells[0] == player and self.cells[1] == player and self.cells[
            2] == player:
        return True
    elif self.cells[3] == player and self.cells[
            4] == player and self.cells[5] == player:
        return True
    elif self.cells[6] == player and self.cells[
            7] == player and self.cells[8] == player:
        return True
    #columns
    elif self.cells[0] == player and self.cells[
            3] == player and self.cells[6] == player:
        return True
    elif self.cells[1] == player and self.cells[
            4] == player and self.cells[7] == player:
        return True
    elif self.cells[2] == player and self.cells[
            5] == player and self.cells[8] == player:
        return True
    #diagonals
    elif self.cells[0] == player and self.cells[
            4] == player and self.cells[8] == player:
        return True
    elif self.cells[2] == player and self.cells[
            4] == player and self.cells[6] == player:
        return True
    else:
        return False

def game_over(self):
    if self.has_won("X") == True or self.has_won("O") == True:
        return True
    else:
        return False

    def check(i):
        if i == "*":
            return True

    y = list(filter(check, self.cells))
    if len(y) == 0:
        result = True
        return result
    else:
        return False

def clear(self):
    self.cells = ["*", "*", "*", "*", "*", "*", "*", "*", "*"]
    return print(self)

def play_tic_tac_toe() -> None:
"""Uses your class to play TicTacToe"""

def is_int(maybe_int: str):
    """Returns True if val is int, False otherwise

    Args:
        maybe_int - string to check if it's an int

    Returns:
        True if maybe_int is an int, False otherwise
    """
    try:
        int(maybe_int)
        return True
    except ValueError:
        return False

brd = TTTBoard()
players = ["X", "O"]
turn = 0

while not brd.game_over():
    print(brd)
    move: str = input(f"Player {players[turn]} what is your move? ")

    if not is_int(move):
        raise ValueError(
            f"Given invalid position {move}, "
            "position must be integer between 0 and 8 inclusive")

    if brd.make_move(players[turn], int(move)):
        turn = not turn

print(f"\nGame over!\n\n{brd}")
if brd.has_won(players[0]):
    print(f"{players[0]} wins!")
elif brd.has_won(players[1]):
    print(f"{players[1]} wins!")
else:
    print(f"Board full, that's game!")

if name == "main":
# here are some tests. These are not at all exhaustive tests. You will
# DEFINITELY need to write some more tests to make sure that your TTTBoard class
# is behaving properly.
brd = TTTBoard()
brd.make_move("X", 8)
brd.make_move("O", 7)

assert brd.game_over() == False

brd.make_move("X", 5)
brd.make_move("O", 6)
brd.make_move("X", 2)

assert brd.has_won("X") == True
assert brd.has_won("O") == False
assert brd.game_over() == True

brd.clear()

assert brd.game_over() == False

brd.make_move("O", 3)
brd.make_move("O", 4)
brd.make_move("O", 5)

assert brd.has_won("X") == False
assert brd.has_won("O") == True
assert brd.game_over() == True

print("All tests passed!")

# uncomment to play!
# play_tic_tac_toe()

Top comments (0)