(For beginners) Let's make Othello with Python

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

(For beginners) Let's make Othello with Python
Let's make Othello with wxPython
Let's make a GUI with python.
Let's make Othello AI with Chainer-Part 1-
Let's make a graph with python! !!
Let's make Othello AI with Chainer-Part 2-
INSERT into MySQL with Python [For beginners]
Let's make a shiritori game with Python
Let's put together Python for super beginners
Let's make a voice slowly with Python
[Python] Let's make matplotlib compatible with Japanese
[Python] Read images with OpenCV (for beginners)
WebApi creation with Python (CRUD creation) For beginners
Let's make a web framework with Python! (1)
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
[For beginners] Try web scraping with Python
python textbook for beginners
OpenCV for Python beginners
Causal reasoning and causal search with Python (for beginners)
~ Tips for Python beginners from Pythonista with love ① ~
Let's replace UWSC with Python (5) Let's make a Robot
Let's make a module for Python using SWIG
How to make Python faster for beginners [numpy]
~ Tips for Python beginners from Pythonista with love ② ~
[Introduction for beginners] Working with MySQL in Python
Rock-paper-scissors with Python Let's run on a Windows local server for beginners
Let's analyze Covid-19 (Corona) data using Python [For beginners]
Learning flow for Python beginners
[Let's play with Python] Make a household account book
Let's make a simple game with Python 3 and iPhone
Make Puyo Puyo AI with Python
Python3 environment construction (for beginners)
Python #function 2 for super beginners
Make a fortune with Python
Let's write python with cinema4d.
Basic Python grammar for beginners
100 Pandas knocks for Python beginners
Python for super beginners Python #functions 1
Python #list for super beginners
~ Tips for beginners to Python ③ ~
Let's build git-cat with Python
[Super easy] Let's make a LINE BOT with Python.
Othello made with python (GUI-like)
❤️ Bloggers ❤️ "Beloved BI" ❤️ Let's get started ❤️ (For those who can make charts with Python)
Let's make a websocket client with Python. (Access token authentication)
[For beginners] Summary of standard input in Python (with explanation)
Experiment to make a self-catering PDF for Kindle with Python
Solve AtCoder Problems Boot camp for Beginners (Medium 100) with python
Make Echolalia LINEbot with Python + heroku
Make apache log csv with python
Python Exercise for Beginners # 2 [for Statement / While Statement]
Python for super beginners Python # dictionary type 1 for super beginners
Getting Started with Python for PHPer-Classes
Let's make a breakout with wxPython
Python #index for super beginners, slices
Let's play with Excel with Python [Beginner]
Othello game development made with Python
Make a recommender system with python
<For beginners> python library <For machine learning>
Let's do image scraping with Python