import copy import random class Othello: def __init__(self): self.board = [[' ' for _ in range(8)] for _ in range(8)] self.board[3][3] = 'O' self.board[3][4] = 'X' self.board[4][3] = 'X' self.board[4][4] = 'O' self.current_player = 'X' def print_board(self, valid_moves=None): print(" 0 1 2 3 4 5 6 7") print(" +-+-+-+-+-+-+-+-+") for i in range(8): row_str = f"{i}|" for j in range(8): if valid_moves and (i, j) in valid_moves: row_str += '█|' else: row_str += f"{self.board[i][j]}|" print(row_str) print(" +-+-+-+-+-+-+-+-+") def is_valid_move(self, row, col): if row < 0 or row > 7 or col < 0 or col > 7 or self.board[row][col] != ' ': return False directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] for d in directions: if self.is_flippable(row, col, d): return True return False def is_flippable(self, row, col, direction): x, y = row + direction[0], col + direction[1] if x < 0 or x > 7 or y < 0 or y > 7 or self.board[x][y] != self.get_opponent(): return False x, y = x + direction[0], y + direction[1] while 0 <= x < 8 and 0 <= y < 8: if self.board[x][y] == self.current_player: return True elif self.board[x][y] == ' ': return False x, y = x + direction[0], y + direction[1] return False def get_opponent(self): return 'O' if self.current_player == 'X' else 'X' def make_move(self, row, col): if not self.is_valid_move(row, col): print("Invalid move!") return False self.board[row][col] = self.current_player directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] for d in directions: self.flip_discs(row, col, d) self.current_player = self.get_opponent() return True def flip_discs(self, row, col, direction): x, y = row + direction[0], col + direction[1] while 0 <= x < 8 and 0 <= y < 8 and self.board[x][y] == self.get_opponent(): self.board[x][y] = self.current_player x, y = x + direction[0], y + direction[1] def game_over(self): for i in range(8): for j in range(8): if self.is_valid_move(i, j): return False return True def count_discs(self): x_count = sum(row.count('X') for row in self.board) o_count = sum(row.count('O') for row in self.board) return x_count, o_count def get_winner(self): x_count, o_count = self.count_discs() if x_count > o_count: return 'X' elif x_count < o_count: return 'O' else: return 'Tie' def get_valid_moves(self): valid_moves = [] for i in range(8): for j in range(8): if self.is_valid_move(i, j): valid_moves.append((i, j)) return valid_moves def ai_move(self, depth): best_move = self.alpha_beta_search(depth) if best_move: row, col = best_move self.make_move(row, col) print(f"Computer moves: {row}, {col}") return True return False def alpha_beta_search(self, depth): _, move = self.max_value(float('-inf'), float('inf'), depth, self.board) return move def max_value(self, alpha, beta, depth, board): if depth == 0 or self.game_over(): return self.evaluate(board), None v = float('-inf') best_move = None for move in self.get_valid_moves(): new_board = copy.deepcopy(board) self.simulate_move(new_board, move) _, min_move = self.min_value(alpha, beta, depth - 1, new_board) if _ > v: v = _ best_move = move alpha = max(alpha, v) if beta <= alpha: break return v, best_move def min_value(self, alpha, beta, depth, board): if depth == 0 or self.game_over(): return self.evaluate(board), None v = float('inf') best_move = None for move in self.get_valid_moves(): new_board = copy.deepcopy(board) self.simulate_move(new_board, move) _, max_move = self.max_value(alpha, beta, depth - 1, new_board) if _ < v: v = _ best_move = move beta = min(beta, v) if beta <= alpha: break return v, best_move def simulate_move(self, board, move): row, col = move board[row][col] = self.current_player directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] for d in directions: self.flip_discs_simulated(row, col, d, board) self.current_player = self.get_opponent() def flip_discs_simulated(self, row, col, direction, board): x, y = row + direction[0], col + direction[1] while 0 <= x < 8 and 0 <= y < 8 and board[x][y] == self.get_opponent(): board[x][y] = self.current_player x, y = x + direction[0], y + direction[1] def evaluate(self, board): x_count, o_count = self.count_discs_board(board) return x_count - o_count def count_discs_board(self, board): x_count = sum(row.count('X') for row in board) o_count = sum(row.count('O') for row in board) return x_count, o_count # Example usage: def human_move(game): valid_moves = game.get_valid_moves() while True: game.print_board(valid_moves) print(f"Player {game.current_player}'s turn.") row = int(input("Enter row: ")) col = int(input("Enter column: ")) if (row, col) in valid_moves: game.make_move(row, col) break else: print("Invalid move! Try again.") def computer_move(game, depth): game.ai_move(depth) def switch_player(game, player): if player == 'X': human_move(game) else: valid_moves = game.get_valid_moves() while not valid_moves: print("No valid moves for the computer. Skipping turn.") game.current_player = game.get_opponent() valid_moves = game.get_valid_moves() computer_move(game, 3) game = Othello() # Play until game over while not game.game_over(): switch_player(game, game.current_player) # Game over, print the winner game.print_board() x_count, o_count = game.count_discs() print(f"X: {x_count}, O: {o_count}") print(f"Winner: {game.get_winner()}")
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |