[PYTHON] I tried to move the ball

Finished product

 ストーカーボール.gif

Motivation

By learning python programming through the lectures so far, I wanted to make something that works easily, so I made this.

procedure

Show Window

qiita.rb



import tkinter as tk
import math

class Application(tk.Frame):
    def __init__(self,master):
        super().__init__(master)
        self.pack()

        self.width=self.height=500
        master.geometry(str(self.width)+"x"+str(self.height))
        master.title("Chasing game")


def main():
    win = tk.Tk()
    app = Application(master = win)
    app.mainloop()


if __name__ == "__main__":

    main()

About another ball

qiita.rb



def enemyVec(self,player,enemy,speed):#Enemy movement(x,y)Returns a vector of
    rad=np.arctan((player.y-enemy.y)/(player.x-enemy.x))#Orientation (calculation of angle)
    if player.x-enemy.x >= 0:
        vx=np.cos(?)*speed
        vy=np.sin(?)*speed
    else:
        vx=np.cos(?)*(-1*speed)
        vy=np.sin(?)*(-1*speed)
    return [vx,vy]

I'm passing a player object and an enemy object as arguments. This is because each center coordinate is used in the calculation. Now, I think the calculation of the orientation of these two objects gets a little confusing. In other words, it is the calculation of the angle between two points. Since we know the coordinates of the two points, we can find the x and y components of the vector. (Example) In the case of A (x1, y1), B (x2, y2) AB→=x2−x1y2−y1

And the angle θ between the x-axis and the vector can be expressed using the inverse function of tan below. θ=tan−1(yx) Since the range of tanθ is -π / 2 to π / 2, the case is divided by the positive or negative of the difference between the x coordinate of player and enemy, and the direction is changed by multiplying speed by -1.

Source code

qiita.rb


import tkinter as tk
import math

class Circle():
    def __init__(self,canvas,x,y,r,color,tag=None):
        self.canvas = canvas
        self.x = x #X coordinate of the center of the circle
        self.y = y #Y coordinate of the center of the circle
        self.r = r #Radius of circle
        self.color = color
        self.tag = tag

    def createCircle(self):
        self.canvas.create_oval(self.x-self.r,self.y-self.r,self.x+self.r,self.y+self.r,fill=self.color,tag=self.tag)

class Application(tk.Frame):
    def __init__(self,master):
        super().__init__(master)
        self.pack()

        self.width=self.height=500
        master.geometry(str(self.width)+"x"+str(self.height))
        master.title("Chasing game")

        self.canvas = tk.Canvas(master,width=self.width,height=self.height,bg="black")
        self.canvas.pack()

        self.player = Circle(self.canvas,250,250,30,"red","player") #Instance player generation
        self.enemy = Circle(self.canvas,0,0,30,"blue","enemy") #Generating an instance enemy

        self.canvas.bind("<Motion>",self.mouseEvent)
        self.master.after(50,self.update)

    def update(self):
        if self.judgeflag(self.player,self.enemy):
            eV = self.enemyVec(self.player,self.enemy,10)
            self.enemy.x += eV[0]
            self.enemy.y += eV[1]
            self.canvas.delete("player")
            self.canvas.delete("enemy")
            self.player.createCircle()
            self.enemy.createCircle()

        self.master.after(50,self.update)

    def enemyVec(self,player,enemy,speed): #Enemy movement(x,y)Returns a vector of
        rad=math.atan((player.y-enemy.y)/(player.x-enemy.x)) #Orientation (calculation of angle)
        if player.x-enemy.x >= 0:
            vx=math.cos(rad)*speed
            vy=math.sin(rad)*speed
        else:
            vx=math.cos(rad)*(-1*speed)
            vy=math.sin(rad)*(-1*speed)
        return [vx,vy]

    def judgeflag(self,player,enemy): #collision detection
        if math.sqrt((player.x-enemy.x)**2+(player.y-enemy.y)**2) > player.r+enemy.r: return True
        else: return False

    def mouseEvent(self,event):
        self.player.x = event.x
        self.player.y = event.y

def main():
    win = tk.Tk()
    app = Application(master=win)
    app.mainloop()

if __name__ == "__main__":
    main()

Impressions

Since it did not work with the original source code, I made a trial and error by referring to Python standard library. Almost the source code is based on [Python] Tkinter's 70-line GUI app "Chasing game". I was able to deepen my understanding of this program during this production. I still feel that it takes a lot of time and experience to make things from scratch myself, so I will study during the summer vacation. I can experience the sense of accomplishment that I did not feel when I was copying the textbook, and I would like to continue learning by turning the sense of accomplishment into motivation.

Future goals

I want to make my own site someday. Recently, I was thinking of going on a trip and opening the site to make a reservation, but every time I made a mistake, I returned to the beginning, so I found it difficult to use. So, through future learning, I would like to make something from scratch that many people can use.

References

-The easiest python introductory class Fumitaka Osawa [Author]

-[Python] GUI app "Chasing game" made with 70 lines by Tkinter

-Python standard library

Recommended Posts

I tried to move the ball
I tried to estimate the interval.
I tried to recognize the wake word
I tried to summarize the graphical modeling.
I tried to estimate the pi stochastically
I tried to debug.
I tried to paste
I tried to move GAN (mnist) with keras
I tried to optimize while drying the laundry
I tried to save the data with discord
I tried to touch the API of ebay
I tried to correct the keystone of the image
Qiita Job I tried to analyze the job offer
LeetCode I tried to summarize the simple ones
I tried to classify dragon ball by adaline
I tried to implement the traveling salesman problem
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
I tried to learn PredNet
I tried to organize SVM.
I tried to implement PCANet
I tried the changefinder library!
I tried to reintroduce Linux
I tried to introduce Pylint
I tried to summarize SparseMatrix
I tried to touch jupyter
I tried to learn the sin function with chainer
I tried to move machine learning (ObjectDetection) with TouchDesigner
I tried to move Faster R-CNN quickly with pytorch
I tried to detect the iris from the camera image
I tried to summarize the basic form of GPLVM
I tried to touch the CSV file with Python
I tried to predict the J-League match (data analysis)
I tried to solve the soma cube with python
I tried to approximate the sin function using chainer
I tried to put pytest into the actual battle
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to visualize the spacha information of VTuber
I tried to erase the negative part of Meros
I tried to simulate the dollar cost averaging method
I tried to redo the non-negative matrix factorization (NMF)
I tried to identify the language using CNN + Melspectogram
I tried to notify the honeypot report on LINE
I tried to complement the knowledge graph using OpenKE
I tried to classify the voices of voice actors
I tried to compress the image using machine learning
I tried to summarize the string operations of Python
I tried to find the entropy of the image with python
I tried to find out the outline about Big Gorilla
I tried porting the code written for TensorFlow to Theano
[Horse Racing] I tried to quantify the strength of racehorses
I tried to simulate how the infection spreads with Python
I tried to implement Deep VQE
I tried to analyze the whole novel "Weathering with You" ☔️
[First COTOHA API] I tried to summarize the old story
I tried to get the location information of Odakyu Bus
I tried the TensorFlow tutorial 1st
I tried to create Quip API
I tried to find the average of the sequence with TensorFlow
I tried the Naro novel API 2
I tried to touch Python (installation)