ALL project 1: Weeks 5 and 6

For the 5th and 6th weeks of ALL sessions I completed the simple version of the tic-tac-toe game. The game is fully functional for two players to play the game on one keyboard. I split my game code up into multiple files so that it can easily be made into a modular design and so that the project is cleaner.

main.py
This is the entry point of the program which instantiates the game board, defines the players and starts the game.

"""Runs the game client""" 
from board import Board
from game import Game
# creating the new game board instance
BOARD = Board()
# defining our players
PLAYERS = ['X', 'O']
# creating the game instance with our Board and Players
GAME = Game(BOARD, PLAYERS)
# starting the game
GAME.start()

board.py
This file represents the tic-tac-toe board for the game to render on. It handles the rendering and also the tiles that users are able to claim.

"""Handles the "screen" of a game""" 
import os  
class Board:
"""Represents a tic-tac-toe board"""
    SIZE = 3 

def __init__(self):
self.tiles = [[""] * self.SIZE for i in range(self.SIZE)]
self.__create_labels()
self.draw()
    def __create_labels(self):
counter = 0
        for i in range(self.SIZE):
for j in range(self.SIZE):
counter += 1
self.tiles[i][j] = counter
    def __print_devider(self):
print('|'.join(['____' for x in range(self.SIZE)]))
    def __print_blank(self):
print('|'.join([' ' for x in range(self.SIZE)]))
    def __print_labels(self, counter):
row = ' | '.join(['%2s' % self.tiles[counter][x] for x in range(self.SIZE)])
row = ' ' + row
print(row)
    def draw(self):
"""Renders the board"""
        for i in range(self.SIZE):
self.__print_blank()
self.__print_labels(i)
            if (i == self.SIZE - 1):
self.__print_blank()
else:
self.__print_devider()
     def clear(self):
"""Clears the screen ready for the board to be drawn again"""
        # command to clear the screen is different depending on the OS
if os.name is "nt": # check if the os is windows
os.system("cls")
else: # clear is used on most unix based systems
os.system("clear")
     def set_tile(self, tile, value):
"""Sets the label of the specified tile"""
        self.tiles[tile // self.SIZE][tile % self.SIZE] = value

checks.py
Here are the functions I wrote in week 3 to see if a player has one the game.

"""Functions used to check if there is a win on the board""" 
def check_win_vertical(board, j):
"""Checks if there is a vertical win on the board"""
    for i in range(len(board) - 1):
if board[i][j] != board[i+1][j]:
return False
    return True 
def check_win_horizontal(board, i):
"""Checks if there is a horizontal win on the board"""
    for j in range(len(board) - 1):
if board[i][j] != board[i][j+1]:
return False
    return True 
def check_win_diagonal_lr(board):
"""Checks if there is a left-to-right diagonal win on the board"""
    return board[0][0] is board[1][1] and board[1][1] is board[2][2] 
def check_win_diagonal_rl(board):
"""Checks if there is a right-to-left diagonal win on the board"""
    return board[2][0] is board[1][1] and board[1][1] is board[0][2]

game.py
This file handles the running of the game and the logic associated with doing that.

"""Handles the running of tic-tac-toe games""" 
import checks  
class Game:
"""Represents a game of tic-tac-toe"""
    def __init__(self, board, players):
self.board = board
self.players = players
self.current_player = 0
self.playing = True
    def get_player(self):
"""Returns the current player's symbol"""
        return self.players[self.current_player]
    def __ask_for_tile(self):
user_input = input("player " + self.get_player() + ":\n")
        if user_input == "exit":
return None
        try:
return int(user_input)
except ValueError:
print("invalid input - integer or exit")
return self.__ask_for_tile()
    def __choose_next_player(self):
if (self.current_player < len(self.players) - 1):
self.current_player += 1
else:
self.current_player = 0
    def __check_if_won(self):
iterations = self.board.SIZE - 1
board = self.board.tiles
        # check vertical wins
for j in range(iterations):
if checks.check_win_vertical(board, j):
return True
        # check horizontal wins
for i in range(iterations):
if checks.check_win_horizontal(board, i):
return True
        # check diagonal wins
if checks.check_win_diagonal_lr(board):
return True
        if checks.check_win_diagonal_rl(board):
return True
    def start(self):
"""Begins the tic-tac-toe game"""
        board_size = self.board.SIZE  
        while True:
chosen_tile = self.__ask_for_tile()
            if chosen_tile is None:
break
            while chosen_tile < 1 or chosen_tile > board_size * board_size:
print("tile is out of bounds!")
chosen_tile = self.__ask_for_tile()
            player = self.get_player()
self.board.set_tile(chosen_tile - 1, player)
            self.board.clear()
self.board.draw()
            if self.__check_if_won():
print("Player " + player + " won!")
break
                self.__choose_next_player()
Like what you read? Give Joe Burnard a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.