Based on this Code Review answer, I have created a noughts and crosses game in Python, which asks for an index (1 to 9) and updates the grid, and displays it on the screen. I have done some very untidy programming in places, and would please like some help on how to make it more readable, and avoid repeating statements, such as print_grid()
. Also I would like to make the 'Change player' part more simple. Any other constructive criticism or improvements also gratefully recieved.
winning_lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6),
(1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
def get_turn(player):
return int(input("Player %d: " % player).strip()) - 1
def format_player(num):
return ' OX'[num]
def print_grid(board):
"""Formats and prints the grid."""
print('\n'
'{}│{}│{}\n'
'─┼─┼─\n'
'{}│{}│{}\n'
'─┼─┼─\n'
'{}│{}│{}\n'
'\n'
.format(*board))
def check_for_win(board, player):
"""Returns True for win, anything else, False"""
for winning_line in winning_lines: # Take all possible winning lines one by one
for pos in winning_line: # Test each index of the winning line
if board[pos] != format_player(player):
break
else: return True
return False
def play_game():
player = 1
board = [" "] * 9
while True:
print_grid(board)
place = get_turn(player)
if place in range(9) and board[place] == " ":
board[place] = format_player(player)
if check_for_win(board, player):
print_grid(board)
return player
# Change player
if player == 1:
player = 2
else:
player = 1
winner = play_game()
print("Player %d wins!" % winner)