[PYTHON] If you are a beginner in programming, why not make a "game" for the time being? The story

Introduction

I started programming, but I don't know what this is useful for. I think there are surprisingly many beginners who can't get an idea of what they can do.

Well, you know that python, for example, can be automated, machine learning, or image recognition. I know too.

But when I actually start studying, the first thing is "variables", "data types", "lists" ... So what is it? Is it delicious? ?? Isn't it? I'm stupid.

Now,

The introduction has become longer. I think the current programming education has a high hurdle. Except for smart people, learning costs are high for people like me.

That's why I think it's okay to start with something simpler.

So what are you doing?

Make a "game". However, the game is deadly easy. It's a simple game where you just play "rock-paper-scissors" with your favorite characters.

It's a rock-paper-scissors game that often appears in books for programming beginners. I will make an arrangement of this in my own way.

Even if it's just one rock-paper-scissors, I think that the rock-paper-scissors made with a lot of love and dedication is interesting as it is.

Implementation

1. First, play simple rock-paper-scissors

janken.py



import random

# janken head
print("Rock-paper-scissors YO!")
print("First Dawn! Janken whit! !!")

# define function
def janken():
    global myhand
    global mynum
    global yournum
    yournum = random.randint(1,3)
    mynum = 0
    myhand = input(":")
    if myhand == "goo":
        mynum = 1
    elif myhand == "choki":
        mynum = 2
    elif myhand == "paa":
        mynum = 3
    else:
        print("Please do it seriously!")
    
    if yournum == 1:
        yourhand = "goo"
        print(yourhand)
    elif yournum == 2:
        yourhand = "choki"
        print(yourhand)
    elif yournum == 3:
        yourhand = "paa"
        print(yourhand)
    
    i = 1
    while i ==1:
        result = (yournum - mynum) % 3
        if result == 0:
            print("Aiko!")
            janken()
        elif result == 1:
            print("I lost ~")
            break
        elif result == 2:
            print("I won!")
            break

# execute function
janken()

A game to play rock-paper-scissors with someone like Fujiwara has been completed. There are two main points in the rock-paper-scissors program, One is to express ["goo", "choki", "paa"] numerically as [1,2,3]. Then, the difference between your opponent and your own number is decided by using the congruence formula of 3. For example, if the other party is "goo" and you also give "goo", 1-1 = 0 0% 3 = 0, so Aiko. If the opponent is "goo" and you are "choki", you lose because 1-2 = -1 -1% 3 = 2. If your opponent is "goo" and you are "paa", you win because 1-3 = -2 -2% 3 = 1. And so on.

