python-pygame small game ball ball battle

This is the first time I write an article and share my python program with you. Please like it a lot, and if you think my writing is good, you can also pay attention to me. I will continue to post more articles in the future!

Today I'm going to introduce the game I made myself - Battle of Balls! Let's take a look!

-------------------------------------------------- - Start writing code! -------------------------------------------------- -------

Tips before coding:

First, install the pygame module with cmd!

pip install pygame

1. Initialization

First, import the very important pygame, random and math modules (I used as), initialize the program, make the interface, and write the title

# import pygame, random and math
import pygame as pg
import random as rd
import math

# init program
pg.init()
# set screen
screen = pg.display.set_mode((1000, 500))
screen.fill((255, 255, 255))
# set title
pg.display.set_caption("球球大作战", "4.0")

After the program is initialized, the next step can be performed.

2. Definition of functions, methods and classes

A program cannot do without functions and classes. We have to define the function circle first, so that it is convenient to draw a circle.

# def circle
def circle(color, point, r, size):
    pg.draw.circle(screen, color, point, r, size)

The next thing to do is the ball class. In order to be eaten, we need to use classes (get it?)

# class ball
class Ball():
    def __init__(self):
        self.color = (rd.randint(0, 255), rd.randint(0, 255), rd.randint(0, 255))
        self.x =rd.randint(0, 1000)
        self.y = rd.randint(0, 500)
        self.r = rd.randint(5, 15)
        self.size = rd.randint(5, 15)

Then set the list of balls controlled by the player and the list of painted balls.

# make a balllist
balllist = []
for i in range(600):
    balllist.append(Ball())

# creat myball
myball = Ball()
myball.color = (0, 0, 0)
myball.x = 500
myball.y = 250
myball.size = 5
myball.speed = 10

At the end of this paragraph, you must make a good judgment, press, eat the ball and generate.

The math module is used here, and the Pythagorean theorem is also used!

30 balls are spawned every ten seconds, so you can "never" run out of balls

To be more realistic, I also added some other code. The more you eat, the slower you go. It is recommended here that *=0.(), you can adjust as much as you want. Why *=? Because / or / / either cannot be divided or divided to zero, it will be troublesome.

# def check touch
# use the pythagorean theorem
def touch(myX, myY, fX, fY, myR, fR):
    distance = math.sqrt((myX - fX) ** 2 + (myY - fY) ** 2)
    if distance <= myR + fR:
        # just return True
        return True
    else:
        # return False
        return False

# def foodDelivery
def foodDelivery():
    time = pg.time.get_ticks()
    # every 10 seconds put 30 foods
    if time % 10000 >= 9000 and time % 10000 <= 9020:
        for i in range(30):
            balllist.append(Ball())

# def draw
# use "Ball" and for range to append in the balllist
def draw():
    for ball in balllist:
        if touch(myball.x, myball.y, ball.x, ball.y, myball.size, ball.size):
            balllist.remove(ball)
            myball.size += 0.1
            # make the speed to be smaller than the last one
            # use the multiplier scale decreases and inverse proportional function
            myball.speed *= 0.992
        else:
            circle(ball.color, (ball.x, ball.y), ball.size, 0)
    circle(myball.color, (myball.x, myball.y), myball.size, 0)

This section is done!

3. The main program runs

The next step must be serious, and the main program will be run soon.

Tips: The fps (frame rate) must be well controlled, otherwise the computer graphics card and CPU may be stuck, and an anti-jamming program must be written to prevent the program from suddenly reporting an error or pausing to exit.

# check fps, do not quit program
fps = pg.time.Clock()
# check quit and play program
while True:
    # do not make the fps so high
    # if the fps is high, the computer will ~"bomb!"
    fps.tick(60)
    event = pg.event.poll()
    if event.type == pg.QUIT:
        pg.quit()
        exit()

The next thing to do is to move the ball, use pygame.key.get_pressed() to judge.

keys = pg.key.get_pressed()
# make the ball to move
# I use the "wasd"
# also can use up down right left
if keys[pg.K_w]:
   myball.y -= myball.speed

"wasd" can be up, down, left, or right, pay attention to the addition and subtraction of the x and y coordinate axes.

# check quit and play program
while True:
    # do not make the fps so high
    # if the fps is high, the computer will ~"bomb!"
    fps.tick(60)
    event = pg.event.poll()
    if event.type == pg.QUIT:
        pg.quit()
        exit()
    keys = pg.key.get_pressed()
    # make the ball to move
    # I use the "wasd"
    # also can use up down right left
    if keys[pg.K_w]:
        myball.y -= myball.speed
    if keys[pg.K_a]:
        myball.x -= myball.speed
    if keys[pg.K_s]:
        myball.y += myball.speed
    if keys[pg.K_d]:
        myball.x += myball.speed
    if keys[pg.K_UP]:
        myball.y -= myball.speed
    if keys[pg.K_DOWN]:
        myball.y += myball.speed
    if keys[pg.K_LEFT]:
        myball.x -= myball.speed
    if keys[pg.K_RIGHT]:
        myball.x += myball.speed
    # the e is to update ball's xy
    elif keys[pg.K_e]:
        myball.x, myball.y = 500, 250

