I made Othello to teach Python3 to children (3)

The program should be moved and learned by watching the explanation while watching the movement.

Anyway, the program works and it's Nambo. There is also the effect of promoting understanding by playing around with it from there, so today I will publish the source of the Othello game, although it is a little long. Let's create this as a new project for PyCharom.

Start PyCharm and create a "New Project" from the File menu. The project name should also be ** Othello **. スクリーンショット 2020-05-24 17.06.53.png

After creating the project, select "New ..." from the File menu, select the Python file, name it othello_cui.py, etc. and press Enter to find othello_cui.py in the left project pane. Will appear.

スクリーンショット 2020-05-24 17.07.40.png スクリーンショット 2020-05-24 17.08.47.png

Then copy and paste all of the following programs into othellocui.py. スクリーンショット 2020-05-24 17.14.59.png

Once you've done that, save your project with CTRL + S (command + S for Mac).

Othello game source

"""
Othello Game
Copyright 2020 (C) by tsFox
"""

class OthelloCls:
    def __init__(self):
        self.ot_bit = list()
        #Initial setting = Place 4 Othello pieces on the board
        for i in range(64):
            if i == 27 or i == 36:
                self.ot_bit.append('○')
            elif i == 28 or i == 35:
                self.ot_bit.append('●')
            else:
                self.ot_bit.append('・')
        self.ot_offdef = '●'                       #Which turn
        self.ot_search = '○'                       #The opposite hand
        #Using a dictionary for frame calculation next to eight directions
        #Create a calculation table (direction is key, calculated value is defined by Tupple)
        self.ot_direction = dict()                  #Eight-way search table
        self.ot_direction = { 'ul' : ( -1 , -1 ) ,  #Diagonally above left
                              'up' : (  0 , -1 ) ,  #Right above
                              'ur' : ( +1 , -1 ) ,  #Diagonally above right
                              'lt' : ( -1 ,  0 ) ,  #left
                              'rt' : ( +1 ,  0 ) ,  #right
                              'dl' : ( -1 , +1 ) ,  #Diagonally below left
                              'dn' : (  0 , +1 ) ,  #Directly below
                              'dr' : ( +1 , +1 ) }  #Diagonally below right
        #Termination position when it is judged that it can be turned over
        self.ot_lastposX = 0                        #Turn over end X
        self.ot_lastposY = 0                        #Turn over end Y

    #input
    def ot_inputXY(self,otstr):
        while True:
            myXY = input(otstr)
            if myXY == "":
                continue
            #I added some ways to check in the comment section!'20/5/30
            if myXY.isdigit() and (1 <= int(myXY) <= 8): 
                return int(myXY)
            print("Bubu ~! Enter 1-8!")

    #It's your turn
    def ot_yourturn(self):
        print("{}It's your hand!".format(self.ot_offdef))

    #It's your turn
    def ot_changeturn(self):
        self.ot_offdef = '●' if self.ot_offdef == '○' else '○'
        self.ot_search = '●' if self.ot_offdef == '○' else '○'

    #Determine if it's over (change the turn if you just can't put your hand)
    def ot_checkendofgame(self):
        #There is no place to put your own hand, and you can't put your opponent's hand
        if 0 > self.ot_canplacemypeace():
            self.ot_changeturn()
            if 0 > self.ot_canplacemypeace():
                bc = myot.ot_bit.count('●')
                wc = myot.ot_bit.count('○')
                if ( bc - wc ) > 0:
                    bws = "● Victory"
                elif ( bc - wc ) < 0:
                    bws = "○ Victory"
                else:
                    bws = "draw"
                print("{}is. Thank you for your hard work!".format(bws))
                return 1
            else:
                print("{}There is no place to put it. It changes to the opponent's turn! !!".format(self.ot_search))
                return -1
        else:
            return 0

    #Find out if there is a place to put your hands
    def ot_canplacemypeace(self):
        for n in range(64):
            if self.ot_bit[n] != '・':
                continue
            for d in self.ot_direction:
                if 1 == self.ot_next_onepeace(int(n%8)+1,int(n/8)+1, d):
                    return 0
        #If there is no place to put one, I will come here
        return -1

    #Put your hand on the board of Othello
    def ot_place(self, ot_x, ot_y):
        ot_change = False
        for d in self.ot_direction:
            if 1 == self.ot_next_onepeace(ot_x,ot_y,d):
                self.ot_peace(ot_x,ot_y,self.ot_offdef)
                self.ot_changepeace(ot_x,ot_y,d)
                ot_change = True
        #When there is no valid direction
        if not ot_change:
            print("{}Could not be placed".format(self.ot_offdef))
            return -1
        #Display the screen and change your hand to the opponent's turn
        self.ot_display()
        self.ot_changeturn()
        return 0

    #Processing to put the next move (including processing that cannot be placed)
    def ot_next_onepeace(self,ot_x,ot_y,ot_dir):
        #When the next hand in all directions from your position is the opposite hand and your own hand
        nx = self.ot_direction[ot_dir][0]
        ny = self.ot_direction[ot_dir][1]

        #Judgment that the next move cannot be placed in the first place
        if ( nx < 0 and ot_x == 1 ) or ( ny < 0 and ot_y == 1 ) or ( nx == 1 and ot_x == 8 ) or ( ny == 1 and ot_y == 8 ):
            return -1

        #Get the next one (left and top are in the minus direction when viewed from your hand)
        nextpeace = self.ot_peace(ot_x+nx,ot_y+ny)

        #Judgment that you can not put it if the next hand is your own hand
        if nextpeace == '・' or nextpeace == self.ot_offdef:
            return -1

        #Determine if there is a neighbor next door
        cx = ot_x+(nx*2)
        cy = ot_y+(ny*2)

        #Judged that it cannot be placed if there is no neighbor next to it (if the direction is left or top, judge the left end and the top)
        if ( nx < 0 and cx == 0 ) or ( nx > 0 and cx == 9 ) or ( ny < 0 and cy == 0 ) or ( ny > 0 and cy == 9 ):
            return -1

        #I can get the next one, so look for it
        nextnextpeace = self.ot_peace(cx,cy)

        if nextnextpeace == '・' :
            return -1         #I can't turn it over Notification

        if nextnextpeace == self.ot_offdef:
            #Record the end position that can be turned over
            self.ot_lastposX = cx
            self.ot_lastposY = cy
            return 1         #You can turn it over Notification

        #If your hand and your hand continue, call your function again (recursive)
        return self.ot_next_onepeace(ot_x+nx, ot_y+ny, ot_dir)

    #The process of turning over the hand
    def ot_changepeace(self,ot_x,ot_y,ot_dir):
        #When the next hand in all directions from your position is the opposite hand and your own hand
        nx = self.ot_direction[ot_dir][0]
        ny = self.ot_direction[ot_dir][1]
        #Rewrite the next one
        nextpeace = self.ot_peace(ot_x+nx,ot_y+ny,self.ot_offdef)
        #Next to next coordinates
        cx = ot_x+(nx*2)
        cy = ot_y+(ny*2)
        #End if the flip position is the last coordinate
        if cx == self.ot_lastposX and cy == self.ot_lastposY:
            return
        #If you can still turn it over, call yourself again (recursive)
        return self.ot_changepeace(ot_x+nx, ot_y+ny, ot_dir)

    #Get the hand at the specified position (and rewrite it as well)
    def ot_peace(self,ot_x,ot_y,ot_chr=None):
        if ot_chr != None:
            self.ot_bit[(ot_y - 1) * 8 + (ot_x - 1)] = ot_chr
        return self.ot_bit[(ot_y-1)*8+(ot_x-1)]

    #Display the board of Othello
    def ot_display(self):
        print("X① ② ③ ④ ⑤ ⑥ ⑦ ⑧")
        for l in range(1,9):
            print("{}".format(l), end='' )
            for c in range(1,9):
                print(" {}".format(self.ot_bit[(l-1)*8+(c-1)]), end='')
            print()
        print("            ○:{} ●:{}".format(self.ot_bit.count('○'),self.ot_bit.count('●')))

if __name__ == '__main__':

    myot = OthelloCls()
    myot.ot_display()

    while True:
        #Determine if the game is over or if there is a place to put your hand
        sts = myot.ot_checkendofgame()
        if sts == 1:            #Game over
            break
        elif sts < 0:           #I can't put my hand
            continue

        #Show which turn
        myot.ot_yourturn()
        #Enter the X and Y coordinates
        myx = myot.ot_inputXY("X = ")
        myy = myot.ot_inputXY("Y = ")
        #Put your hand on the specified coordinates
        myot.ot_place(myx,myy)

Let's play once! !!

You can start the program by selecting Run othello_cui from PyCharm's Run menu or by pressing the green triangle Run button at the left end of ʻif name =='main': `in the source. スクリーンショット 2020-05-24 17.18.35.png

When the program executed like this is displayed at the bottom of the PyCharm screen, enter X (horizontal) 1 to 8 and then Y (vertical) 1 to 8 to enter the family's Try to play against someone in Othello.

スクリーンショット 2020-05-24 17.22.23.png

What happens to the screen if I do something? After playing the game to the end while observing everywhere, I would like to explain the contents of the program in detail from the next time.

Studying Python today = Variables

In this chapter we want to learn about Python variables.

What is a variable? It's not a "strange number". Think of it as a container that stores the various values that your program generates. For example, when cooking, the ingredients are cut in advance and put in a bowl, and this bowl plays the same role as a variable. For those who cook, suddenly put salt in a cooking pot, add sugar, add soy sauce, and once in a measuring cup, add half a teaspoon of salt, one teaspoon of sugar, three tablespoons of soy sauce, etc. You put it in, taste it there, and then put it in a pot. There is no doubt that you can think of this measuring cup as a variable.

Think about why you need variables. If you think about the recipe, you can see that if it's a program that only makes curry for 3 people, what you put in is decided, and the amount is also decided, isn't it? But what if you wanted to be able to make as many curry programs as you like? First of all, the number of people changes every time, so you have to put the specified number of people in the variable. Since the amount of ingredients such as potatoes also changes, this must also be included in the variable. In reality, if a program that can make anything is better than a program that makes only curry, the number of types of ingredients, the number and amount of seasonings to be added will change steadily. Do you understand that variables are indispensable for a program? ??

Today I would like to explain some variables.

General variables and operations

For general variables, the value of the variable is of course rewritable.

If you do ʻage = 12, you are assigning the value 12 to the variable named age. If this age 12 person gets one year next year, he can add +1 to the value in age by writing ʻage + = 1. This is called ** operation **. The following operators can be used for calculation. In addition, the operation has priority, and unless specified in (), the operation is performed according to the appearance order and priority assigned to the operator.

operator meaning Calculation priority
+ Add + 3
- Pull- 3
* Call 2
/ Divide 2
// Truncation division 2
% Remainder 2
** Exponentiation 1

The following calculations are performed in order of priority from the left.

temp = 20 * 3 / 10 + 5 * 3
60 / 10 + 15
6 + 15
21

You can also explicitly specify the calculation priority by adding ().

temp = 20 * 3 / (10 + 5) * 3
60 / 15 * 3
4 * 3
12

A variable called an array

It's enough to put only one value in one variable, but there are times when you want to put a large number of values in one variable. In such cases, use a variable called ** array **. For example, if you want to have 7 days of the week in letters,

WeekDay = [ "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday" ]

When accessing the value of an array, specify a numerical value called a subscript or index, such as WeekDay [0]. For the index, specify 0 to access the very first value. It's 0 on Monday, 1 on Tuesday ...

Arrays have the idea of multidimensional arrays. In the previous example, it is a one-dimensional array containing 7 character strings, but if you want to have calendar data, for example, you can create an array with 31 arrays and 12 arrays, so Calendar [12] [ You can also create a two-dimensional array called 31] . It is also a good idea to use a multidimensional array depending on the program to be created, but if it is too multidimensional, it will be difficult to understand, so it is better to focus on being able to understand and write clean code. Let's do it.

Next time, I would like to learn about Tuple and Dictionary, which are unique to Python, while explaining the program. First of all, please play the Othello game! !!

c u

<< I made Othello to teach Python3 to children (2) I made Othello to teach Python3 to children (4) >>

Recommended Posts

I made Othello to teach Python3 to children (4)
I made Othello to teach Python3 to children (2)
I made Othello to teach Python3 to children (5)
I made Othello to teach Python3 to children (3)
I made Othello to teach Python3 to children (1)
I made Othello to teach Python3 to children (6) Final episode
I made blackjack with python!
I made a python text
I made a python library to do rolling rank
I made blackjack with Python.
I made an action to automatically format python code
Othello made with python (GUI-like)
I made wordcloud with Python.
I made a package to filter time series with python
I made an animation to return Othello stones with POV-Ray
I made a Line-bot using Python!
I made my own Python library
I made a fortune with Python.
Othello game development made with Python
I want to debug with Python
I made a daemon with Python
I made a library to easily read config files with Python
I tried to teach Python to those who have no programming experience
I made a library that adds docstring to a Python stub file.
I tried to summarize Python exception handling
I tried to implement PLSA in Python
I tried to implement permutation in Python
I made a payroll program in Python!
I made a character counter with Python
I installed Python 3.5.1 to study machine learning
I tried to implement PLSA in Python 2
Python3 standard input I tried to summarize
I want to use jar from python
I wanted to solve ABC160 with Python
I want to build a Python environment
I want to analyze logs with Python
I want to play with aws with python
I tried to implement ADALINE in Python
I wanted to solve ABC159 in Python
I tried to implement PPO in Python
I made a script to display emoji
I made a Hex map with Python
[Python] I tried to calculate TF-IDF steadily
After studying Python3, I made a Slackbot
I wanted to solve ABC172 with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
What I did to save Python memory
Othello app (iOS app) made with Python (Kivy)
[Python] I made a decorator that doesn't seem to have any use.
I made a web application in Python that converts Markdown to HTML
Environment maintenance made with Docker (I want to post-process GrADS in Python
I made a program to check the size of a file in Python
I refactored "I tried to make Othello AI when programming beginners studied python"
I made a function to see the movement of a two-dimensional array (Python)
Updated to Python 2.7.9
I made a python dictionary file for Neocomplete
I want to do Dunnett's test in Python
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.