python-pygame小游戏之球球大作战

python-pygame小游戏之球球大作战_第1张图片

这是我第一次写文章,和大家分享我的python程序。请大家多多点赞,觉得我写的好的话还可以关注一下我。后期我会继续多发一些文章的哦!

今天我要来介绍介绍我自己做的游戏——球球大作战!大家来看看吧!

---------------------------------------------------开始写代码了!---------------------------------------------------------

做代码前的小贴士:

首先要用cmd安装好pygame模块哦!

pip install pygame

一、初始化

首先要导入很重要的pygame,random和math模块(我用了as),初始化程序,做好界面,写上标题

# 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")

初始化好了程序才能进行下一步。

二、函数、方法和类的定义

程序少不了函数与类。我们得先定义好函数circle,这样方便画圆圈。

# 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

这一段的最后要做好判断按下,吃球和生成。

这里要运用上math模块,还用了勾股定理!

每过十秒生成30个球,这样就“永远”也吃不完球了

为了更真实一点,我还加了一些其它代码。越吃得多,速度就越慢。这里推荐*=0.(),想要多少可以自己调。为什么要*=呢?因为/或//要么除不进或者除到零了就麻烦了。

# 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)

这样这一段就做好了!

三、主程序运行

接下来必须得认真了,马上就要运行主程序了。

小贴士:fps(帧率)一定要控制好,否则电脑显卡和cpu可能会卡,还要写好防卡程序,可以避免程序忽然报错或者暂停退出。

# 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()

接下来要做球的移动了,要用pygame.key.get_pressed()来判断哦。

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”上下左右都可以,注意x,y坐标轴的加减。

# 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

最后写上更新和画图的方法,整个程序就写好了!(别忘了加一次fill,这样易于更新)

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))

四、完整代码

最后奉上全部代码:

# 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))

五、效果图

python-pygame小游戏之球球大作战_第2张图片

六、知识总结

通过这次编程,我们了解了如何使用pygame做游戏,也用到了许多模块和复杂的代码。

我们也从中学习到了random, math和pygame模块的运用方法,了解了pygme模块的厉害。

我们操控的球,就好像大白们和白衣天使,他们竭尽全力,与病毒(其他可以吃的球)战斗,让我们更加安全。

希望大家多多学习python,借助在家隔离的这段期间学习编程,分享程序,共克时艰,战胜疫情。

大家可以多多点赞哦~谢谢阅读!下次再见

彩蛋:(下期透露:极光迷宫)

你可能感兴趣的:(编程,学习,python,pygame,游戏,青少年编程,小程序)