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.
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.
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.
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
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 = [ '・' , '・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' , \
'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' ,'・' , \
'○' , '●' , '・' ,'・' ,'・' ,'・' ,'・' ,'・' ]
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.
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.
ʻ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.
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.
In this figure, X = 6 and Y = 5 are set, so you can search for them as follows.
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