Skip to content

Instantly share code, notes, and snippets.

@arnaudbouffard
Created August 10, 2020 15:13
Show Gist options
  • Save arnaudbouffard/8dc2b41e8a9b6c89aaf65a4d8e8abbba to your computer and use it in GitHub Desktop.
Save arnaudbouffard/8dc2b41e8a9b6c89aaf65a4d8e8abbba to your computer and use it in GitHub Desktop.
command line python tictactoe
#! python3
# tictactoe.py - command line tic tac toe game
import random
from itertools import cycle
myIterator = cycle(range(2))
players = ["O", "X"]
game_result = ""
deck = [
[".",".","."],
[".",".","."],
[".",".","."]]
def print_deck(deck):
print()
for line in deck:
for position in line:
print(position + " ", end = "")
print()
print()
def deck_is_full(deck):
# check if there are remaining empty positions
period_in_deck = any("." in line for line in deck)
# if not, return game result
if not period_in_deck:
return "Draw: nobody wins..."
def three_in_line(deck, sign):
# for each line in the deck
for line in deck:
# we check if they only contain the sign passed as a parameter
if "".join(line) == 3 * sign:
return f"{sign} wins!"
for col in range(3):
if deck[0][col] == sign and deck[1][col] == sign and deck[2][col] == sign:
return f"{sign} wins!"
if deck[1][1] == sign:
if deck[0][0] == sign and deck[2][2] == sign:
return f"{sign} wins!"
if deck[0][2] == sign and deck[2][0] == sign:
return f"{sign} wins!"
def game_over(deck):
if deck_is_full(deck):
return deck_is_full(deck)
if three_in_line(deck, "X"):
return three_in_line(deck, "X")
if three_in_line(deck, "O"):
return three_in_line(deck, "O")
return False
# we randomly choose which player starts
player_to_play = random.choice(players)
# and make sure he's second in the players array
if players[0] == player_to_play:
players.append(players.pop(0))
print(f"Welcome to TicTacToe! \nPlayer {player_to_play} gets to start!\n")
while not game_over(deck):
print(f"Player {player_to_play}, please type the position you want to fill:")
print_deck(deck)
player_input = input()
# put player sign at player inputed deck position
deck[int(player_input[0])][int(player_input[1])]= player_to_play
# use itertools.cycle() to cycle to next player
# (1st iteration is 0, 2nd is 1, etc.)
player_to_play = players[next(myIterator)]
print()
print(20 * "*")
print_deck(deck)
print(game_over(deck))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment