I made Othello to teach Python3 to children (5)

Let's explain the Othello class Part 2

Let's talk about molds

You have a blood type, right? Whether it is true or not, A-type, B-type, O-type, AB-type, etc., the type has its own characteristics, like "A-type that is meticulous" and "B-type that is selfish". In programming, types are used to make important divisions like blood types.

I've talked a lot about ** variables ** so far, but I haven't dared to mention types. I explained that arrays are a class called list (), and dictionary variables are also a class called dict (). The data type in the program, like the blood type, represents the nature of the data.

Data type name Data type Description
String str "letter"Or'letter'
integer int +-Numerical value
Floating point float +-Floating point
Imaginary number complex +-Real part+-Imaginary number部j
Authenticity bool True or False
Date Time datetime Date and time
List (array) list Array regardless of data type
Tuple (reference sequence) tuple Array regardless of data type
Set (unique array) set Block array with unique and out-of-order data
Dictionary (keymap array) dict Key vs. data array

In Python, when using variables, the types are assigned without any special awareness. This is called dynamic typing. For example, if you write ʻage = 12`, Python will make the type int (). To find out the assigned type, you can do type (age) to find out the type assigned to the variable age. As I wrote last time, all types are classes that include the functions required to handle the data type. If it is assigned to an unintended type, you can explicitly specify it with float () etc. or convert the type.

Othello game source explanation (2) Othello class functions

Keyboard input

First is the function that performs keyboard input. Displays the string passed as an argument and waits for keyboard input. If you hit the enter key blank or enter a value other than 1 to 8, you will return to keyboard input again. Once the correct number is entered, int () converts it back to an ** integer **. Important values for this Othello class are numbers 1-8 of X and Y. Even if it becomes a graphical Othello and the location is clicked with the mouse, it can be internally converted to the X and Y coordinates of 1 to 8 so that the functions of the current class can be used as they are.

    #input
    def ot_inputXY(self,otstr):
        while True:
            myXY = input(otstr)
            if myXY == "":
                continue
            if '1' <= myXY <= '8' :
                return int(myXY)

Functions governing "Your Turn To Kill" (strings and ternary operators)

The function ʻot_yourturn () is a function that only displays" It's the hand of ●! "Or which player's turn. What is displayed is a character string enclosed in "~", but ** "character string" ** is the character string class str ()` as mentioned above, so even a character string just written as "aiueo" is str. The functions contained in the () class can be used as they are.

