好吧,我一周前才开始使用pygame,但我想我已经了解了基本原理。我的游戏真的很简单,左右移动气球来躲避来袭的螺丝。 我成功地使气球左右移动,但我对类非常陌生,我不知道有任何其他方法可以快速地在屏幕上产生多个螺丝钉。任何帮助都将不胜感激。在
这是我的代码:
import pygame
from pygame.locals import *
import sys
import time
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption('Baloon Pop')
baloon_size = (70,70)
white = (255,255,255)
cyan = (0,255,255)
red = (255,0,0)
screen.fill(cyan)
baloon = pygame.image.load('/users/Gaming/Desktop/rsz_baloon.png')
screw = pygame.image.load('/users/Gaming/Desktop/rsz_screw_png3029.png')
FPS = 30
fps_time = pygame.time.Clock()
baloonX = 280
baloonY = 500
import random
screwX = random.randint(0,600)
screwY = 20
LEFT = "left"
RIGHT = "right"
movement = "down"
while True:
screwY = screwY+10
screen.fill(cyan)
screen.blit(screw, (screwX,screwY))
screen.blit(baloon, (baloonX,baloonY))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_RIGHT:
baloonX = baloonX+30
if baloonX >= 580:
baloonX = baloonX -30
elif event.key == K_LEFT:
baloonX = baloonX -30
if baloonX <=-30:
baloonX = baloonX+30
pygame.display.update()
fps_time.tick(FPS)
为了使你的程序不那么复杂,你需要一些关于气球和螺丝的类。第一个类是为你的玩家准备的,假设你只从左向右移动:
这段代码将使你的气球成为精灵,准备好检测碰撞。你的screws类看起来很相似,只是在类的
^{2}$move
和location
函数和speed
在类的__init__
部分:这个类使螺丝精灵,也准备好检测。课程部分到此结束。现在我们来谈谈这些精灵的分组,等等:
同样,变量是可变的,但是
c
越高,螺钉下降的速度就越快。a
和b
将决定气球的位置,random.randint()
将决定螺钉的位置。self.rect.top
是一种查找位置的方法,它将其用作rect
的“顶部”侧的位置。在这种情况下,它保持不变。对于,self.rect.left
也是一样,但它是rect
的“左”侧的位置。现在转到气球的移动部分,为了避免上下按键的过度按下(以及疲劳),请在后面添加以下代码行:delay
是每个KEYDOWN被激活之间的毫秒数,interval是等待到重复的KEYDOWN的毫秒数。这将帮助用户只需按住右箭头键的左边,气球将继续朝所需的方向移动。下一节将讨论on
和screwy
变量。接下来,while循环即将出现:只要
screwy
-1的值小于-1(负1),while循环会生成尽可能多的螺钉。这还会翻转屏幕,以避免屏幕上留下任何“轨迹”。现在到气球的移动部分:这将允许你移动气球(你可以按住键使气球像在真正的电子游戏中一样移动)。接下来将是螺丝钉的继续繁殖:
这将在随机位置生成螺钉(相同的
self.rect.top
值使其看起来真实)。b
在本例中等于屏幕的宽度。最后,精灵检测:这将检测气球是否与螺丝相撞。如果那是真的,你可以决定。您可以退出while循环并退出程序,这是一种方法。但是,如果您计划执行
print 'Game Over!
之类的操作,请在执行on = False
/sys.exit()
之前添加这一行,这将立即退出循环/程序。您需要重新blit图像并允许屏幕顺利退出(pygame.quit
):记住把
pygame.quit()
放在while循环之外,否则屏幕会立即消失。当然,做一些代码来防止气球离开屏幕。将KEYDOWN部分更改为以下内容:如果向左/向右移动一次使气球部分离开屏幕,程序将不允许气球通过不使用
pass
向左/向右移动。这将大大改善你的计划,并回答你的问题。我希望这对你有帮助!在首先,我建议使用一个类来控制你的播放器。 这使得绘制和检测碰撞更容易。 一种简单的方法是:
然后,一个类似的类来控制你的敌人。在
^{2}$这里, time_passed是Clock()对象的刻度值。 屏幕是你的pygame.display表面。
现在您已经将敌人对象化了,您可以创建一个列表来存储敌方类的实例。在
正如我所建议的,使用这个机制可以使你的游戏更加流畅。 不建议对每个KEYDOWN事件使用增量。在
创建一个列表来存储敌方实例并创建玩家实例:
继续创造随机敌人。 如果你需要创建,每n个循环就有一个螺丝钉(即敌人()), 您可以创建在该间隔内激活的标志。 你可以用一个变量'count'来决定这一点。 初始值可以是0,然后在每个循环中增加1。 (例如:如果你想让一个敌人每5个循环产卵一次,用5替换n。)
也就是说,在屏幕的任意位置生成一个敌人,并让他们向下移动。 0.1只是一个采样速度。在
现在,到循环部分。。。 for event循环应该有KEYDOWN和KEYUP检查,以确保单次按键。 这里,Player1是Player类实例的名称。在
添加检查以确保播放机不会离开屏幕。
玩家的动作现在完成了,符合游戏的要求。在
调用玩家、敌人的update()函数并翻转屏幕。在
现在,添加碰撞检查以完成游戏。 此外,您可以删除已从屏幕中传递出去的实例以节省内存。在
相关问题 更多 >
编程相关推荐