I made Othello to teach Python3 to children (4)

Let's explain the Othello game program

Let's understand the function

Functions are a very important element in a program. A function is a set of actions as a function.

For example, the function "eat" includes the following actions.

  1. Put in your mouth
  2. Chew
  3. Taste
  4. Swallow
  5. (Extraordinarily if you feel danger, spit it out)

If you write this 5-step logic every time you eat something, the code will be redundant, and if there is a story like "you should check the aroma" in the "eat" function, all the logic to eat It's hard because I have to fix and turn around. Therefore, define the same code that appears several times as a ** function **, and pass the part that changes what you eat as a ** variable **.

To define a function in Python, write: If what you pass as a parameter is variable, you have an "eat" function that allows you to eat anything.

def EatFood(food):

If you want to eat curry, call ʻEatFood ("curry") , and if you want to feed udon, call ʻEatFood ("udon "). If you pass the value you want to eat in parentheses, the function that receives it will perform the function and return. The value to be passed is called ** argument ** and so on.

In the math world, a function would do sum (10,20,30) to execute 10 + 20 + 30 and return 60 as the sum, or ʻaverage (70,70,100)`. It may find the average of 70, 70, 100 and return 80 as a result. In the world of programs, a function is also a block that organizes processing, and if you pass some value, it will be processed and returned, or it will be returned after operating based on some value.

Let's understand the class

In the previous (3), we explained ** variables **. And in this chapter we have described ** functions **. Next, after learning about ** class **, I would like to explain the source of Othello games. In the world of programming, the word ** class ** should be noticeable. What is a ** class **?

In the ** function ** above, I illustrated a function called EatFood (). We talked about these as chunks of functionality, but ** classes ** are more like chunks of larger chunks.

For example, let's say you create a ** class ** called human.

The human class requires the following elements:

element type Description
sex variable Variable that stores values related to gender
Birthday variable Birthdayを格納する変数
height variable Variable to store height
body weight variable Variable to store weight
speak function Function to act to speak
sleep function Function to sleep
Get up function Function to take action

If you actually classify humans, this kind of thing is not enough, but the elements that make up ** humans ** in this way are called ** classes **. I will. If you write it in Python, it will look like this.

class Human:
    #Human class variables
    def __init__(self):
        self.sex = None        #Gender variable
        self.birthday = None   #Birthday
        self.tall = None       #height
        self.weight = None     #body weight
    #speak
    def talk(self, quote):
~~~logic~~~
    #sleep
    def sleep(self):
~~~logic~~~
    #Get up
    def wakeup(self):
~~~logic~~~

This Human class is like a blueprint that defines a human who has no substance yet. When actually programming, you have to use this Human class to materialize it. This is called instantiation. Now, let's instantiate Sazae-san and Maso-san.

Sazae= Human()
Sazae.sex = female
Sazae.tall = 159
Sazae.weight = 48
Sazae.talk("Ngagugu")    #Talk with ngagugu

Mr. Maso= Human()
Mr. Maso.sex = male
Mr. Maso.tall = 173
Mr. Maso.weight = 70
Mr. Maso.talk("Yeah? ??")    # Yeah? ?? としゃべる

By creating multiple entities with the same blueprint in this way, it becomes possible to program more efficiently. There are various benefits to classifying. For example, in the Othello game, the Othello game itself has been classified, but if you make it more beautifully, you will be able to create a derivative class and create a graphical Othello class. In a programming language called object-oriented, libraries of various classes are prepared, and classes created by great programmers such as GitHub are published. By using such a class library, it is possible to create programs efficiently instead of creating everything from scratch.

Let's explain the Othello class (1)

As I explained earlier, a class is a blueprint made up of a bunch of ** variables and functions **. I created the Othello class as a class for making Othello games, but I would like to explain what variables and functions there are.

First is the variable part. The class starts the declaration with class * className *:. All the indented parts from this declaration are included in the class. The variables of the class are defined in the initialization function def __init __ (self):. (There are different ways, but explaining the different ways will only confuse you, so now you can remember that class variables are defined in the initialization function * maybe)

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

"Array variable" that comes out immediately

Now, the variable that comes out immediately is an array. Arrays are defined in python using a class called list. Here, variables are defined using the list () class to create 64 arrays of 8x8, which is the board of Othello. When converting the board of Othello into variables, a two-dimensional array may be used, but I think that it is difficult for beginners to understand the two-dimensional array, so I decided to use an ordinary array.

If you want to fill the value of the list variable with the initial value, you can add it with the append () function, but you can also initialize it at the same time as the variable definition by writing as follows. (Since it is a little long, it is omitted)

ot_bit = [ '・' , '・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' , \
'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' , \
'○' , '●' , '・' ,'・' ,'・' ,'・' ,'・' ,'・' ]

Arrays other than lists

It's a dialect unique to Python, or there are three ways to represent an array with variables. Rewritable variables are also called ** mutable **, and non-rewritable variables are also called ** immutable **, but they are described as "rewritable" in the table below because they are difficult to understand.

Mold class Initialization description Rewrite order Duplicate values
list list() [element,element,element,element] Yes order Yes
Tuple tuple() (element,element,element,element) Impossible order Yes
set set() {element,element,element,element} Yes Immovable Impossible

The only difference between the list type and the tuple type is whether they can be rewritten or not, and the other usages are almost the same. If it is an array that is only referenced, the access speed is faster with tuples, so it is recommended to use tuples.

"Repeated sentence with a fixed number of times" that appears immediately

The above-mentioned repeating sentence appears here. def __init __ (self): contains the variable definition and the program (logic) that initializes the variable. This time, the number of repetitions is fixed at 64, so while repeating 64 times, if the variable i that stores the number of repetitions to put the frame in the initial state is 27 or 36, substitute ○ and i is 28. Or if it is 35, substitute ●, otherwise substitute ・. This array contains all the elements of 8x8 squares, with ○ in the part where the white frame is placed, ● in the part where the black frame is placed, and the square where nothing is placed. It is made by the rule of substituting ・ for. To add a value to an array, add a value to the ot_bit instantiated by the list class using a function called append (). Remember to use a function called append () to append a value to an array. To see the values in the array, you can refer to one cell with ot_bit [index]. You can also update the value by substituting it with a subscript such as ot_bit [index] = "●". Functions that remove parts of an array include del (), pop (), and remove (), but try to find a way to use them when you actually need them. I think you can easily search for the search keyword with python list delete etc.

General variables

ʻOt_offdef is assigned the frame of the current turn (○ or ●), and ʻot_search is assigned the frame that is not the current turn (○ or ●). ʻOt_lastposX and ʻot_lastposY are variables to remember the last place to flip.

About dictionary variables

Well, this time I would like to finish by explaining the dictionary variables. A dictionary variable is a structure for having an array of key: value. I didn't have to make it a dictionary variable this time, but I used a dictionary variable for studying.

In Othello, if you place a piece at a specific (X, Y) coordinate, you may be able to place your hand in eight directions.

        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

This table is a numerical value of how it moves in eight directions from the place where the top is placed. In the previous chapter, I wrote that "the program should be put into a form that can be expressed in words", but it is important to put the words "how to move when the frame is placed". See the figure below. If you put one frame, humans can understand that "Oh, the left side can be turned over", but the program can only be viewed in eight directions in order. If it is diagonally to the upper left from the place you placed it, look for a place that is -1 in the vertical direction and -1 in the horizontal direction.

スクリーンショット 2020-05-26 0.16.00.png

In this figure, X = 6 and Y = 5 are set, so you can search for them as follows.

  1. With X = 5 and Y = 4, look for a piece that can be turned over.
  2. With X = 6 and Y = 4, look for a piece that can be turned over.
  3. With X = 7 and Y = 4, look for a piece that can be turned over.
  4. With X = 7 and Y = 5, look for a piece that can be turned over.
  5. With X = 7 and Y = 6, look for a piece that can be turned over.
  6. With X = 6 and Y = 6, look for a piece that can be turned over.
  7. With X = 5 and Y = 6, look for a piece that can be turned over.
  8. At X = 5 and Y = 5, look for a piece that can be turned over.

A dictionary variable called ʻot_direction` is a table of where to look from the coordinates you placed. ul = UpLeft is defined as (-1, -1), which is a tuple type to look in either the vertical direction or the horizontal direction, respectively.

The above is the explanation of variables in the Othello class. Dictionary variables may be a little confusing, but I'll explain how to use them in a program later, so it's okay if you just remember the array key: value here.

This is a homework to think about before going to the next time. How should the program express "whether there is a frame that can be turned over"? For example, in the case of a black turn, I placed pieces at X = 6 and Y = 5. How do you think about whether you can turn it over programmatically? There are many ways to do it, so if you can do it, that's the correct answer. Think for a moment!

Next time, I would like to explain the functions of the Othello class.

c u

<< I made Othello to teach Python3 to children (3) I made Othello to teach Python3 to children (5) >>

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 a password generator to teach Python3 to children (bonus) * Completely remade
I made blackjack with python!
I made a Python module to translate comment outs
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 tried to touch Python (installation)
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
I tried to touch Python (basic syntax)
After studying Python3, I made a Slackbot
I made a roguelike game with Python
What I was addicted to Python autorun
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)
I made a Docker container to use JUMAN ++, KNP, python (for pyKNP).
[Python] I made a decorator that doesn't seem to have any use.
I made a tool to automatically browse multiple sites with Selenium (Python)
I made a web application in Python that converts Markdown to HTML
I tried to discriminate a 6-digit number with a number discrimination application made with python