198k views
2 votes
Write code to play a Tic-tac-toe tournament. Tic-tac toe is a game for two players who take turns marking the spaces with Xs and Os in a 3x3 grid. The purpose of the game is to place three of your marks in a horizontal, vertical or diagonal.

User Roctimo
by
3.6k points

1 Answer

8 votes

Answer:

Step-by-step explanation:

The following code is written in Python and is a full Two player tic tac toe game on a 3x3 grid that is represented by numbers per square.

# Making all of the main methods of the game

board = [0,1,2,

3,4,5,

6,7,8]

win_con = [[0,1,2],[3,4,5],[6,7,8],

[0,3,6],[1,4,7],[2,5,8],

[0,4,8],[2,4,6]] # possible 3-in-a-rows

def show():

print(board[0],'|',board[1],'|',board[2])

print('----------')

print(board[3],'|',board[4],'|',board[5])

print('----------')

print(board[6],'|',board[7],'|',board[8])

def x_move(i):

if board[i] == 'X' or board[i] == 'O':

return print('Already taken!')

else:

del board[i]

board.insert(i,'X')

def o_move(i):

if board[i] == 'X' or board[i] == 'O':

return print('Already taken!')

else:

del board[i]

board.insert(i,'O')

# Creating the main loop of the game

while True:

turn_num = 1

board = [0,1,2,3,4,5,6,7,8]

print('Welcome to Tic-Tac-Toe!')

print('AI not implemented yet.')

while True:

for list in win_con: #check for victor

xnum = 0

onum = 0

for num in list:

if board[num] == 'X':

xnum += 1

elif board[num] == 'O':

onum += 1

else:

pass

if xnum == 3 or onum == 3:

break

if xnum == 3 or onum == 3: # break loops

break

if turn_num > 9: # Check if there are any more moves available

break

show()

if turn_num % 2 == 1:

print('X\'s turn.')

else:

print('O\'s turn.')

move = int(input('Choose a space. '))

if turn_num % 2 == 1:

x_move(move)

else:

o_move(move)

turn_num += 1

if xnum == 3: #If game ends

print('X Won!')

elif onum == 3:

print('O Won!')

else:

print('Draw!')

play_again = input('Play again? Y or N ')

if play_again == 'Y' or play_again == 'y':

continue

else:

break

User Huwiler
by
3.6k points