Implement the following features:
board[row][column]
Drawing a random integer number can be done by utilizing a Python function called randrange(). The example program below shows how to use it (the program prints ten random numbers from 0 to 8).
Note: the from-import instruction provides an access to the randrange function defined within an external Python module called random.
from random import randrange
for i in range(10):
print(randrange(8))
from random import randrange
from warnings import showwarning
board = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
def display():
print('+-------+-------+-------+')
print('| | | |')
print('| ', board[0][0], ' | ', board[0][1], ' | ', board[0][2], ' |')
print('| | | |')
print('+-------+-------+-------+')
print('| | | |')
print('| ', board[1][0], ' | ', board[1][1], ' | ', board[1][2], ' |')
print('| | | |')
print('+-------+-------+-------+')
print('| | | |')
print('| ', board[2][0], ' | ', board[2][1], ' | ', board[2][2], ' |')
print('| | | |')
print('+-------+-------+-------+')
def move(player: str, n: int):
for i in range(3):
for j in range(3):
if n == board[i][j]:
board[i][j] = player
return True
return False
def randmove(player: str):
while not move(player, randrange(8)):
continue
def won(player: str):
for i in range(3):
if player == board[i][0] and player == board[i][1] and player == board[i][2]:
return True
for j in range(3):
if player == board[0][j] and player == board[1][j] and player == board[2][j]:
return True
return \
player == board[0][0] and player == board[1][1] and player == board[2][2] or \
player == board[0][2] and player == board[1][1] and player == board[2][0]
if __name__=='__main__':
player = input('Enter a team (\'X\' or \'O\') : ')
computer = 'O' if player == 'X' else 'X'
circle = 0
while True:
n = int(input('Enter a move (0 to 8) : ' ))
if not move(player, n):
print('Try once again!')
continue
display()
if won(player):
print('Player', player, 'is won!!!')
break
circle += 1
if circle == 9:
print('Draw!!!')
break
randmove(computer)
display()
if won(computer):
print('Player', computer, 'is won!!!')
break
circle += 1
Comments
Leave a comment