The second is to express this case well. Rock-paper-scissors is an algorithm that causes a loop only at this time. So, at this time, you need to write a process to start over (I'm calling the function again, but there may be a better way).

By the way, just playing rock-paper-scissors with a person like Fujiwara is fun as it is, and for a general study book, this is the end, but this time I would like to arrange more.

2. Get 3 in advance

Speaking of rock-paper-scissors, it's about three in advance. So, I will take three of these programs in advance.

janken.py



import random

# janken head
print("It's rock-paper-scissors with 3 pre-taken YO!")
print("First Dawn! Janken whit! !!")

count = [0,0]   # [mypoint,yourpoint]

# define function
def janken():
    global myhand
    global mynum
    global yournum
    yournum = random.randint(1,3)
    mynum = 0
    myhand = input(":")
    if myhand == "goo":
        mynum = 1
    elif myhand == "choki":
        mynum = 2
    elif myhand == "paa":
        mynum = 3
    else:
        print("Please do it seriously!")
    
    if yournum == 1:
        yourhand = "goo"
        print(yourhand)
    elif yournum == 2:
        yourhand = "choki"
        print(yourhand)
    elif yournum == 3:
        yourhand = "paa"
        print(yourhand)
    
    global count
    i = 1
    while i ==1:
        result = (yournum - mynum) % 3
        if result == 0:
            print("Aiko!")
            janken()
        elif result == 1:
            print("I lost ~")
            if count[0] < 2:
                print("I won't lose next time ~")
                count[0] += 1
                print(str(count[0]) + "Win"+ str(count[1]) + "It's a loss!")
                janken()
            elif count[0] == 2:
                print("I was killed ~")
                break
        elif result == 2:
            print("I won!")
            if count[1] < 2:
                print("The loser listens to whatever the winner says ~")
                count[1] += 1
                print(str(count[0]) + "Win"+ str(count[1]) + "It's a loss!")
                janken()
            elif count[1] == 2:
                print("Hooray! I won ~")
                break

# execute function
janken()

With this, I was able to get three in advance. Is the winning percentage about 50%? When I actually try it, I can't win unexpectedly. This time, we just create a variable called count and add 1 point for each win or loss, so it's easy to implement. Until we get 3 ahead, we call the function and loop in the same way as before.

By the way, just playing rock-paper-scissors with Secretary Fujiwara is fun as it is, and maybe just playing rock-paper-scissors with Secretary Fujiwara will pass one day. Something like this ... it's not enough.

3. Increase the number of characters

I agree. The true identity of the unsatisfactory is the lack of characters. Well, Secretary Fujiwara is also cute, but you get tired of playing rock-paper-scissors with Secretary Nakafujiwara all day long (or rather, you get tired of Secretary Fujiwara). So let's increase the number of characters.

janken.py



import random

#Count the number of wins
count = [0,0]   # [mypoint,yourpoint]

# define class and function
class Shuchiin:
    def __init__(self,name,words_list):
        self.name = name
        self.words_list = words_list
    
    def janken_head(self,words_list):
        self.words_list = words_list
        print(words_list[0])
        print(words_list[1])

    def janken(self,words_list):
        self.words_list = words_list
        global myhand
        global mynum
        global yournum
        yournum = random.randint(1,3)
        mynum = 0
        myhand = input(":")
        if myhand == "goo":
            mynum = 1
        elif myhand == "choki":
            mynum = 2
        elif myhand == "paa":
            mynum = 3
        else:
            print(words_list[2])
        
        if yournum == 1:
            yourhand = "goo"
            print(yourhand)
        elif yournum == 2:
            yourhand = "choki"
            print(yourhand)
        elif yournum == 3:
            yourhand = "paa"
            print(yourhand)
        
        global count
        i = 1
        while i ==1:
            result = (yournum - mynum) % 3
            if result == 0:
                print(words_list[3])
                self.janken(words_list)
            elif result == 1:
                if count[0] < 2:
                    print(words_list[4])
                    print(words_list[5])
                    count[0] += 1
                    print(str(count[0]) + "Win"+ str(count[1]) + "It's a loss")
                    self.janken(words_list)
                elif count[0] == 2:
                    print(words_list[6])
                    break
            elif result == 2:
                if count[1] < 2:
                    print(words_list[7])
                    print(words_list[8])
                    count[1] += 1
                    print(str(count[0]) + "Win"+ str(count[1]) + "It's a loss")
                    self.janken(words_list)
                elif count[1] == 2:
                    print(words_list[9])
                    break

# define each words_list
Kei_list = ["Is it rock-paper-scissors?","At first, goo, rock-paper-scissors, hoi","If you don't take it seriously, I'll stop","Aiko, right?","Uh","Next time ...","You're strong. But next time I won't lose","Whew","Do you still do it?","It's my win. You should start by practicing today's killing method"]
Huziwara_list = ["It's rock-paper-scissors with 3 pre-taken YO!","First Dawn! Janken whit! !!","Please do it seriously!","Aiko!","I lost ~","I won't lose next time ~","I was killed ~","I won!","The loser listens to whatever the winner says ~","Hooray! I won ~"]
Shinomiya_list = ["Oh, do you want to play rock-paper-scissors with me?  How cute. Is it okay to get three in advance?","At first, goo, rock-paper-scissors, hoi","Could you take it seriously","Aiko","Oh, I lost","I won't lose next time","Let's admit, I'm losing","Oh, I won","You should think about your will","How cute"]

# create each instance
Kei = Shuchiin("Kei",Kei_list)
Huziwara = Shuchiin("Huziwara",Huziwara_list)
Shinomiya = Shuchiin("Shinomiya",Shinomiya_list)

# execute function
player = input("Who will you play against?:")
if player == "kei":
    Kei.janken_head(Kei_list)
    Kei.janken(Kei_list)
elif player == "huziwara":
    Huziwara.janken_head(Huziwara_list)
    Huziwara.janken(Huziwara_list)
elif player == "shinomiya":
    Shinomiya.janken_head(Shinomiya_list)
    Shinomiya.janken(Shinomiya_list)
else:
    print("Let's go home today")

In addition to Secretary Fujiwara, I have called Kei-chan and Kaguya-sama (it happens that there are only women). Now you have a lot of variety. The changes are that the dialogue has been changed for each character, and the opponent player can be selected at the start.

Hmm, now you can play all day long.

in conclusion

Well, I thought about implementing a simple game, but I found that programming can express "procedures" including conditional branching and repetition.

Rock-paper-scissors can be said to be the simplest procedure that involves repeating conditional branching of victory and defeat and consecutive battles.

And I found that even one rock-paper-scissors game requires four arithmetic operations, conditional branching, functions and classes.

I think that it is the strongest to keep doing small things steadily. I am also a beginner in programming, but I would like to walk the programming path step by step.

Recommended Posts

If you are a beginner in programming, why not make a "game" for the time being? The story
Make a histogram for the time being (matplotlib)
I made a function to check if the webhook is received in Lambda for the time being
Register a task in cron for the first time
Until you run a Flask application on Google App Engine for the time being
The story around the time acquisition API in programming languages
Why do you add a main ()-if statement in Python?
I want to create a Dockerfile for the time being.
Settings for running a test each time you save a file in the editor using watchmedo (watchdog)
A decorator that notifies you via AWS-SNS if the function does not finish within the specified time
The first time a programming beginner tried simple data analysis by programming
Try using FireBase Cloud Firestore in Python for the time being
A beginner who has been programming for 2 months tried to analyze the real GDP of Japan in time series with the SARIMA model.
[Hi Py (Part 1)] I want to make something for the time being, so first set a goal.
The story when different distributions are specified for the same parameter in Optuna
If you want a singleton in python, think of the module as a singleton
If you get a Programming Error: (1146, "Table'<table name>' doesn't exist") in Django
When you make a mistake in the directory where you execute `pipenv install`
A useful note when using Python for the first time in a while
If you get a no attribute error in boto3, check the version
Until you win the silver medal (top 3%) in the competition you participated in within a month for the first time in data science!
I thought I could make a nice gitignore editor, so I tried to make something like MVP for the time being
Python Master RTA for the time being
Change the list in a for statement
MongoDB for the first time in Python
What is the reason why the basic commands are not displayed in Japanese in man?
A solution if you accidentally remove the python interpreter in / usr / local / bin /.
A programming beginner tried to find out the execution time of sorting etc.
Try adding an external module to pepper. For the time being, in requests.
Turn multiple lists with a for statement at the same time in Python
It's okay to participate for the first time! A hackathon starter kit that you want to prepare "before" participating in the hackathon!
Horse Racing Prediction: If you think that the recovery rate has exceeded 100% in machine learning (LightGBM), it's a story
Even if you are a beginner in python and have less than a year of horse racing, you could win a triple.