[Pygame] Use Pygame to make simple and fun small game series 1: mouse catch ball

foreword

Hello everyone! I am a newcomer posting an article for the first time, please advise if I am wrong

Preparation

We need the following tools :

  • Pygame library
  • A computer with Python 3.8 (or higher) installed
  • IDLE or other development tools (such as PyCharm )

If you have not installed the Pygame library, enter the following code in CMD :

  1| pip install pygame 

If no error is reported, the installation is successful.

start writing code

Initialize variables

First, we need to import the Pygame library, Sys library, Random library and Locals library under Pygame

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

Then we have to initialize Pygame , otherwise an error will be reported

pygame.init()

The next step is to create the screen and other values

screen = pygame.display.set_mode((1820, 980)) #创建屏幕
ball_pos = (random.randint(0, 1770), random.randint(0, 930)) #随机创建球的位置
ball_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) #随机创建球的颜色
ball_size = 50
is_down = False #判断鼠标有没有捉到球
score = 0 #创建分数
font = pygame.font.Font("Mojangles.ttf", 48) #创建字体,字体文件我会放在文章结尾

Okay, everything is ready, let's write the main body next!

Create subject

We have to make the simplest loop program first:

while True:
    for event in pygame.event.get(): #获取当前事件
        if event.type == QUIT: #如果事件是退出
            pygame.quit() #}退出
            sys.exit(0)   #}退出
    
    pygame.display.update() #开始循环

After running, a black window pops up.

We have to first define an initialization function to make it white

def init(screen):
    screen.fill((255, 255, 255))

Put this function inside the loop

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
	init(screen)    #初始化
    pygame.display.update(

Next we want to create the ball, put this code at the end of the initialization function:

pygame.draw.circle(screen, ball_color, pos, ball_size) # 创建小球

After that, there will be a small ball that will change position on each run

After finishing the creation of the main body, the next step is the core part!

create core

How can we judge whether the mouse has "caught" the ball? There is no function for judging in Pygame, so we can only do it ourselves.

I thought of a way, because the function circle() for drawing a ball, the radius parameter is the radius of the drawing ball, so we can judge whether the position is within the range of the ball when the mouse is pressed because it cannot be in the
insert image description here
circle The shape is fine, so the part left blank is regarded as pressed

The core part is the following code:

def core():
    global ball_color, pos, score
    if is_down:
        mouse = pygame.mouse.get_pos()
        if ball_pos[0] + 50 > mouse[0] > ball_pos[0] - 50 and ball_pos[1] + 50 > mouse[1] > ball_pos[1] - 50:
            score += 1
            ball_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            ball_pos = (random.randint(0, 1770), random.randint(0, 930))

        else:
            pygame.draw.circle(screen, (255, 255, 0), mouse, 30)

This line of code is to judge whether the mouse is within the range when it is pressed. If so, re-designate the position and color and add points. If not, it will display a yellow circle to remind the player that it has not been "caught".

Add the core function to the loop, but we must first determine whether the mouse is pressed, and add it together

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        if event.type == MOUSEBUTTONDOWN: # 判断鼠标有没有按下
            is_down = True # 如果有, True
        else:
            is_down = False #如果没有, False
    init(screen)
    core() #添加核心函数
    pygame.display.update()

Final Step: Display the Score

We're just one step away! Add points!
Very simple, use the render() function to integrate it with the show_score() function

def show_score(score):
    text = font.render("{0}".format(score), True, (0, 0, 0)) # 写文字
    screen.blit(text, (1700, 10)) # 显示文字

Add it to the loop:

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        if event.type == MOUSEBUTTONDOWN:
            is_down = True
        else:
            is_down = False
    init(screen)
    core()
    show_score(score) # 显示分数
    pygame.display.update()

final code

import random
import sys

import pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((1820, 980))
clock = pygame.time.Clock()
FPS = 100
ball_pos = (random.randint(0, 1770), random.randint(0, 930))
ball_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
is_down = False
score = 0
font = pygame.font.Font("Mojangles.ttf", 48)


def core():
    global ball_color, ball_pos, score
    if is_down:
        mouse = pygame.mouse.get_pos()
        if ball_pos[0] + 50 > mouse[0] > ball_pos[0] - 50 and ball_pos[1] + 50 > mouse[1] > ball_pos[1] - 50:
            score += 1
            ball_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            ball_pos = (random.randint(0, 1770), random.randint(0, 930))

        else:
            pygame.draw.circle(screen, (255, 255, 0), mouse, 30)


def show_score(score):
    text = font.render("{0}".format(score), True, (0, 0, 0))
    screen.blit(text, (1700, 10))


def init(screen):
    screen.fill((255, 255, 255))
    pygame.draw.circle(screen, ball_color, pos, 50)


while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        if event.type == MOUSEBUTTONDOWN:
            is_down = True
        else:
            is_down = False
    init(screen)
    core()
    show_score(score)
    pygame.display.update()

epilogue

Glad you can read this article! But now, you can play by yourself or with your friends to see who can "catch" the most balls in the shortest time, and post them in the comment area!

Guess you like

Origin blog.csdn.net/csdngeogeo/article/details/126521622