pygame implementation of ball dropping Game 1

Posted by nhan on Sun, 16 Jan 2022 08:41:24 +0100

Game content: a ball falls on the screen and moves through the mouse. If the underground wood block is connected, points will be added, otherwise one life will be subtracted, and the game will end when three lives are used up.

Lead bag

Introduce the corresponding package and write a printed text as before

import sys, random,  pygame
from pygame.locals import *


def print_text(font, x, y, text, color=(255, 255, 255)):
    img_text = font.render(text, True, color)
    screen.blit(img_text, (x, y))

Initialize configuration

Initialize the game, some information of pygame window, and some parameters used in the game.

pygame.init()
# timer
mainClock = pygame.time.Clock()

# Set screen and window titles
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drop ball game")
# Set font
font1 = pygame.font.SysFont("Founder bold black song simplified Chinese", 24)
pygame.mouse.set_visible(False)
# Set color variable
white = 255, 255, 255
red = 220, 50, 50
yellow = 230, 230, 50
black = 0, 0, 0

# Life number
lives = 3
# branch
score = 0
# The game begins flg
game_over = True
# Mouse position
mouse_x = mouse_y = 0
pos_x = 300
pos_y = 460
# x and y axis coordinates of the ball falling
bomb_x = random.randint(0, 500)
bomb_y = -50
# The speed at which the ball falls
vel_y = 0.7

Capture events

Capture the event. If you press the mouse at the end of the game, the game will restart, mouse_x, mouse_y snap mouse position, move_x, move_y gets the offset of the mouse

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == MOUSEMOTION:
            mouse_x, mouse_y = event.pos
            move_x, move_y = event.rel
        elif event.type == MOUSEBUTTONUP:
            if game_over:
                game_over = False
                lives = 3
                score = 0
    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()

Fill the screen and let the ball fall

Fill the screen with a warm color. If the game does not start, the screen displays "click to start a new game", otherwise the ball falls.
If the ball is greater than 500, reset a new ball and subtract one from life. If there is no life, the game ends.
The element collision principle is not used here. There are two relative positions. If the ball is greater than the vertical coordinate of the baffle, the x coordinate of the tangent ball is greater than the starting position of the baffle and less than the width of the baffle, the score is added and the position of the ball is reset.

	screen.fill((255, 166, 77))

    if game_over:
        print_text(font1, 100, 200, "Click new game")
    else:
        bomb_y += vel_y
    if bomb_y > 500:
        bomb_x = random.randint(0, 500)
        bomb_y = -50
        lives -= 1
    if lives == 0:
        game_over = True

    elif bomb_y > pos_y:
        if bomb_x > pos_x and bomb_x < pos_x + 120:
            score += 120
            bomb_x = random.randint(0, 500)
            bomb_y = -50

Draw the ball and bezel, draw the screen

According to Bob_ x,bomb_ Y to display the ball and draw a shadow

Rectangle like

Display the number of lives and scores, update the screen, and set the frequency per second to 20
There is obviously a big problem here, because the point is the center of the circle when drawing the circle, so there will be an error in the comparison. If you use the right part of the rectangle to catch the left part of the ball center, the display will still not be received. We don't go deep here. The simple game is realized, and I'll put the optimization in the second part.

    pygame.draw.circle(screen, black, (bomb_x - 4, int(bomb_y) - 4), 30, 0)
    pygame.draw.circle(screen, yellow, (bomb_x, int(bomb_y)), 30, 0)
    pygame.draw.rect(screen, black, (pos_x - 4, pos_y - 4, 120, 40), 0)
    pygame.draw.rect(screen, red, (pos_x, pos_y, 120, 40), 0)

    print_text(font1, 0, 0, "Life number: " + str(lives))

    print_text(font1, 500, 0, "fraction: " + str(score))

    pygame.display.update()
    mainClock.tick(20)

Complete code

import sys, random,  pygame
from pygame.locals import *


def print_text(font, x, y, text, color=(255, 255, 255)):
    img_text = font.render(text, True, color)
    screen.blit(img_text, (x, y))


pygame.init()
# timer
mainClock = pygame.time.Clock()

# Set screen and window titles
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drop ball game")
# Set font
font1 = pygame.font.SysFont("Founder bold black song simplified Chinese", 24)
pygame.mouse.set_visible(False)
# Set color variable
white = 255, 255, 255
red = 220, 50, 50
yellow = 230, 230, 50
black = 0, 0, 0

# Number of life
lives = 3
# branch
score = 0
# The game begins flg
game_over = True
# Mouse position
mouse_x = mouse_y = 0
pos_x = 300
pos_y = 460
# x and y axis coordinates of the ball falling
bomb_x = random.randint(0, 500)
bomb_y = -50
# The speed at which the ball falls
vel_y = 0.7


while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == MOUSEMOTION:
            mouse_x, mouse_y = event.pos
            move_x, move_y = event.rel
        elif event.type == MOUSEBUTTONUP:
            if game_over:
                game_over = False
                lives = 3
                score = 0
    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()

    screen.fill((255, 166, 77))

    if game_over:
        print_text(font1, 100, 200, "Click new game")
    else:
        bomb_y += vel_y

    if bomb_y > 500:
        bomb_x = random.randint(0, 500)
        bomb_y = -50
        lives -= 1
    if lives == 0:
        game_over = True

    elif bomb_y > pos_y:
        if bomb_x > pos_x and bomb_x < pos_x + 120:
            score += 120
            bomb_x = random.randint(0, 500)
            bomb_y = -50

    pygame.draw.circle(screen, black, (bomb_x - 4, int(bomb_y) - 4), 30, 0)
    pygame.draw.circle(screen, yellow, (bomb_x, int(bomb_y)), 30, 0)
    pos_x = mouse_x
    if pos_x < 0:
        pos_x = 0
    elif pos_x > 500:
        pos_x = 500

    pygame.draw.rect(screen, black, (pos_x - 4, pos_y - 4, 120, 40), 0)
    pygame.draw.rect(screen, red, (pos_x, pos_y, 120, 40), 0)

    print_text(font1, 0, 0, "Life number: " + str(lives))

    print_text(font1, 500, 0, "fraction:  " + str(score))

    pygame.display.update()
    mainClock.tick(20)

Topics: Python Game Development pygame pyhon