Python 0 basic development game: groundhog (detailed tutorial) VS code version

If you don't have any programming experience, and want to try to learn programming and development, this series of tutorials must be suitable for you, it will take you to learn the most basic Python syntax, and let you master the development skills of small games. All you need is some time and patience to try out the code and operations. The material and executable code in this article can be added to the group: 45692667, get it. This is an exchange group created by me for basic partners of 0. In the next article, I will update the groundhog version of pycharm.

@[top]

I. preparations

1 download and install python
2 download and install VS code Editor
When installing, please check add to path

3 install pygame module

  • Open the command line terminal in the top menu [terminal new temporary] of visual studio code, and then input the command python -m pip install --upgrade pip, enter and wait for completion.

  • Then enter the same command pip install pygame and wait for the installation to complete, which may take several minutes

II. Create project

<meta charset="utf-8">

  1. Create a folder mygame on the desktop, then use the menu [file open folder] in VSCode, select the mygame folder, and the EXPLORER navigation bar will appear on the left side of VSCode.
  2. In the left navigation bar, right click New File to create the file main.py.

-Paste the following code into the 'main.py' file on the right.
import pygame
import sys
pygame.display.set_mode([600,400])
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
  1. Run the code.

    • Still input the command python main.py in the [terminal new terminal] terminal, which will run our above code, and a black window will pop up.

III. optional operation

  1. When performing the above operations, the bottom right corner of VSCode will often pop up some prompts. If there is the word "Install", you can click it to install more content.
  2. You can also click the icon in the left column to open [EXTENSIONS], Search @ id:ms-python.python, click the found result, and then click the [Install] button on the right side to Install. After installation, the triangle run button will appear in the upper right corner of the main.py file. Click it to run the code, which is equivalent to entering python main.py in the terminal.

  1. pip install... The install command is too slow. For Windows users, you can download the pip.ini file from the above network disk, create the PIP folder under the [C disk user user name] folder, copy the downloaded pip.ini file, and then run pip install... The installation speed will be much faster.
  2. It's a lot of trouble for Apple users. First, execute cd ~ on the terminal to switch to the user folder, and then execute MKDIR. Pip to create the. PIP folder. It is invisible. We open visit, execute [go to folder...] from the menu, go to the ~ /. test directory, paste the downloaded pip.conf file into it, and finish.

