Skip to content

Instantly share code, notes, and snippets.

@ZaidaZadkiel
Last active February 6, 2022 03:37
Show Gist options
  • Save ZaidaZadkiel/600f81f270f44c34efae5daff4f5c832 to your computer and use it in GitHub Desktop.
Save ZaidaZadkiel/600f81f270f44c34efae5daff4f5c832 to your computer and use it in GitHub Desktop.
Tic Tac Toe in python in a 4 iteration for loop
# import only system from os
from os import system, name
import math
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# converted to regular array because dictionaries are annoying
board = [' '] * 9 # marks the game spots
board_x = [ 0] * 9 # holds player X's spots
board_o = [ 0] * 9 # holds player O's spots
def print_board(board):
#clear()
print(f"1:[{board[0]}] | 2:[{board[1]}] | 3:[{board[2]}] ")
print('------+-------+------')
print(f"4:[{board[3]}] | 5:[{board[4]}] | 6:[{board[5]}] ")
print('------+-------+------')
print(f"7:[{board[6]}] | 8:[{board[7]}] | 9:[{board[8]}] ")
# gets and validate input, looping if input is not valid
def get_input(turn):
while True:
try:
print(f"\nIt's your turn {turn} [1-9]: ", end='')
move = int(input())-1 # 1-based to 0-based
print(f"selected: {move}")
#check first if its within bounds
if(move < 0 or move > 8): #internal is 0-based, display is 1-based
print("It is not a valid number, use 1 to 9 only.")
continue
#test if the spot was not taken
if(board[move] == ' '):
board[move] = turn
player_board = board_x if (turn == 'X') else board_o
player_board[move] = 10 #any nonzero number
return move
print("That place is already filled, try again.")
except ValueError:
print("It is not a valid number, use 1 to 9 only. Try again") #this could be a specific error for "the input was not parsed as number"
continue
def check_win(turn):
player_board = board_x if (turn == 'X') else board_o
y = 0
# reads the player board, multiplies all the spots together 3-line by 3-line, if any of the
# tested line has any spot == 0, the result of the multiplication is 0
# if any of the lines is NOT zero, then that line is filled by this player
for x in range(1, 5): # 1, 2, 3, 4 bcz off by one (thankyou python! )
# takes the middle spot, adds the same index in postive and negative
# gets the diagonal, center vertical, second diagonal and middle horizontal
y += player_board[4-x] * player_board[4] * player_board[4+x]
#checks the outer lines: top horizontal, left vertical, right vertical, bottom horizontal
other = x+(x-1)
distance = 1+(2*(math.floor(other/3) % 2))
y += player_board[other-distance] * player_board[other] * player_board[other+distance]
return y!=0
def main():
turn = 'X'
counter = 0
clear()
for i in range(9):
print_board(board)
move = get_input(turn)
clear()
counter += 1
has_won = check_win(turn)
if(has_won):
print_board(board)
print(f"Player {turn} has won!")
return
turn = ['X', 'O'][counter % 2]
print("Nobody won, its a tie")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment