This is my first program written outside of using books and tutorials. Any help on style and functionality would be helpful.
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]} *
*************
'''))
move_count= 0
def main():
while True:
#Prints board layout to console.
board_layout()
#checks for a winner when called at end of each turn
def check_winner():
global move_count
#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]]]
#Keeps a reference to winning_list so it is updated at the end of every turn
new_list = winning_list
#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()
#possible moves is 9 in tic tac toe. If all moves are taken and there is no winner no winner forces a draw.
if move_count == 9:
print('You Tied')
end()
#Takes user input for the move
move =int(input('Please select a spot: '))
print(move)
#Player move, makes sure the spot is not taken and adds 1 to move_count
if board[move] !='x' and board[move] != 'o':
board[move] = 'x'
move_count += 1
check_winner()
#npc move, chooses a random spot that is not taken and adds 1 to move_count
while True:
npc = random.randint(0,8)
if board[npc] != 'o' and board[npc] != 'x':
board[npc] = 'o'
print('Computer chooses spot ', npc)
move_count += 1
check_winner()
break
#If spot is taken prints that the spot is already taken
else:
print('This spot is taken')
#Game ending
def end():
print('Thank you for playing')
sys.exit()
if __name__ == "__main__":
main()
check_winner()
would be checking only those lines where the move has been just made. Not sure, though, if it is an improvement - it would certainly save some effort on checking lines which did not change recently, but it would require additional work on selecting those needing checking. However, in games on bigger boards it will definitely make some gain. \$\endgroup\$