The {} and format () described here when using the string type are very common expressions, so remember them here. {} Is called ** replacement field ** and so on. str ("Aka {} Tana ". format (" sa ") is a convenient description that replaces {} with the data specified by the format () function. In Python 3.6 and later, the f character. You can now put variables directly into the replacement field as a column operation, improving readability.

    name = input("Please enter your name=")
    print("A brave man who came often{}Yo! !! I've been waiting for a hero to destroy the Demon King!".format(name))
    # Python3.After 6 it is convenient to write as follows!
    print(f"A brave man who came often{name}Yo! !! I've been waiting for a hero to destroy the Demon King!")

In ʻot_yourturn () `in the actual Othello class, ● or ○ is displayed because the variable ot_offdef that stores the current hand is specified in the replacement field.

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

The ʻot_changeturn () `function is a function that switches the attacker's turn.

    #It's your turn
    def ot_changeturn(self):
        #Store the attacker's piece
        self.ot_offdef = '●' if self.ot_offdef == '○' else '○'
        #Stores the opposite piece to the attacker
        self.ot_search = '●' if self.ot_offdef == '○' else '○'

Programs have a ternary operator. It's almost like writing an IF statement in an Excel macro, but the logic above and the logic below do exactly the same thing. By writing value when the condition is met if condition else value when the condition is not met, the if conditional statement can be concisely stored in one line. The ternary operator has the effect of refreshing the program depending on how it is written, but if you use it forcibly, it will be a very unreadable source, so it is recommended to use it with caution. If you find it difficult to understand, you can replace it with the following source.

    #It's your turn
    def ot_changeturn(self):
        #Store the attacker's piece
        if self.ot_offdef == '○':
            self.ot_offdef = '●'
        else:
            self.ot_offdef = '○'
        #Stores the opposite piece to the attacker
        if self.ot_offdef == '○':
            self.ot_search = '●'
        else:
            self.ot_search = '○'

A function that considers the next behavior of an Othello game

The ʻot_checkendofgame () `function is a program that considers whether the Othello game will end. Please refer to (2) of this series of articles for the operation.

What we are doing in this is as follows.

  1. Use the ʻot_canplacemypeace () `function to see if there is a place to put the attacker's piece.
  2. If the attacker's piece cannot be placed ʻot_changeturn () `to switch the attacker's piece to the opponent's turn
  3. Use the ʻot_canplacemypeace () `function to see if there is a place to put the attacker's piece.
  4. If it is determined that there is no place to put both, compare the numbers of ● and ○ to determine which one won or draw, display the result and return 1 to tell that the game is over.
  5. If there is no place to put only the attacker in 1. above, the message "It will change to the opponent's turn" is displayed and -1 is returned to notify that.
  6. If the attacker decides that the piece can be placed as it is, it returns 0 and notifies that fact.

In this function, count (), which is called myot.ot_bit.count ('●'), is a function that returns the number of data contained in the array of the list () class.

    #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

A function that finds all the places that can be turned over

The previous ʻot_checkendofgame () determined if the game was over, if there was a place to put your hand, or if not, if there was a place to put your opponent's hand. The ʻot_canplacemypeace () function thinks "Is there a place to put my hand?"

   #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

Here's what we're doing:

  1. On the 8x8 board, the places where the frames are already placed will be skipped more and more.
  2. If there is a place where the frame is not placed, convert the position from 0 to 63 to the X coordinate and the Y coordinate. The X coordinate is 1 relative X coordinate, and the value divided by 8 plus 1 is the Y coordinate.
  3. Check in all directions (8 directions) whether you can place your hand at the converted X and Y coordinate positions (is there a place where you can turn the opponent's frame over?). In the part of for d in self.ot_direction:, the key string indicating the direction stored in the dictionary is stored in the variable d, which is repeated for the number of times of the dictionary variable.
  4. If a place to put the frame is found, 0 is returned to notify that fact.
  5. If there is no place to put the frame, return -1 to notify that.

Place a frame at the specified X and Y coordinates

As I said last time, if you put a piece in the specified place, you have to judge whether it is a place where you can put it, and if you can put it, you have to turn over the opponent's piece. And if the place where you put it is a place where you should not put it in the first place, you have to display that fact.

    #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

This function is called when you try to put a frame in a predetermined place. At the specified location, X and Y are the coordinates specified by the values 1 to 8, respectively. Now let's explain the program of this function.

  1. Initialize ʻot_change` with False as a flag variable for whether or not a frame has been placed. This will be True if a frame can be placed.
  2. Repeat for a few minutes (that is, 8 directions) of the array of ʻot_direction. The variable d contains the key value of ʻot_direction.
  3. Call the ʻot_next_onepeace () `function to see if the current direction can be flipped, and if so, how far it can be flipped. A return value of 1 from the function indicates that this direction is a flipping direction.
  4. Call the ʻot_peace () function with your hand in the third argument to place your frame at the specified coordinates. The ʻot_peace () function is also a function that returns one frame at the specified coordinates if the third argument is omitted. If the third argument is specified, the frame at the specified coordinates will be replaced with the specified character.
  5. Call the ʻot_changepeace () `function to flip it to where it can be flipped.
  6. If a frame is placed, set the ʻot_change` flag to True. If you cannot flip all eight directions, it remains False.
  7. Check if the ʻot_change` flag is False when exiting the iteration. If it is False, it means that you have specified coordinates that cannot be placed in the first place, so a message indicating that it cannot be placed in that location is displayed and the message returns.
  8. If the ʻot_change flag is True when exiting the iteration, the flipping process has completed the rewriting of the board data ʻot_bit, so call the ʻot_display ()function to redisplay the board. Then call the ʻot_changeturn ()function to change the attacker's turn.

Next time, the explanation of the program will be the last!

Next time, I will explain the ʻot_next_onepeace () function and the ʻot_changepeace () function, which may be the most complicated. These two functions are called recursive functions, which are the functions that you call yourself, so I would like to explain about them.

See you again! !!

c u

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

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
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
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 tried to discriminate a 6-digit number with a number discrimination application made with python
Environment maintenance made with Docker (I want to post-process GrADS in Python
I made a script in python to convert .md files to Scrapbox format
I made a program to check the size of a file in Python