Skip to content

Instantly share code, notes, and snippets.

@FrederickGeek8
Created October 16, 2019 14:52
Show Gist options
  • Save FrederickGeek8/93905461190e369351c71ea0fc41f746 to your computer and use it in GitHub Desktop.
Save FrederickGeek8/93905461190e369351c71ea0fc41f746 to your computer and use it in GitHub Desktop.
Solutions for the "hard" problems in the Fall 2019 SPLICE Club "Get to know Python" workshop
# Problem 1
# blank board
tic_tac_toe = [
['□', '□', '□'],
['□', '□', '□'],
['□', '□', '□']
]
# Problem 2
def show_board(board):
for row in board:
string = ""
for item in row:
string += item + " "
print(string)
# Problem 3
def is_won(board):
# Check if the rows contain a winning condition
for row in board:
# I realize that I forgot to mention the 'and', 'or', and 'not'
# conditions. They allow you to use multiple conditions in your
# if statements and check for false (as their same suggests)
if row[0] != '□' and row[0] == row[1] and row[1] == row[2]:
return True
# Check if the columns contain a winning condition
for col in range(len(row[0])):
if board[0][col] != '□' and board[0][col] == board[1][col] and board[1][col] == board[2][col]:
return True
# Check if the diagonals contain a winning condition
if board[0][0] != '□' and board[0][0] == board[1][1] and board[1][1] == board[2][2]:
return True
if board[0][2] != '□' and board[0][2] == board[1][1] and board[1][1] == board[2][0]:
return True
return False
# Problem 4
def is_draw(board):
for row in board:
for item in row:
if item == '□':
return False
return True
# While the game is not a draw
while not is_draw(tic_tac_toe):
show_board(tic_tac_toe)
# Player 1 move
while True:
x = int(input("Enter the X coordinate (1-3) of your move: ")) - 1
y = int(input("Enter the Y coordinate (1-3) of your move: ")) - 1
if x < 0 or x > 2 or y < 0 or y > 2:
print('Invalid coordinates. Please try again.')
continue
if tic_tac_toe[y][x] != '□':
print('This move has already been played. Please try again.')
continue
tic_tac_toe[y][x] = 'X'
if is_won(tic_tac_toe):
print('Player 1 wins!')
# Exit program
exit(0)
else:
break
show_board(tic_tac_toe)
if is_draw(tic_tac_toe):
print('Game is a draw!')
# Exit program
exit(0)
while True:
x = int(input("Enter the X coordinate (1-3) of your move: ")) - 1
y = int(input("Enter the Y coordinate (1-3) of your move: ")) - 1
if x < 0 or x > 2 or y < 0 or y > 2:
print('Invalid coordinates. Please try again.')
continue
if tic_tac_toe[y][x] != '□':
print('This move has already been played. Please try again.')
continue
tic_tac_toe[y][x] = 'O'
if is_won(tic_tac_toe):
print('Player 2 wins!')
# Exit program
exit(0)
else:
break
print('Game is a draw!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment