以下のコードをGoogle ColabなどのPythonを実行できる環境で実行してみてください。
# Othello Game Program
# Define the board
board = [[' ' for x in range(8)] for y in range(8)]
board[3][3] = 'W'
board[3][4] = 'B'
board[4][3] = 'B'
board[4][4] = 'W'
# Define the players
player1 = 'B'
player2 = 'W'
# Define the function to print the board
def print_board(board):
print(' 0 1 2 3 4 5 6 7')
print(' +-+-+-+-+-+-+-+-+')
for i in range(8):
print(str(i) + '|' + '|'.join(board[i]) + '|')
print(' +-+-+-+-+-+-+-+-+')
# Define the function to check if a move is valid
def is_valid_move(board, player, row, col):
if board[row][col] != ' ':
return False
for xdir, ydir in [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]:
r, c = row, col
r += xdir
c += ydir
if r < 0 or r >= 8 or c < 0 or c >= 8:
continue
if board[r][c] == ' ' or board[r][c] == player:
continue
r += xdir
c += ydir
while r >= 0 and r < 8 and c >= 0 and c < 8:
if board[r][c] == ' ':
break
if board[r][c] == player:
return True
r += xdir
c += ydir
return False
# Define the function to make a move
def make_move(board, player, row, col):
if not is_valid_move(board, player, row, col):
return False
board[row][col] = player
for xdir, ydir in [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]:
r, c = row, col
r += xdir
c += ydir
if r < 0 or r >= 8 or c < 0 or c >= 8:
continue
if board[r][c] == ' ' or board[r][c] == player:
continue
r += xdir
c += ydir
while r >= 0 and r < 8 and c >= 0 and c < 8:
if board[r][c] == ' ':
break
if board[r][c] == player:
while True:
r -= xdir
c -= ydir
if r == row and c == col:
break
board[r][c] = player
break
r += xdir
c += ydir
return True
# Define the function to get the player's move
def get_move(board, player):
while True:
row = int(input('Enter row: '))
col = int(input('Enter column: '))
if is_valid_move(board, player, row, col):
return row, col
else:
print('Invalid move. Try again.')
# Define the main function
def main():
print('Welcome to Othello!')
print_board(board)
while True:
# Player 1's turn
print('Player 1 (Black)')
row, col = get_move(board, player1)
make_move(board, player1, row, col)
print_board(board)
# Player 2's turn
print('Player 2 (White)')
row, col = get_move(board, player2)
make_move(board, player2, row, col)
print_board(board)
if __name__ == '__main__':
main()