Finally, write the method of updating and drawing, and the whole program is finished! (Don't forget to add a fill, so it is easy to update)

while True:
    # do not make the fps so high
    # if the fps is high, the computer will ~"bomb!"
    fps.tick(60)
    event = pg.event.poll()
    if event.type == pg.QUIT:
        pg.quit()
        exit()
    keys = pg.key.get_pressed()
    # make the ball to move
    # I use the "wasd"
    # also can use up down right left
    if keys[pg.K_w]:
        myball.y -= myball.speed
    if keys[pg.K_a]:
        myball.x -= myball.speed
    if keys[pg.K_s]:
        myball.y += myball.speed
    if keys[pg.K_d]:
        myball.x += myball.speed
    if keys[pg.K_UP]:
        myball.y -= myball.speed
    if keys[pg.K_DOWN]:
        myball.y += myball.speed
    if keys[pg.K_LEFT]:
        myball.x -= myball.speed
    if keys[pg.K_RIGHT]:
        myball.x += myball.speed
    # the e is to update ball's xy
    elif keys[pg.K_e]:
        myball.x, myball.y = 500, 250
    # draw and check
    draw()
    foodDelivery()
    # display program
    pg.display.update()
    screen.fill((255, 255, 255))

4. Complete code

Finally, all the codes are presented:

# import pygame, random and math
import pygame as pg
import random as rd
import math

# init program
pg.init()
# set screen
screen = pg.display.set_mode((1000, 500))
screen.fill((255, 255, 255))
# set title
pg.display.set_caption("BallFight_Avaritia", "4.0")
# Chinese:pg.display.set_caption("球球大作战_无尽贪婪", "4.0")

# def circle
def circle(color, point, r, size):
    pg.draw.circle(screen, color, point, r, size)

# class ball
class Ball():
    def __init__(self):
        self.color = (rd.randint(0, 255), rd.randint(0, 255), rd.randint(0, 255))
        self.x =rd.randint(0, 1000)
        self.y = rd.randint(0, 500)
        self.r = rd.randint(5, 15)
        self.size = rd.randint(5, 15)

# make a balllist
balllist = []
for i in range(600):
    balllist.append(Ball())

# creat myball
myball = Ball()
myball.color = (0, 0, 0)
myball.x = 500
myball.y = 250
myball.size = 5
myball.speed = 10

# def check touch
# use the pythagorean theorem
def touch(myX, myY, fX, fY, myR, fR):
    distance = math.sqrt((myX - fX) ** 2 + (myY - fY) ** 2)
    if distance <= myR + fR:
        # just return True
        return True
    else:
        # return False
        return False

# def foodDelivery
def foodDelivery():
    time = pg.time.get_ticks()
    # every 10 seconds put 30 foods
    if time % 10000 >= 9000 and time % 10000 <= 9020:
        for i in range(30):
            balllist.append(Ball())

# def draw
# use "Ball" and for range to append in the balllist
def draw():
    for ball in balllist:
        if touch(myball.x, myball.y, ball.x, ball.y, myball.size, ball.size):
            balllist.remove(ball)
            myball.size += 0.1
            # make the speed to be smaller than the last one
            # use the multiplier scale decreases and inverse proportional function
            myball.speed *= 0.992
        else:
            circle(ball.color, (ball.x, ball.y), ball.size, 0)
    circle(myball.color, (myball.x, myball.y), myball.size, 0)

# check fps, do not quit program
fps = pg.time.Clock()
# check quit and play program
while True:
    # do not make the fps so high
    # if the fps is high, the computer will ~"bomb!"
    fps.tick(60)
    event = pg.event.poll()
    if event.type == pg.QUIT:
        pg.quit()
        exit()
    keys = pg.key.get_pressed()
    # make the ball to move
    # I use the "wasd"
    # also can use up down right left
    if keys[pg.K_w]:
        myball.y -= myball.speed
    if keys[pg.K_a]:
        myball.x -= myball.speed
    if keys[pg.K_s]:
        myball.y += myball.speed
    if keys[pg.K_d]:
        myball.x += myball.speed
    if keys[pg.K_UP]:
        myball.y -= myball.speed
    if keys[pg.K_DOWN]:
        myball.y += myball.speed
    if keys[pg.K_LEFT]:
        myball.x -= myball.speed
    if keys[pg.K_RIGHT]:
        myball.x += myball.speed
    # the e is to update ball's xy
    elif keys[pg.K_e]:
        myball.x, myball.y = 500, 250
    # draw and check
    draw()
    foodDelivery()
    # display program
    pg.display.update()
    screen.fill((255, 255, 255))

Five, renderings

6. Knowledge summary

Through this programming, we learned how to use pygame to make games, and also used many modules and complex codes.

We also learned how to use the random, math and pygame modules, and learned about the power of the pygme module.

The ball we manipulate is like the big whites and the angels in white. They try their best to fight against viruses (other edible balls) and make us safer.

I hope that everyone will learn more about python, learn programming and share programs during the period of isolation at home, so as to overcome difficulties and overcome the epidemic.

Everyone can like it a lot~ Thank you for reading! see you later

Easter egg: (revealed in the next issue: Aurora Labyrinth)

Guess you like

Origin blog.csdn.net/B20111003/article/details/124608538