我正在制作一个小的2d游戏,目标是尽可能多地吃粪便,但是我在随机的时间里很难产生粪便。我希望粪便在敌人的y位置产卵,然后像rpg一样向前射击
import pygame
from pygame.locals import *
from numpy.random import rand
pygame.init()
pygame.display.set_caption('STINKY BEETLE')
screen_width = 800
screen_height = 600
game_running = True
pl_x = int(screen_width/10)
pl_y = int(screen_height/2)
pl_width = 80
pl_height = 40
pl_vel = 30
en_width = 80
en_height = 40
en_x = screen_width - screen_width/10 - en_width
en_y = int(screen_height/2)
en_yvel = -10
po_width = 50
po_height = 30
po_x = 720
po_y = en_y
po_xvel = 15
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
while game_running:
clock.tick(10)
po_delay = rand(1)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
if event.type == MOUSEBUTTONDOWN:
if event.button == 4 and pl_y > pl_vel:
pl_y -= pl_vel
elif event.button == 5 and pl_y < screen_height - pl_width:
pl_y += pl_vel
if po_delay < 0.01:
poop(po_x, po_y)
en_y += en_yvel
if en_y <= 0 or en_y >= screen_height - en_height:
en_yvel =- en_yvel
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (105, 255, 125), (pl_x, pl_y, pl_width, pl_height))
pygame.display.update()
pygame.draw.rect(screen, (255, 125, 115), (en_x, en_y, en_width, en_height))
pygame.display.update()
pygame.quit()
你可以使用pygame的时间模块随机繁殖敌人。我假设您正在为此使用OOP。首先,当初始化敌人类时,记录它第一次生成的时间
然后你可以计算出自从你的敌人上次开火以来经过的时间。您可以在主游戏循环中执行类似
now = time.time()
的操作,并获得差异现在,您可以使用此
time_passed
作为您可能创建的spawn_enemy()
函数的参数,该函数可能如下所示:将此函数调用为
spawn(time_passed)
如果你想管理多个“便便”,那么你必须创建一个列表。每个“poop”都是一个对象(aclass的实例)
板条箱一个类
Poop
,它可以update
位置和draw
船尾:使用计时器事件生成粪便。使用^{} 重复创建^{} 。时间以毫秒为单位设置。通过^{} 设置随机时间,例如,将时间设置在0.5到4秒之间(当然,您可以选择自己的时间间隔):
注意,在pygame中可以定义客户事件。每个事件都需要一个唯一的id。用户事件的id必须从
pygame.USEREVENT
开始。在本例中pygame.USEREVENT+1
是计时器事件的事件id,该事件生成POOP当事件在事件循环中发生时,创建一个新的poop,并设置一个新的随机时间:
在循环中更改粪便的位置,如果它们离开左侧的窗口,则将其从列表中删除:
把它们画成一个圈
请参见示例:
相关问题 更多 >
编程相关推荐