[PYTHON] Create an application by classifying with Pygame

What is python

A versatile language that can do almost anything except system software (embedded software). [GUI](https://ja.wikipedia.org/wiki/%E3%82%B0%E3%83%A9%E3%83%95%E3%82%A3%E3%82%AB%E3%83 % AB% E3% 83% A6% E3% 83% BC% E3% 82% B6% E3% 82% A4% E3% 83% B3% E3% 82% BF% E3% 83% 95% E3% 82% A7 % E3% 83% BC% E3% 82% B9) applications and [AI](https://ja.wikipedia.org/wiki/%E4%BA%BA%E5%B7%A5%E7%9F%A5 % E8% 83% BD) is said to be very good at it.

What is classification?

How to make a template called class and make a real thing called an instance. It is implemented in many languages such as C ++, C #, Java, and Python, and you can create applications that are easy to see. For more information, see Object Oriented (https://ja.wikipedia.org/wiki/%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF% Please read E3% 83% 88% E6% 8C% 87% E5% 90% 91).

What is pygame

A collection of cross-platform Python modules designed for making video games, including a library for working with computer graphics and audio in Python. Pygame is built on top of the SDL library and is designed to allow real-time computer games to be developed without the use of low-level mechanisms like C. This is based on the assumption that most of the computationally intensive functions (mainly graphics processing) can be separated from the game logic itself, which allows high-level languages like Python to be used for game development. There is. Please read PYGAME for more information.

Sample script

skeleton.pyw


import pygame,main,apng,OpenGL as lse,OpenGL.GL as lily 
from pygame.locals import * 

class CVak:
    #Underscore*Private at 2
    #__RenderName = None
    #__Scene = None
    #__FULLNESS = (22222,)Constant declaration(Uppercase tuple)Access is this.__FULLNESS[0]

    #constructor(Class initialization)
    def __init__(this):#This part is generally called self or this
        #Render target creation
        #exp/this(self).__RenderName = main.CvRender("Data\\name.png ",posx,posy)
        #this.__Scene = CvScene()
        pass#No need for anonymous functions like C that do nothing<-The interpreter will skip it.

    #Initialization process(every time)
    def init(this):
        return

    #Update process when entering a key
    def UpdDwKey(this,key):
        #if key == K_Up:
        return

    #Update processing at the time of key output
    def UpdUpKey(this,key):
        return

    #Get mouse coordinates
    def MousePos(this,x,y):
        return

    #Update process
    def Update(this):
        return

    #Drawing process
    def Draw(this):
        #exp/this.__RenderName.Draw()
        return

    #Music playback process pygame.mixer system
    def Music(this):
        return

    #Game loop
    def GameLoop(this):
        if(False):#Does not activate
            this.init()
        this.Update()
        #Color output on screen
        main.Main.Drawwnd(main.Clist.Red.get())
        this.Draw()
        this.Music()
        pass

    #End processing
    def finGame(this):
        return

main.pyw


import pygame ,sys,OpenGL as GL
from OpenGL.GL import *
from OpenGL.GLU import *
import skeleton as sk

class Main:
    #Static variables
    #__SCRFLG = ((pygame.OPENGL|pygame.DOUBLEBUF),)When you need 3D
    __SCRFLG = (0,)#2D
    __ScreenHeight:int = 810
    __ScreenWidth:int = 931
    __GameFPS:int = 60
    __GameName:str = "Vgame"
    pygame.init()
    __wnd = pygame.display.set_mode((__ScreenWidth,__ScreenHeight),__SCRFLG[0]) 
    pygame.display.set_caption(__GameName)
    pygame.time.Clock()
    __wnd.fill((0,0,255))
    __game = None
        
    def quit():
        Main.__game.finGame()
        pygame.quit()
        sys.exit(None)

    def Eventloop(event):
        if(event.type == pygame.QUIT):
            Main.quit()
        if(event.type == pygame.KEYDOWN):
            if(event.key == pygame.K_ESCAPE):
                Main.quit()
            else:
                Main.__game.UpdDwKey(event.key)
                return
        if(event.type == pygame.KEYUP):
            Main.__game.UpdUpKey(event.key)
        if(event.type == pygame.MOUSEMOTION):
            (x, y) = event.pos
            Main.__game.MousePos(x,y)
        else:
            return

    def GameMain():
        Main.__game = sk.CVak()
        while(True):
            for event in pygame.event.get():
                Main.Eventloop(event)
            Main.__game.GameLoop()
            pygame.display.update()
        return

    def Drawwnd(color):
        Main.__wnd.fill(color)

    def getWndGet():
        return Main.__wnd
        
#main function
def main():
    Main.GameMain()

class CvRender:
    x:int
    y:int
    path:str
    surf:int

    def __init__(this,path,x,y):
        this.path = path
        this.x = x
        this.y = y
        this.surf = pygame.image.load(this.path).convert_alpha()
    
    def getSizeGet(this):
        return (-this.surf.get_width(),-this.surf.get_height())

    def Draw(this):
        Main.getWndGet().blit(this.surf,(this.x,this.y))
    
    def DrawMiddle(this):
        Main.getWndGet().blit(this.surf,(this.x-this.surf.get_width()/2
                                         ,this.y-this.surf.get_height()/2))

    def CutDraw(this,startx,starty,cutx,cuty):
        Main.getWndGet().blit(this.surf,(this.x,this.y),(startx,starty,cutx,cuty))
    
    def Rev(this,bx,by):
        this.surf = pygame.transform.flip(this.surf,bx,by)

    def Scale(this,sx,sy):
        this.surf = pygame.transform.scale(this.surf,(sx,sy))

    def Rot(this,angle):
        this.surf = pygame.transform.rotate(this.surf.convert(),angle)

class HitsFlg():

    #Put width in posz
    def tri(pos1,pos2,h2):
        if(pos1.posx + pos1.posz <= pos2.posx 
           or pos1.posx >= pos2.posx + pos2.posz):
            return False
        elif(pos2.posy + h2 >= pos1.posy 
             or pos1.posy <= pos2.posy + h2):
            return False
        else:
            return True

    def yen(pos0,pos1):
        posx = pos1.x - pos0.x
        posy = pos1.y - pos0.y
        rad = pos1.z + pos0.z
        if(pow(posx,2) + pow(posy,2) 
           <= pow(rad,2)):
            return True
        else:
            return False
        pass

class CvPos():
    x:int
    y:int
    z:int
    def __init__(this,posx,posy,Btwn):
        this.x = posx
        this.y = posy
        this.z = Btwn

class Cv3DPos():
    pos:CvPos
    size:CvPos

    def __init__(this,posx:int,posy:int,posz:int,sizex = 0,sizey = 0):
        this.pos = (posx,posy,posz)
        this.size = (sizex,sizey,0)
        return 

    def location_in_view(this,adj_x, adj_y):
        """Coordinate calculation on 2D from 3D coordinates"""
        x2 = int((this.pos.x + adj_x * this.pos.y) / (this.pos.z/10 + 1)) + 200 - int(this.size.x * 0.5 / (this.pos.z/10 + 1))
        y2 = int((this.pos.y + adj_y * this.pos.z) / (this.pos.z/10 + 1)) + 150 - int(this.size.y * 0.5 / (this.pos.z/10 + 1)) 
        return (x2, y2)

    def size_in_view(this):
        """Size calculation on 2D from 3D coordinates"""
        s_x2 = int(this.size.x / (this.pos.z/10 + 1))
        s_y2 = int(this.size.y / (this.pos.z/10 + 1))
        return (s_x2, s_y2)

#Color definition
class CvCollor():
    __red:int
    __green:int
    __blue:int
    def __init__(this,r,g,b):
        this.__red = r
        this.__green = g
        this.__blue = b
    def get(this):
        return(this.__red,this.__green,this.__blue) 

#Color list(Expand your favorite color)
class Clist():
    #color= CvCollor(deep red,Green,Blue)
    White = CvCollor(255, 255, 255)
    Black = CvCollor(0, 0, 0)
    Green = CvCollor(0, 255, 0)
    Blue = CvCollor(0, 0, 255)
    Red = CvCollor(255, 0, 0) 
    Yellow = CvCollor(255, 255, 0)
    Purple = CvCollor(255, 0, 255)
    Skyblue = CvCollor(0, 255, 255)
    Orange = CvCollor(255, 180, 105)
    Blown = CvCollor(165, 42, 42)
    Pink = CvCollor(255, 0, 165)
    Silver = CvCollor(192, 192, 192)
    Lime = CvCollor(50, 205, 50)
    Virid = CvCollor(0, 137, 107)
    Coblue = CvCollor(0, 71, 171)
    Dblown = CvCollor(81, 31, 9)
    Greeny = CvCollor(17, 69, 20)

class Cvmoveflg():
    up:bool
    down:bool
    left:bool
    right:bool
    def __init__(this,upflg,dwflg,ltflg,rtflg):
        this.up = upflg
        this.down = dwflg
        this.left = ltflg
        this.right = rtflg

class CvFont():
    font:int
    collor:CvCollor
    def __init__(this,name,size,collor):
        this.font = pygame.font.Font(name,size)
        this.collor = collor

    def UpdColor(this,collor):
        this.collor = collor

    def show(this,string,sd,x,y):
        Main.getWndGet().blit(this.font.render(string,sd,this.collor.get()),(x,y))

    def bcshow(this,string,sd,bc,x,y):
        Main.getWndGet().blit(this.font.render(string,sd,this.collor.get(),bc.get()),(x,y))

    def Font(this,collor):
        this.collor = collor
        
if __name__ == "__main__":
    main()


If you copy this whole

You should see a red screen with the title "vgame" with x = 931 and y = 810. If you create it from now on, you can easily create applications and games with music. We recommend that beginners of the program copy and paste. Start the program now. Once you have a script to create your application, read on.

A quick way to create an application

Open cmd.exe

[cmd.exe path]>> cd [pip path]
[pip path]>> pip install pyinstaller

Hit pyinstaller etc. are famous First of all, copy pyinstaller.exe to the path of the target application Open cmd.exe

[cmd.exe path]>> cd [The path of the desired application(Below G)]

And hit

[G]>> pyinstaller [main.Renamed from pyw].pyw [skeleton.Renamed from pyw].pyw --onefile --noconsole (--exclude pandas --exclude numpy)

Hit Then, I think that [renamed from main.pyw] .spec is created, so add "pygame" to the excludes item of a.

a.datas += Tree("[Python path]/Lib/site-packages/pygame/", prefix= "pygame")
a.datas += Tree("[Python path]/lib/xml/", prefix= "xml")

After deleting the __pycache__ and build and dist folders, return to cmd.exe

[G]>> pyinstaller [main.Renamed from pyw].spec [skeleton.Renamed from pyw].spec

If you type, the exe under dist will start successfully if the external data is not read. If it was read, it will succeed if it is brought over dist.

Finally

I want to use PyOpenGL. Still, I want to write a lot of articles.

Recommended Posts

Create an application by classifying with Pygame
Create games with Pygame
Create an environment with virtualenv
Create an API with Django
Create an Excel file with Python3
Create an age group with pandas
Create an image processing viewer with PySimpleGUI
Quickly create an excel file with Python #python
Create an update screen with Django Updateview
Create an application using the Spotify API
[Python] Quickly create an API with Flask
Create an add-in-enabled Excel instance with xlwings
Create an English word app with python
Create an upgradeable msi file with cx_Freeze
Create an app that guesses students with python
Create an academic society program with combinatorial optimization
Create an image composition app with Flask + Pillow
Create a game UI from scratch with pygame2!
Create an image with characters in python (Japanese)
Create a one-file hello world application with django
Create a Python console application easily with Click
Create an API server quickly with Python + Falcon
Create an application that inputs, displays, and deletes forms by using an array as a DB with Python / Flask.
You can create an interactive web application with Python alone [Strength finder dashboard creation]
Create an animated GIF local server with Python + Flask
Procedure for creating an application with Django with Pycharm ~ Preparation ~
Create an idol-like tweet with Keras LSTM (sentence generation)
An easy way to create an import module with jupyter
Create an app that guesses students with python-GUI version
Create a random number with an arbitrary probability density
Create an OpenAI Gym environment with bash on Windows 10
I tried to make an OCR application with PySimpleGUI
Create an environment for test automation with AirtestIDE (Tips)
Make an application using tkinter an executable file with cx_freeze
Create filter with scipy
Create a 2D array by adding a row to the end of an empty array with numpy
Create a web application that recognizes numbers with a neural network
How to convert an array to a dictionary with Python [Application]
Create an environment for "Deep Learning from scratch" with Docker
Create an LCD (16x2) game with Raspberry Pi and Python
Minimum Makefile and buildout.cfg to create an environment with buildout
Create an example game-like stage with just the Blender 2.80 script
Let's create an app that authenticates with OIDC with Azure AD
I'm trying to create an authentication / authorization process with Django
Create an authentication feature with django-allauth and CustomUser in Django
Create a Todo app with Django ① Build an environment with Docker
[Python Kivy] How to create an exe file with pyinstaller
I tried to create an article in Wiki.js with SQLAlchemy
Create an application that just searches using the Google Custom Search API with Python 3.3.1 in Bottle