I am unsure if I followed the the suggestions on my previous post. I have only been working on programming for about 3 weeks so any more suggestions or insight would be more than welcomed.
import sys
from textwrap import dedent
import os
import random
os.system('CLS')
# board number setup
board = [0, 1, 2,
3, 4, 5,
6, 7, 8]
# Defines the board layout printed to the console
def board_layout():
print(dedent(f'''
*************
* {board[0]} | {board[1]} | {board[2]} *
*-----------*
* {board[3]} | {board[4]} | {board[5]} *
*-----------*
* {board[6]} | {board[7]} | {board[8]} *
*************
'''))
def main():
players = ('Player','NPC')
turn = 'Player'
change_turn = 0
for moves in range(9):
if turn == 'Player':
while True:
try:
board_layout()
player_move = int(input('Please select a spot: '))
if board[player_move] != 'x' and board[player_move] != 'o':
board[player_move] = 'x'
check_winner()
break
except IndexError:
print('please select valid spot')
if turn == 'NPC':
# npc move, chooses a random spot that is not taken
while True:
npc = random.randint(0, 8)
if board[npc] != 'o' and board[npc] != 'x':
board[npc] = 'o'
print('Computer chooses spot ', npc)
check_winner()
break
try:
change_turn += 1
turn = players[change_turn]
except:
change_turn = 0
turn = players[change_turn]
else:
print('You Tied')
end()
def end():
print('Thank you for playing')
answer = input('Would you like to play again?: Y/N')
if answer.lower() == 'n':
quit()
elif answer.lower() == 'y':
clear_board()
main()
else:
print('Please choose a valid option')
end()
def clear_board():
for i in range(9):
board[i] = i
# checks for a winner when called at end of each turn
def check_winner():
# list of lists with all the winning combinations for from the tic tac toe board
winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],
[board[6], board[7], board[8]], [board[0], board[4], board[8]],
[board[2], board[4], board[6]],
[board[0], board[3], board[6]], [board[1], board[4], board[7]],
[board[2], board[5], board[8]]]
# iterates over the lists in winning_list
for i, j, k in winning_list:
# looks at the lists in winning_list to determine if a list has all x's for a win
if i == 'x' and j == 'x' and k == 'x':
print('X wins')
end()
# looks at the lists in winning_list to determine if a list has all o's for a win
elif i == 'o' and j == 'o' and k == 'o':
print('O wins')
end()
if __name__ == "__main__":
main()