Use pygame to make the game in your heart ~ can it be included in your favorites

Keywords: Python Game Development pygame

Use pygame to make the game in your heart ~ can it be included in your favorites

Chapter 1 basic operation of pygame
Chapter 2 pygame creating character display (to be updated)

pygame basic usage operation

Does anyone like me learn programming to make games? c + + is the mainstream development of the game industry, but pygame has simple syntax and simple logic. It is suitable for 2d game development. The quality of the game has nothing to do with the programming language used to write the game. I just want to complete what I wanted to do a long time ago.

1, Death messenger

Made GIF renderings, it doesn't seem to be very good, um ~, excuse me, excuse me


In short, we should use pygame to realize the attack, movement, resurrection, static action, etc. of the death Messenger, which can be regarded as the completion of the protagonist's debut~~~~
What about the enemy? I'll get ps and change the color

2, How to display windows with pygame

pygame official documentation
The most troublesome thing is that I can't understand the official documents in English. I translated them together with the code

Libraries used

import pygame
from sys import exit
from pygame.locals import *

1.pygame is the main library.
2.pygame.locals includes some definitions of pygame, but we do not intend to use this library for the sake of code understanding.
3. The exit program will use the exit function of sys module or exit directly.

Display window

pygame only needs a few sentences of code to display the window and listen to events.
The code is as follows:

import pygame
import sys
pygame.display.init()
screen = pygame.display.set_mode([520, 520])
pygame.display.set_caption("Death messenger")
while True:
    screen.fill(pygame.Color(255,255,255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    pygame.display.update()

Here we will use pygame's display method, emmm and display function. The main function must be to display the window. I don't need to say more.

display

  1. To use display, you need to initialize display, that is, pygame.display.init(),
  2. To display a window, you must first create the window object screen = pygame.display.set_mode([520, 520]). Remember that the parameters passed in are arrays and the returned are window objects. All subsequent operations are carried out around screen.
  3. pygame.display.set_caption("death messenger") is used to set the window name

The implementation principle of pygame game is to create pictures and move pictures through the processing of mouse and keyboard events. This process certainly needs to constantly refresh the screen, that is, while True loop

  1. For the set screen, fill it with white. Screen. Fill (pygame.Color (255255255)). To create a color object that can be used by pygame, you need to use pygame.Color. The parameter passed in by this class is rgb color system
  2. pygame.display.updata() is used to continuously refresh the game. It is usually written at the end.

event

You can see that all events are obtained through pygame.event.get(), including, of course, the movement of the mouse, whether the mouse button is pressed, and each key on the keyboard. If you do not handle the event, you will not be able to exit without any operability.
The obtained event is traversed through the for loop. When the type of event is exit, close the program

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

3, Upgrade code to object-oriented

The code is as follows (example):

import pygame


class PlayGame:
    def __init__(self):
        pygame.display.init()
        self.screen = pygame.display.set_mode([800, 520])
        self.clock = pygame.time.Clock()
        pygame.display.set_caption("Death messenger")
        self.map = pygame.image.load("./images/map/001map.png").convert()
        
    
    def star_game(self):
        while True:
            self.clock.tick(60)
            self.screen.blit(self.map, (0, 0))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
            pygame.display.update()


if __name__ == '__main__':
    PlayGame().star_game()

if name = = 'main': is it troublesome to write this string of code? I'll tell you quietly. Just hit main and enter. Equivalent to the population of a main program, and then just create the main class!

  1. python executes while Ture very fast. We often don't use such a fast speed, so we can create a clock object through self.clock = pygame.time.Clock(), and then call the self.clock.tick(60) code in the first sentence of the while Ture loop, which is equivalent to time.sleep(). Why not use time.sleep()~~~~

  2. Object oriented always do not understand how to do, write a few pygame games, package you thoroughly!! From here on, we need to understand the code with object-oriented thinking.

  3. self.screen.blit(self.map, (0, 0)) pastes the picture to the window

  4. Quietly paste a background so that you don't have to write the screen.fill() function
    Create a map object: self.map=pygame.image.load("./images/map/001map.png").convert()
    Display the map object in the loop: the coordinates are, of course, the position of the upper left corner of the picture
    self.screen.blit(self.map, (0, 0))

Some ideas of object-oriented

The code is as follows:

import pygame


class PlayGame:
	screen = None
    def __init__(self):
        pygame.display.init()
        PlayGame.screen = pygame.display.set_mode([800, 520])
        self.clock = pygame.time.Clock()
        pygame.display.set_caption("Death messenger")
        self.map = pygame.image.load("./images/map/001map.png").convert()
        
    
    def star_game(self):
        while True:
            self.clock.tick(60)
            PlayGame.screen.blit(self.map, (0, 0))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
            pygame.display.update()


if __name__ == '__main__':
    PlayGame().star_game()
  1. Here, the object screen of the window is converted from the instance attribute to the class attribute. Of course, the advantage is that it is easier to call. In this way, if there are many important objects such as characters in the later stage, they can be set as class attributes, which can increase the readability of the code. Of course, don't be lazy to write comments like me. The role of comments is also very important, Only when you are proficient in these basic operations and can write them like dictating the text, the notes can be omitted
  2. If you think bigger, it will always appear. The required data needs to be realized by various parameters. Why not plan ahead and put all the used data into data.py
    The main function code is as follows:
import pygame
from data import *


class PlayGame:
    def __init__(self):
        pygame.display.init()
        Screen.screen = pygame.display.set_mode([Screen.ScreenWeight, Screen.ScreenHeight])
        Screen.clock = pygame.time.Clock()
        Map.map = pygame.image.load("./images/map/001map.png").convert()
        pygame.display.set_caption("Death messenger")

    @staticmethod
    def star_game():
        while True:
            Screen.clock.tick(60)
            Screen.screen.blit(Map.map, Map.Map_pos)
            EventGet.event_list = pygame.event.get()
            EventGet.mouse = pygame.mouse.get_pos()
            for event in EventGet.event_list:
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit()
            pygame.display.update()


if __name__ == '__main__':
    PlayGame().star_game()
  1. @staticmethod converts the instance method into a class method, so that the Yellow message will not be reported
  2. pygame.mouse.get_pos() gets the position of the mouse and assigns it to EventGet.mouse in data
  3. pygame.quit() close pygame

The data.py code is as follows:

class Screen:
    ScreenWeight = 800
    ScreenHeight = 520
    clock = None
    screen = None


class Map:
    map = None
    Map_pos = (0, 0)


class EventGet:
    event_list = None
    mouse = None
  1. Save the coordinates of mouse movement, keyboard key operation and other events, and save the window object, size, picture object and position.

summary

Many ideas are about bug s encountered when writing games. Writing code is like building a house. If you think more in the early stage, you can go further. Save some public resources in the variables of py file for easy calling. Many of them are my own ideas. I can refer to them. After all, I'm just a cute new person

The code hasn't been written yet, so it won't be sent. I hope you can give me suggestions on how to play and operate the game~~~~ Persistent baldness~~~~
All picture links
Extraction code: 57mk

Posted by ingoruberg on Tue, 14 Sep 2021 19:59:06 -0700