Hello! It's cool! !!
This time I would like to make Othello in Python.
(Addition) (1) Random was not necessary. I'm sorry. The required libraries are as follows. (1) random (2) numpy
(1) is called the standard library and is originally built into Python, so you don't need to pip install it.
If numpy in (2) is not installed,
Type in the command prompt and try installing.
When the library is ready, I would like to enter the main Othello program.
from numpy import zeros, where, float32
class othello:
    #constant(-By multiplying by 1, you can express the flip from black to white and from white to black.)
    white = 1.
    black = -1.
    empty = 0.
    edge = 8          #Number of sides
    
    #Initialization
    def __init__(self):
        self.board = zeros(self.edge**2, dtype=float32)     #0 on the board(=self.empty)Initialize with
        self.board[27] = self.board[36] = self.white           #Initial frame arrangement
        self.board[28] = self.board[35] = self.black            #Initial frame arrangement
        self.turn = True                             # white:True  black:False
        self.available = []                          #An array that holds the coordinates of where you can flip
    #Turn over s:Place number ex:If True, turn over,If False, just check if it can be placed without turning it over
    def over(self, s, ex=True):
        s = int(s)
        start = s
        my_color = self.white if self.turn else self.black      
        flag = False               #Flag whether it can be placed in s
        for i in range(-1, 2):
            for j in range(-1, 2):
                v = self.edge * i + j       #v is 8 directions(Any of)Represents a move to
                if v == 0:
                    continue
                s = start
                for k in range(self.edge - 1):
                    s += v                         #Add the amount of movement
                    if (s < 0 or s > self.edge**2 - 1 or self.board[s] == self.empty):   #If it is off the board or empty, it cannot be turned over in that direction.
                        break
                    if self.board[s] == my_color:                        #If it matches your color
                        if k > 0:                                               # k=When it is 0,Place where you put it(start)Since it is a square that is in contact with
                            if ex:          
                                self.board[start + v: s : v] *= -1      #Perform flip
                            flag = True                                    #If you can turn over even one sheet, you can put it in that place
                        break
                    if (((s % self.edge == 0 or s % self.edge == self.edge - 1) and abs(v) != self.edge)
                        or ((s // self.edge == 0 or s // self.edge == self.edge - 1) and abs(v) != 1)):
                        break
        if flag and ex:                   #If you can put a piece in the specified place, put it
            self.board[start] = my_color
        return flag
    #Win / loss judgment
    def judge(self):
        n_white = len(where(self.board == self.white)[0])     #Number of Shiroishi
        n_black = len(where(self.board == self.black)[0])      #Number of black stones
        print("\n", "black>> ", n_black, "White>> ", n_white, "\n")     #Output the number of stones
        if n_white < n_black:                   
            print("Black wins")
        elif n_black < n_white:
            print("White wins")
        else:
            print("draw")
    #Update function
    def update(self, end=False):
        self.turn ^= True
        self.available = []                                             # self.Put the coordinates that can be placed in available
        for i in range(self.edge**2):
            if self.board[i] == self.empty and self.over(i, ex=False):
                self.available.append(i)
        if len(self.available) == 0:           
                return False if end else self.master(end=True)           #If you can't put it twice in a row, the game ends
        self._input()
        return True
    
    #input(CUI)
    def _input(self):
        while True:
            msg = "White turn" if self.turn else "Black turn"         
            x, y = map(int, input(msg + "Matrix specification>> ").split())
            if 8 * x + y in self.available:                     #When the place where the stone can be placed is entered
                self.over(8 * x + y)                            #The process of turning over
                break
            print("---Invalid Position---")                    #Warning message when a place where stones cannot be placed is entered
    #Board drawing(CUI)
    def draw(self):
        edge = self.edge
        print("\n    0  1  2  3  4  5  6  7")
        for i in range(edge):
            temp = []
            temp.append(str(int(i)))
            for el in self.board[edge * i:edge * (i + 1)]:
                if el == self.white:
                    temp.append("○")
                elif el == self.black:
                    temp.append("●")
                else:
                    temp.append("+")
            print(" ".join(temp))            
#Main function
def main():
    s = othello()                #Othello instance generation
    flag = True                  #Flag of whether the game is continuing(True:Ongoing, False:End)
    while flag:
        s.draw()                  #Board drawing
        flag = s.update()     #Update function
    s.judge()                     #Win / loss judgment when the game is over
if __name__ == "__main__":
    main()
(important point) (1) In the over method, the keyword argument ex is used to determine whether or not the frame is actually flipped. The time when you don't have to turn it over is when you search for where to put the pieces in advance.
(2) In the over method, the coordinates of the board are expressed by the index on self.board instead of the matrix format. So be careful about matrix and index conversion. For example, the index for i-by-j is i * self.edge + j.
Try copying and running this program. Please feel free to contact us if you have any problems.
Recommended Posts