pip.ini or pip.conf file is to download and install PIP from abroad by default instead of from home, so the speed will be much faster.

  • Among them, import is to import the external code module we want to use, pygame is of course necessary, Sys is the abbreviation of the system, because our game is to run on the system (windows or Mac OS), so we will use some commands of the system, such as the following command sys.exit().
  • Pyagme. Display. Set [mode ([600400]), where [600400] is a pair of numbers combined, called binary array, where it represents a rectangle with width of 600 and height of 400. The whole sentence is to set the size of the window to pop up, display display, set setting, mode mode mode.
  • When 1:... When it is 1, it means that 1 is correct, true and existing in the code. On the contrary, 0 means wrong, false and nonexistent. while 1:do something then something will be done, if while 0: do something then it will not be done.
  • For... Sys. Exit() is a fixed format. As long as you know that it means that when the game program is finished, the system will close the window, clean up the computer and leave no trace, and exit.

Ideas of game development

There are fixed routines in game development. Whether it's a big game like playing gophers, angry birds, watermelon ninjas, or even King glory, they generally follow the following ideas:

  1. Create a map scene. There may be some props on it.

    For example, there are several ground mouse holes, some wooden boxes that can hold pigs, and even very complex valley terrain, with many wild monsters on them.
    The elements on these maps are generally passive, that is, if you don't approach or provoke wild monsters, they won't fight each other and kill each other. Similarly, when the birds haven't been launched, the wooden box won't collapse by itself.

  2. Create at least one element that the player can control that interacts with the map scene.

    This controllable element is called the player character. The character is a hammer in the groundhog game. The character in the angry bird is actually a slingshot. The pop-up bird is actually a prop. In the king's glory game, the player's character is his hero.

  3. There must be criteria to measure the outcome.

    Player controlled characters interact with map scenes and react accordingly. There must also be a criterion, such as calculating the number of times to hit the hamster in 3 minutes, the number of green pigs killed, or the experience gained from fighting against the monsters. These rules must be clear and cannot contradict each other.
    Most of the games have win or lose, and win or lose is usually only whose score first reaches a certain critical point. It can be the change of some key props, such as the tower is destroyed in the duel game, or it can be the attribute change of the player's character, such as being killed in the duel game, or it can be just a pure point evaluation, using the leaderboard instead of winning or losing.

Technical points of game development

  1. To be able to draw in the window.

    It can be drawing geometry directly with code or loading pictures to display content.

  2. Be able to control the animation of each element (props and characters) with code.

    Animation is a group of pictures constantly changing. To be able to use code control to play and stop the animation of each element, and to quickly switch between different animations.

  3. Be able to receive user control and influence the elements in the game.

    Know when the user pressed the keyboard, when he clicked the mouse, which key he pressed, left mouse button or right mouse button? We often call these operations interactive events.

  4. It can calculate and manage the effective data generated by various elements in the game.

    If the player's character cuts down, the monster's HP is reduced by 100 points. This is the data, and it is very useful data. Without this data, the monster may never die.
    Sometimes these data should be saved so that users can still see that their level and equipment still exist the next time they open the game. Sometimes the data should be cleaned up in time. For example, when a new game starts again, the props and characters on the map should be restored as they are.

Ground mouse game

We can simplify the classic game of Groundhog as follows:

  • Maps and props: gophers at random locations
  • Interactive character: control the hammer figure and click the mouse figure to make it disappear
  • Winning or losing points: number of times to hit the hamster figure in a limited time

The core play method is simplified into a sentence: Click to randomly display the figure.

Draw a hamster

We use a blue circle to represent the hamster. How to draw a circle in the window?

Baidu [pyGame circle drawing] keyword can be used. You can find the pygame.draw.circle statement to be used. Its specific syntax can be found in the official document, Please click here for details.

We found that its syntax is:

pygame.draw.circle()
circle(surface, color, center, radius) -> Rect

This means that draw.circle() needs four parameters: surface, color, center point, radius.

Let's continue to see the description of the surface parameters:

surface (Surface) -- surface to draw on

It sounds like a canvas - you have to have a canvas before you can draw circles on it.
Click on the Surface link for further instructions:

Surface((width, height), flags=0, depth=0, masks=None) -> Surface

At the end of the sentence - "Surface means Surface((width...)" can generate a Surface. We can capture the generated Surface with the following statement:

sur=pygame.Surface((600, 400)

In this way, sur is the surface we generate.

Color and location

Return to the color parameter:

color (Color or int or tuple(int, int, int, [int])) 
-- color to draw with, 
the alpha value is optional if using a tuple (RGB[A])

It's obviously a circle of what color to draw. tuple(int, int, int, [int]) indicates that three integers int are needed to represent color. RGB refers to red red, green green green, blue blue and alpha transparency

clr=(0,0,255) #blue

For the center position, we can also use the same method. Here, Vector2 represents the binary vector and the positions of horizontal x and vertical y:

pos=pygame.vector2(300,200) #Window center

Draw circles

With all the parameters, you can start drawing circles. Run the following code:

import pygame
import sys

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos = (300,200)
rad = 100

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

    # Code executed in cycles per frame
    pygame.draw.circle(sur, clr, pos, 100# Draw circle

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()

Note that the bottom two lines of the refresh screen, in which window.blit(sur, (0, 0)) means to refresh the surface sur we have drawn into the window; pygame.display.flip() means to refresh the window.

Random appearance

Random appearance is random position. We must make sure that the pos position of each flower circle is different, and it should be a fixed position of several gopher holes. ——Don't forget we're going to play the game of Groundhog.

Suppose that there are six positions of hamster pos, namely [200200], [300200], [400200], [200300], [300300], [400300], how to randomly select one of them? That is, how to randomly take a number from 1 to 6.

We can find from Baidu [Python random number] that we need to use random module, which is a module of python, and we don't need to pip install again.
If you search [python random document], you can find Official grammar description As follows:

random.randint(a, b)
Return a random integer N such that a <= N <= b. 
Alias for randrange(a, b+1).

This means that a number between a and b can be randomly generated. Also from Chinese rookie tutorial
Learn this knowledge.

Create a new test.py file. Let's test it:

import random
a = random.randint(0, 5)
print(a)

Each run generates a different number.

Continue testing:

import random
a = random.randint(0, 6)
pos6=[[200,200],[300,200],[400,200],[200,300],[300,300],[400,300]]
print(pos6[a])

pos6[a] here represents the A in the six positions of pos6. Running this code will generate different locations each time.

After the test is successful, we copy it into the circle drawing code just now and get:

import pygame
import sys
import random

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos6 = [[200, 200], [300, 200], [400, 200], [
    200, 300], [300, 300], [400, 300]]  # !! Six positions
rad = 100

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

    # Code executed in cycles per frame
    sur.fill((0, 0, 0))  # !! Use black to cover the previous frame to refresh
    a = random.randint(0, 5)  # !! Random 0 to 5
    pygame.draw.circle(sur, clr, pos6[a], 100)  # !! Use random locations

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()

Note the addition of sur.fill... Line, which uses black (0,0,0) to clean up the content of the previous frame and avoid multiple circles.

Refresh every n frames

The above code will see the blue circle jumping around after running. It's too fast. We hope to stop after changing the position and wait for us to hammer it.

We need the circle of the picture to change randomly every n frames instead of every frame now. The idea is as follows: we set a counter, which starts with 0, and each frame adds 1 to it, that is, 0,1,2,3,4... Until it increases to more than 50, then we change the position of the circle and reset the counter to 0 at the same time.

The code is as follows:

import pygame
import sys
import random

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos6 = [[200, 200], [300, 200], [400, 200], [
    200, 300], [300, 300], [400, 300]]  # Six positions
rad = 100
tick=0 #!! Counter.

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

    # Code executed in cycles per frame
    if tick>50: #Every 50 refreshes and transforms
        sur.fill((0, 0, 0))  # Use black to cover the previous frame to refresh
        a = random.randint(0, 5)  # Random 0 to 5
        pygame.draw.circle(sur, clr, pos6[a], 100)  # Use random location
        tick=0
    else: #!! When the transformation is not refreshed
        tick=tick+1 #!! Increase counter

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()

Add interactive Click

When the user clicks on the screen, we need to know where it has clicked and whether it has clicked on the circle we drew.

Baidu search [pygame click] can find relevant resources, or Found directly in the official documentation.

The idea is that we add real-time monitoring of event.type event types, once we find a click event, we get the location coordinates. The code is as follows:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos6 = [[200, 200], [300, 200], [400, 200], [
    200, 300], [300, 300], [400, 300]]  # Six positions
rad = 100
tick = 0  # !! Counter.
pos = pos6[0]  # !! Record the position of the circle outside

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # !! If it's a mouse down event
            mpos = pygame.mouse.get_pos()  # !! Get mouse position
            print(mpos)

    # Code executed in cycles per frame
    if tick > 50:  # Every 50 refreshes and transforms
        sur.fill((0, 0, 0))  # Use black to cover the previous frame to refresh
        a = random.randint(0, 5)  # Random 0 to 5
        pos = pos6[a]  # !! Update the position of the circle of the external record
        pygame.draw.circle(sur, clr, pos, 100)  # !! Use random locations
        tick = 0  # Reset counter
    else:  # !! When the transformation is not refreshed
        tick = tick+1  # !! Increase counter

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()

Run this code, any click on the screen will print out the location of the schedule mouse click.

Distance measurement

Know the position pos of the current circle and the position mpos of the current click, so we can calculate the distance between the two points. If the distance is greater than the radius of the circle, there is no point to the hamster. If the distance is less than the radius, there is point to the hamster.

Baidu search [pygame two point distance] can find some methods to calculate the distance. Here we use the method provided by pygame official to test the following code:

import pygame
a=pygame.math.Vector2.length(pygame.math.Vector2(3,4))
print(a)

It will output 5. Here (3,4) is the difference between pos and mpos.
Take this idea into the original code and get:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos6 = [[200, 200], [300, 200], [400, 200], [
    200, 300], [300, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = pos6[0]  # Record the position of the circle outside

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(
                mpos[0]-pos[0], mpos[1]-pos[1])  # !! Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # ! calculate distance
            if len < rad:
                tick = 51  # !! Change position now

    # Code executed in cycles per frame
    if tick > 50:  # Every 50 refreshes and transforms
        sur.fill((0, 0, 0))  # Use black to cover the previous frame to refresh
        a = random.randint(0, 5)  # Random 0 to 5
        pos = pos6[a]  # Update the position of the circle of the external record
        pygame.draw.circle(sur, clr, pos, 100)  # Use random location
        tick = 0  # Reset counter
    else:  # When the transformation is not refreshed
        tick = tick+1  # add counters

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()

Here we set that if the distance length len is less than the radius rad of the circle, then set tick=51 immediately to make it greater than 50, and perform random position transformation immediately.

Up to now, running the above code can realize the random appearance of hamster (circle) and click to make it disappear, which also realizes the most basic logic function of the game. In the future, we will write more contents to make it more perfect.

Record score

It's easy to increase the number. Set a score=0, and then increase it by 1 when you hit the hamster. But how to display it on the screen?

Baidu can search [pygame display text] and then find the general method. Let's do some tests first:

import pygame

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

# display text
pygame.font.init()  # !! Initialize text
font = pygame.font.SysFont('Microsoft YaHei', 30)  # !! Set font and size
sur = font.render("Hello World!!{}".format(999), False, (255, 0, 0))  # !! Generate w text surface

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

    window.blit(sur, (200, 10))  # !! Add fractional surface
    pygame.display.flip()

In this code, you can see that pygame draws text in three steps:

  • pygame.font.init() needs to be initialized first
  • pygame.font.SysFont('microsoft YaHei ', 30) set font and font size
  • font.render("Hello World!!{}".format(999), False, (255, 0, 0)) generates a Surface
    Finally, of course, don't forget to put the surface in the window

Run the above code to get a window as follows:

We improved the code based on this experience:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos6 = [[200, 200], [300, 200], [400, 200], [
    200, 300], [300, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = pos6[0]  # Record the position of the circle outside

# Fraction
score = 0  # !! Fraction counting
pygame.font.init()  # !! Initialize text
score_font = pygame.font.SysFont('Microsoft YaHei', 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(
                mpos[0]-pos[0], mpos[1]-pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score+1  # Score increase

    # Code executed in cycles per frame
    if tick > 50:  # Every 50 refreshes and transforms
        score_sur = score_font.render(
            str(score), False, (255, 0, 0))  # !! Regenerate fractional text surface
        sur.fill((0, 0, 0))  # Use black to cover the previous frame to refresh
        a = random.randint(0, 5)  # Random 0 to 5
        pos = pos6[a]  # Update the position of the circle of the external record
        pygame.draw.circle(sur, clr, pos, 50)  # Use random location
        tick = 0  # Reset counter
    else:  # When the transformation is not refreshed
        tick = tick+1  # add counters

    # Refresh screen
    window.blit(sur, (0, 0))
    window.blit(score_sur, (200, 10))  # !! Add fractional surface
    pygame.display.flip()

Run the above code, you can click the jumping blue circle with the mouse, each time you hit it, you can get 1 point, which is displayed on the top in real time.

More about text Please refer to the official documentation.

Mouse pointer to hammer

Now the mouse is still displayed in the window, not the hammer. Let's see how to turn the mouse into a specific figure.

PyGame the mouse control module is pygame.mouse, Official documents Look here.

We can hide the mouse with pygame.mouse.set ﹣ visible (false), but then we can't see the mouse and can't operate it.

But it doesn't matter. We remember that when we click the mouse, there is an MPOs = pyGame. Mouse. Get poss() to get the current mouse position. Similarly, we can get the mouse position when the mouse moves, and then draw a red circle on this position to represent the mouse.

Test the following code:

import pygame
from pygame.locals import *

pygame.init()
window = pygame.display.set_mode([600, 400])

pygame.mouse.set_visible(False)  # Hidden mouse
sur = pygame.Surface([600, 400])
mpos = [300, 200]  # Record mouse position

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # Update mouse position

    sur.fill((0, 0, 0))  # Fill black
    pygame.draw.circle(sur, (255, 0, 0), mpos, 10)  # Draw a red circle at the mouse position
    window.blit(sur, (0, 0))
    pygame.display.flip()

Run this code, when the mouse is over the window, there will be a red dot following the mouse movement, red dot instead of the original pointer.

We put the red dot mouse code into the game and get the following code:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos6 = [[200, 200], [300, 200], [400, 200], [
    200, 300], [300, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = pos6[0]  # Record the position of the circle outside

# Fraction
score = 0  # Fraction counting
pygame.font.init()  # Initialize text
score_font = pygame.font.SysFont('Microsoft YaHei', 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

# mouse
pygame.mouse.set_visible(False)  # ! hide mouse
mpos = [300, 200]  # !! Record mouse position

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(
                mpos[0]-pos[0], mpos[1]-pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score+1  # Score increase
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # !! Update mouse position

    # Code executed in cycles per frame
    if tick > 50:  # Every 50 refreshes and transforms
        score_sur = score_font.render(
            str(score), False, (255, 0, 0))  # Regenerate fractional text surface        
        a = random.randint(0, 5)  # Random 0 to 5
        pos = pos6[a]  # Update the position of the circle of the external record        
        tick = 0  # Reset counter
    else:  # When the transformation is not refreshed
        tick = tick+1  # add counters

    # Draw mouse
    sur.fill((0, 0, 0))  # ! use black to cover the previous frame to refresh
    pygame.draw.circle(sur, clr, pos, 50)  # ! draw hamster with random position
    pygame.draw.circle(sur, (255, 0, 0), mpos, 10)  # !! Draw a red circle at the mouse position

    # Refresh screen
    window.blit(sur, (0, 0))
    window.blit(score_sur, (200, 10))  # Add fractional surface
    pygame.display.flip()

The theorists moved sur.fill and the original code for drawing the blue circle of the hamster to the bottom, and put them together with the code for drawing the red dot of the mouse, so that it is more reasonable to put the drawing content together.

Limit the time of each round

There are many ways to limit the length of each game, such as time limit 1 minute, or limit the total number of hamster jumps 100 times. Let's use the second restriction here, jump out 100 times to finish and count the scores.

Add a counter times=0, and then add 1 to it every time the random position. When times > 100, we will end the game and display the end screen to count the results.

There is no new content in the specific code, and there is not much explanation. The results are as follows:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
pos6 = [[200, 200], [300, 200], [400, 200], [
    200, 300], [300, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = pos6[0]  # Record the position of the circle outside

# Fraction
score = 0  # Fraction counting
pygame.font.init()  # Initialize text
score_font = pygame.font.SysFont('Microsoft YaHei', 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

# mouse
pygame.mouse.set_visible(False)  # ! hide mouse
mpos = [300, 200]  # !! Record mouse position

times = 0  # The number of times the gopher jumps out
times_max=10 #Maximum number of times
tick_max=15 #How many frames does the hamster jump at a time

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(
                mpos[0]-pos[0], mpos[1]-pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score+1  # Score increase
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # !! Update mouse position

        if times > times_max:
            # Display end screen
            sur.fill((0, 0, 0))
            pygame.mouse.set_visible(True) 
            sur.fill((0, 0, 0)) 
            end_font = pygame.font.SysFont('Microsoft YaHei', 80)  # !! Set font and size
            end_sur = score_font.render("Your Score is:{}/{}!".format(score,times_max), False, (255, 0, 0))  # !! Generate count surface
            window.blit(sur, (0, 0))
            window.blit(end_sur, (100, 100))  # Add fractional surface
            pygame.display.flip()
        else:
            # Code executed in cycles per frame
            if tick > tick_max:  # Every 50 refreshes and transforms
                times=times+1 #Increase count
                score_sur = score_font.render(
                    str(score), False, (255, 0, 0))  # Regenerate fractional text surface        
                a = random.randint(0, 5)  # Random 0 to 5
                pos = pos6[a]  # Update the position of the circle of the external record        
                tick = 0  # Reset counter
            else:  # When the transformation is not refreshed
                tick = tick+1  # add counters

            # Draw mouse
            sur.fill((0, 0, 0))  # ! use black to cover the previous frame to refresh
            pygame.draw.circle(sur, clr, pos, 50)  # ! draw hamster with random position
            pygame.draw.circle(sur, (255, 0, 0), mpos, 10)  # !! Draw a red circle at the mouse position

            # Refresh screen
            window.blit(sur, (0, 0))
            window.blit(score_sur, (200, 10))  # Add fractional surface
            pygame.display.flip()

Run this code, click on the blue circle with the mouse, and the blue circle will run 10 times before the end, and then display the number of hits. You can make the circle beat faster or slower by adjusting the number of tick ﹐ max, and you can adjust the times ﹐ max = 100 to make the hamster beat 100 times before it ends.

Now our game of gopher has some appearance, but it is also blue and red circles and dots. Next we will change it into a picture.

Chinese font

In the previous section, we only used English fonts. How to display Chinese fonts?

Download the files on the online disk directly and put them together in your main.py

score_font = pygame.font.SysFont('Microsoft YaHei', 30)

Revised to:

score_font = pygame.font.Font('MicrosoftYaqiHeiLight-2.ttf', 30) 

Then you can use Chinese in the render to display:

end_sur = score_font.render("Your score:{}/{}!".format(score,times_max), False, (255, 0, 0))

In addition, we can also use the Chinese font of the system, but we don't know which fonts are installed in the system. We can print all the system fonts with print (pyGame. Font. Get \\\\\\\\\\\.

Show background picture

This is our background picture dds-map.jpg:

We can use map = pyGame. Image. Load ('dds map. JPG ') to read the image into the code.
For more official instructions on the pictures, see here
Note that pygame.image.load() gets a surface. We can blit it to the window wind or blit it to the window wind.

Here is the complete code:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
posAll = [[100, 150], [300, 150], [500, 150], [
    200, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = posAll[0]  # Record the position of the circle outside

# Fraction
score = 0  # Fraction counting
pygame.font.init()  # Initialize text
score_font = pygame.font.Font('MicrosoftYaqiHeiLight-2.ttf', 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

# mouse
pygame.mouse.set_visible(False)  # ! hide mouse
mpos = [300, 200]  # !! Record mouse position

times = 0  # The number of times the gopher jumps out
times_max=10 #Maximum number of times
tick_max=30 #How many frames does the hamster jump at a time
map=pygame.image.load('dds-map.jpg')#!! Read pictures

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            dis = pygame.math.Vector2(
                mpos[0]-pos[0], mpos[1]-pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score+1  # Score increase
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # Update mouse position        

    if times >= times_max:
        # Display end screen
        sur.fill((0, 0, 0)) #!! Clear the screen with black at the end
        pygame.mouse.set_visible(True) 
        end_font = pygame.font.Font('MicrosoftYaqiHeiLight-2.ttf',48) # !! Set font and size
        end_sur = score_font.render("Your score is:{}/{}!".format(score,times_max), True, (255, 0, 0))  # !! Generate count surface
        window.blit(sur, (0, 0))
        window.blit(end_sur, (100, 100))  # Add fractional surface
    else:
        sur.blit(map, (0, 0)) #!! Add background picture
        # Code executed in cycles per frame
        if tick > tick_max:  # Every 50 refreshes and transforms
            times=times+1 #Increase count
            score_sur = score_font.render(
                "Fraction:{}/{}!".format(score,times), False, (255, 0, 0))  # Regenerate fractional text surface        
            a = random.randint(0, 4)  # Random 0 to 4
            pos = posAll[a]  # Update the position of the circle of the external record        
            tick = 0  # Reset counter
        else:  # When the transformation is not refreshed
            tick = tick+1  # add counters      

        # Draw mouse
        pygame.draw.circle(sur, clr, pos, 50)  # Use random location to draw hamster            
        pygame.draw.circle(sur, (255, 0, 0), mpos, 10)  # ! draw a red circle at the mouse position

    # Refresh screen            
    window.blit(sur, (0, 0))
    window.blit(score_sur, (200, 10))  # Add fractional surface
    pygame.display.flip() #Refresh screen

Notice that we read the image first, and then decide whether to use it in each frame. The operation is as follows:

Use dynamic pictures

The hamster and hammer have two states respectively, normal hamster and hit hamster, normal hammer and hit hammer, as shown in the figure below (the figure below cannot be used directly, please download from the network disk):

We can first load all four pictures into rat1,rat2,ham1,ham2, and then we use ratsur and hamsur to represent the real surface to be used. When the mouse is pressed, we set hamsur=ham2 to hit the picture. When the mouse click position is less than the radius of the hamster, we use ratsur=rat2 to hit the picture. Finally, we put the hamster and the hammer blit on the sur.

The modified code is as follows:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type
import time

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
posAll = [[100, 150], [300, 150], [500, 150], [
    200, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = posAll[0]  # Record the position of the circle outside

# Fraction
score = 0  # Fraction counting
pygame.font.init()  # Initialize text
score_font = pygame.font.Font('MicrosoftYaqiHeiLight-2.ttf', 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

# mouse
pygame.mouse.set_visible(False)  # ! hide mouse
mpos = [300, 200]  # !! Record mouse position

times = 0  # The number of times the gopher jumps out
times_max=10 #Maximum number of times
tick_max=30 #How many frames does the hamster jump at a time
map=pygame.image.load('dds-map.jpg')#!! Read pictures
rat1=pygame.image.load('rat1.png')#!! Read picture of hamster
rat2=pygame.image.load('rat2.png')#!! Read the picture of the smashed hamster
ham1=pygame.image.load('hammer1.png')#!! Read hammer picture
ham2=pygame.image.load('hammer2.png')#!! Read the picture of hammering

while 1:
    hamsur=ham1
    ratsur=rat1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            hamsur=ham2 #!! Using a drop hammer
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(
                mpos[0]-pos[0], mpos[1]-pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score+1  # Score increase
                ratsur=rat2 #!! Use the smashed hamster
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # Update mouse position        

    if times >= times_max:
        # Display end screen
        sur.fill((0, 0, 0)) #Clear the screen with black at the end
        pygame.mouse.set_visible(True) 
        end_font = pygame.font.Font('MicrosoftYaqiHeiLight-2.ttf',48) # !! Set font and size
        end_sur = score_font.render("Your score is:{}/{}!".format(score,times_max), True, (255, 0, 0))  # !! Generate count surface
        window.blit(sur, (0, 0))
        window.blit(end_sur, (100, 100))  # Add fractional surface
    else:
        sur.blit(map, (0, 0)) #Add background picture
        # Code executed in cycles per frame
        if tick > tick_max:  # Every 50 refreshes and transforms
            times=times+1 #Increase count
            score_sur = score_font.render(
                "Fraction:{}/{}!".format(score,times), False, (255, 0, 0))  # Regenerate fractional text surface        
            a = random.randint(0, 4)  # Random 0 to 4
            pos = posAll[a]  # Update the position of the circle of the external record        
            tick = 0  # Reset counter
        else:  # When the transformation is not refreshed
            tick = tick+1  # add counters

        sur.blit(ratsur,(pos[0]-50,pos[1]-70)) #Draw a hamster
        sur.blit(hamsur,(mpos[0]-50,mpos[1]-100)) #Draw hammers

    # Refresh screen            
    window.blit(sur, (0, 0))
    window.blit(score_sur, (200, 10))  # Add fractional surface
    pygame.display.flip() #Refresh screen
    time.sleep(0.04) #!! Hold the picture for a while

Note the import time and time.sleep(0.04) here, which is to allow each frame to stay for a little time, 0.04 seconds, 25 frames per second (assuming that each frame does not need time for drawing).
In addition, we use the offset (pos[0]-50,pos[1]-50) when blit again, because the picture always uses the upper left corner as the starting point of the position, so the offset will change to the center of the picture. In fact, we deliberately make the hamster and hammer higher, so we use it (pos[0]-50,pos[1]-70).

The running appearance is as follows:

Let the game start again

After each time the final score is displayed, can the game start again in 3 seconds?

Let's set a gameover=0, and increase this number for each frame after the game is over. If gameover > 100, it means 100 frames have passed, then we will start again.
Restart must mean that all kinds of data (scores, timing, etc.) and images must be reset to the original state.
The modified code is as follows:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type
import time

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
posAll = [[100, 150], [300, 150], [500, 150], [200, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = posAll[0]  # Record the position of the circle outside

# Fraction
score = 0  # Fraction counting
pygame.font.init()  # Initialize text
score_font = pygame.font.Font("MicrosoftYaqiHeiLight-2.ttf", 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

# mouse
pygame.mouse.set_visible(False)  # ! hide mouse
mpos = [300, 200]  # !! Record mouse position

times = 0  # The number of times the gopher jumps out
times_max = 10  # Maximum number of times
tick_max = 30  # How many frames does the hamster jump at a time
map = pygame.image.load("dds-map.jpg")  # !! Read pictures
rat1 = pygame.image.load("rat1.png")  # !! Read picture of hamster
rat2 = pygame.image.load("rat2.png")  # !! Read the picture of the smashed hamster
ham1 = pygame.image.load("hammer1.png")  # !! Read hammer picture
ham2 = pygame.image.load("hammer2.png")  # !! Read the picture of hammering

gameover = 0 #!! Closing time
gameover_max = 100 #!! The maximum value of end timing. If it exceeds this value, start again

while 1:
    hamsur = ham1
    ratsur = rat1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            hamsur = ham2  # !! Using a drop hammer
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(mpos[0] - pos[0], mpos[1] - pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score + 1  # Score increase
                ratsur = rat2  # !! Use the smashed hamster
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # Update mouse position

    if times >= times_max:
        # Display end screen
        sur.fill((0, 0, 0))  # Clear the screen with black at the end
        pygame.mouse.set_visible(True)
        end_font = pygame.font.Font("MicrosoftYaqiHeiLight-2.ttf", 48)  # !! Set font and size
        end_sur = score_font.render(
            "Your score is:{}/{}!".format(score, times_max), True, (255, 0, 0)
        )  # !! Generate count surface
        sur.blit(end_sur, (100, 150))
        cd = int((gameover_max - gameover) / 10)
        cd_sur = score_font.render(
            "Restart countdown{}".format(cd), True, (255, 0, 0)
        )  # !! Generate count surface
        sur.blit(cd_sur, (100, 200))  # Add fractional surface
        gameover = gameover + 1 #!! Increase end time
    else:
        sur.blit(map, (0, 0))  # Add background picture
        score_sur = score_font.render(
            "Fraction:{}/{}!".format(score, times + 1), False, (255, 0, 0)
        )  # Regenerate fractional text surface
        sur.blit(score_sur, (200, 10))  # Add fractional surface
        if tick > tick_max:  # Every 50 refreshes and transforms
            times = times + 1  # Increase count
            a = random.randint(0, 4)  # Random 0 to 4
            pos = posAll[a]  # Update the position of the circle of the external record
            tick = 0  # Reset counter
        else:  # When the transformation is not refreshed
            tick = tick + 1  # add counters
        if tick > 5:  # Don't show hamsters in the first few frames
            sur.blit(ratsur, (pos[0] - 50, pos[1] - 70))  # Draw a hamster
        sur.blit(hamsur, (mpos[0] - 50, mpos[1] - 100))  # Draw hammers

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()  # Refresh screen
    time.sleep(0.04)  # !! Hold the picture for a while

    # !! Reset game
    if gameover > gameover_max:
        pygame.mouse.set_visible(False)
        times = 0
        score = 0
        gameover = 0

Run this code to play the game again and again.
The game looks much better here, but there is no background music, and there is no sound effect when playing the hamster. We will continue to add sound in the next section.

Add sound effects

There are two kinds of sounds in the game, one is music, the other is sound. The background music is music, and the hitting sound and clicking sound in the game are all sound effects. There is usually only one music playing at the same time, but there can be many sound effects playing at the same time.

PyGame can use pygame.mixer.music.load('bg.mp3 ') to load foo.mp3 music, and then pygame.mixer.music.play(0) can play. Here, 0 means play once, if you want to play unlimited times, you need to change it to - 1

But if you want to play sound, you can only use wav format in pyGame (and 32-bit depth is not supported, only 16 bit depth is supported). The way to load the sound effect is sd=pygame.mixer.Sound("hit.wav"), and the playback is sd.play(0), where 0 is also 1 time. Generally, the sound effect does not need to be played continuously.

We can play background music at the beginning of the game, but we can only play the sound of hammer when we click the mouse event.type == MOUSEBUTTONDOWN, and only when we hit the hamster.

The modified code is as follows:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type
import time

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
posAll = [[100, 150], [300, 150], [500, 150], [200, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = posAll[0]  # Record the position of the circle outside

# Fraction
score = 0  # Fraction counting
pygame.font.init()  # Initialize text
score_font = pygame.font.Font("MicrosoftYaqiHeiLight-2.ttf", 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

# mouse
pygame.mouse.set_visible(False)  # ! hide mouse
mpos = [300, 200]  # !! Record mouse position

times = 0  # The number of times the gopher jumps out
times_max = 10  # Maximum number of times
tick_max = 30  # How many frames does the hamster jump at a time
map = pygame.image.load("dds-map.jpg")  # !! Read pictures
rat1 = pygame.image.load("rat1.png")  # !! Read picture of hamster
rat2 = pygame.image.load("rat2.png")  # !! Read the picture of the smashed hamster
ham1 = pygame.image.load("hammer1.png")  # !! Read hammer picture
ham2 = pygame.image.load("hammer2.png")  # !! Read the picture of hammering

gameover = 0  # !! Closing time
gameover_max = 100  # !! The maximum value of end timing. If it exceeds this value, start again

# Music and sound effects
pygame.mixer.music.load("bg.mp3")  # !! Load background music
pygame.mixer.music.play(-1)  # !! Unlimited background music
hitsound = pygame.mixer.Sound("hit.wav")  # !! Load hit sound
hurtsound = pygame.mixer.Sound("aiyo2.wav")  # !! Load hamster call

while 1:
    hamsur = ham1
    ratsur = rat1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            hamsur = ham2  # Using a drop hammer
            hitsound.play()  # !! Play percussion sound
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(mpos[0] - pos[0], mpos[1] - pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score + 1  # Score increase
                ratsur = rat2  # Use the smashed hamster
                hurtsound.play()  # !! Play hamster sound
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # Update mouse position

    if times >= times_max:
        # Display end screen
        sur.fill((0, 0, 0))  # Clear the screen with black at the end
        pygame.mouse.set_visible(True)
        end_font = pygame.font.Font("MicrosoftYaqiHeiLight-2.ttf", 48)  # Set font and size
        end_sur = score_font.render(
            "Your score is:{}/{}!".format(score, times_max), True, (255, 0, 0)
        )  # Generate count surface
        sur.blit(end_sur, (100, 150))
        cd = int((gameover_max - gameover) / 10)
        cd_sur = score_font.render(
            "Restart countdown{}".format(cd), True, (255, 0, 0)
        )  # Generate count surface
        sur.blit(cd_sur, (100, 200))  # Add fractional surface
        gameover = gameover + 1  # !! Increase end time
    else:
        sur.blit(map, (0, 0))  # Add background picture
        score_sur = score_font.render(
            "Fraction:{}/{}!".format(score, times + 1), False, (255, 0, 0)
        )  # Regenerate fractional text surface
        sur.blit(score_sur, (200, 10))  # Add fractional surface
        if tick > tick_max:  # Every 50 refreshes and transforms
            times = times + 1  # Increase count
            a = random.randint(0, 4)  # Random 0 to 4
            pos = posAll[a]  # Update the position of the circle of the external record
            tick = 0  # Reset counter
        else:  # When the transformation is not refreshed
            tick = tick + 1  # add counters
        if tick > 5:  # Don't show hamsters in the first few frames
            sur.blit(ratsur, (pos[0] - 50, pos[1] - 70))  # Draw a hamster
        sur.blit(hamsur, (mpos[0] - 50, mpos[1] - 100))  # Draw hammers

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()  # Refresh screen
    time.sleep(0.04)  # Hold the picture for a while

    # Reset game
    if gameover > gameover_max:
        pygame.mouse.set_visible(False)
        times = 0
        score = 0
        gameover = 0

Running the above code, you can hear happy background music. When you click the mouse, there will be a thumping sound. When you hit the hamster, there will be a whoops.

Publishing software

The code we write can only run on our own computer at present, because we need to install python first, and then install pygame, which is different from the software we usually download. The downloaded software can run directly (or run after installing itself).

Python provides us with a tool to automatically package code into software. Under Windows, auto py to exe is recommended. Also install PIP install Auto py to exe first, and then just execute auto py to exe to open a window.

The basic settings are as follows:

Pay attention to several points:

  • Script Location points to your main. Py file, here is main.py
  • Onefile select One Directory, which will put all files produced in one folder
  • Console Window select Console Based, because our pygame is Console Based
  • Icon icon, you can download. ico files on the Internet, such as easyicon There are many. There is a mouse icon icon.ico in the net disk
  • Additional Files. Click the Add Files button to select all the fonts, pictures and sounds used
  • Convert. Py to. Exe click this button to generate. After generating, it will become two blue buttons

Click OPEN OUTPUT FOLDER to open the production software directory (the default is in the output folder under your code folder), find the file with the same name as your Script Location, and click it to run the game.

You can also copy the MAIN.exe and paste the shortcut on the desktop. In the future, just click the shortcut.

Include a main.rar file in the network disk file, download it and unzip it to get the software I packaged and generated.

There is a bit of trouble about the method of generating software under Mac and apple, please pay attention to it.

The first little game seems to have been developed, but there are still many contents, and our code also has many unreasonable places. In the next article, we will review and sort out together, and continue to introduce more development methods of little games.

Add sound effects

There are two kinds of sounds in the game, one is music, the other is sound. The background music is music, and the hitting sound and clicking sound in the game are all sound effects. There is usually only one music playing at the same time, but there can be many sound effects playing at the same time.

PyGame can use pygame.mixer.music.load('bg.mp3 ') to load foo.mp3 music, and then pygame.mixer.music.play(0) can play. Here, 0 means play once, if you want to play unlimited times, you need to change it to - 1

But if you want to play sound, you can only use wav format in pyGame (and 32-bit depth is not supported, only 16 bit depth is supported). The way to load the sound effect is sd=pygame.mixer.Sound("hit.wav"), and the playback is sd.play(0), where 0 is also 1 time. Generally, the sound effect does not need to be played continuously.

We can play background music at the beginning of the game, but we can only play the sound of hammer when we click the mouse event.type == MOUSEBUTTONDOWN, and only when we hit the hamster.

The modified code is as follows:

import pygame
import sys
import random
from pygame.locals import *  # Bring in mouse event type
import time

pygame.init()  # Initialization
window = pygame.display.set_mode([600, 400])  # Setup window

sur = pygame.Surface([600, 400])  # Draw background container
clr = (0, 0, 255)
posAll = [[100, 150], [300, 150], [500, 150], [200, 300], [400, 300]]  # Six positions
rad = 50
tick = 0  # Counter
pos = posAll[0]  # Record the position of the circle outside

# Fraction
score = 0  # Fraction counting
pygame.font.init()  # Initialize text
score_font = pygame.font.Font("MicrosoftYaqiHeiLight-2.ttf", 30)  # !! Set font and size
score_sur = score_font.render(str(score), False, (255, 0, 0))  # !! Generate count surface

# mouse
pygame.mouse.set_visible(False)  # ! hide mouse
mpos = [300, 200]  # !! Record mouse position

times = 0  # The number of times the gopher jumps out
times_max = 10  # Maximum number of times
tick_max = 30  # How many frames does the hamster jump at a time
map = pygame.image.load("dds-map.jpg")  # !! Read pictures
rat1 = pygame.image.load("rat1.png")  # !! Read picture of hamster
rat2 = pygame.image.load("rat2.png")  # !! Read the picture of the smashed hamster
ham1 = pygame.image.load("hammer1.png")  # !! Read hammer picture
ham2 = pygame.image.load("hammer2.png")  # !! Read the picture of hammering

gameover = 0  # !! Closing time
gameover_max = 100  # !! The maximum value of end timing. If it exceeds this value, start again

# Music and sound effects
pygame.mixer.music.load("bg.mp3")  # !! Load background music
pygame.mixer.music.play(-1)  # !! Unlimited background music
hitsound = pygame.mixer.Sound("hit.wav")  # !! Load hit sound
hurtsound = pygame.mixer.Sound("aiyo2.wav")  # !! Load hamster call

while 1:
    hamsur = ham1
    ratsur = rat1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:  # If it's a mouse down event
            hamsur = ham2  # Using a drop hammer
            hitsound.play()  # !! Play percussion sound
            mpos = pygame.mouse.get_pos()  # Get mouse position
            dis = pygame.math.Vector2(mpos[0] - pos[0], mpos[1] - pos[1])  # Calculate coordinate difference
            len = pygame.math.Vector2.length(dis)  # Calculated distance
            if len < rad:
                tick = 1000  # Change position now
                score = score + 1  # Score increase
                ratsur = rat2  # Use the smashed hamster
                hurtsound.play()  # !! Play hamster sound
        elif event.type == MOUSEMOTION:  # When the mouse moves
            mpos = pygame.mouse.get_pos()  # Update mouse position

    if times >= times_max:
        # Display end screen
        sur.fill((0, 0, 0))  # Clear the screen with black at the end
        pygame.mouse.set_visible(True)
        end_font = pygame.font.Font("MicrosoftYaqiHeiLight-2.ttf", 48)  # Set font and size
        end_sur = score_font.render(
            "Your score is:{}/{}!".format(score, times_max), True, (255, 0, 0)
        )  # Generate count surface
        sur.blit(end_sur, (100, 150))
        cd = int((gameover_max - gameover) / 10)
        cd_sur = score_font.render(
            "Restart countdown{}".format(cd), True, (255, 0, 0)
        )  # Generate count surface
        sur.blit(cd_sur, (100, 200))  # Add fractional surface
        gameover = gameover + 1  # !! Increase end time
    else:
        sur.blit(map, (0, 0))  # Add background picture
        score_sur = score_font.render(
            "Fraction:{}/{}!".format(score, times + 1), False, (255, 0, 0)
        )  # Regenerate fractional text surface
        sur.blit(score_sur, (200, 10))  # Add fractional surface
        if tick > tick_max:  # Every 50 refreshes and transforms
            times = times + 1  # Increase count
            a = random.randint(0, 4)  # Random 0 to 4
            pos = posAll[a]  # Update the position of the circle of the external record
            tick = 0  # Reset counter
        else:  # When the transformation is not refreshed
            tick = tick + 1  # add counters
        if tick > 5:  # Don't show hamsters in the first few frames
            sur.blit(ratsur, (pos[0] - 50, pos[1] - 70))  # Draw a hamster
        sur.blit(hamsur, (mpos[0] - 50, mpos[1] - 100))  # Draw hammers

    # Refresh screen
    window.blit(sur, (0, 0))
    pygame.display.flip()  # Refresh screen
    time.sleep(0.04)  # Hold the picture for a while

    # Reset game
    if gameover > gameover_max:
        pygame.mouse.set_visible(False)
        times = 0
        score = 0
        gameover = 0

Running the above code, you can hear happy background music. When you click the mouse, there will be a thumping sound. When you hit the hamster, there will be a whoops.

Tags: Python pip Windows network

Posted on Mon, 02 Dec 2019 15:48:17 -0800 by spxdcz