python - 如何在pygame中画一条向上移动屏幕的线
问题描述
我做了一个 Python 游戏,当你按下空格键时,它会射出一颗子弹(一条线)。虽然只能拍摄一次。我想知道如何让它多次拍摄?
shotStartX = x + 30
shotStartY = y + 20
shotEndX = x + 30
shotEndY = y
shoot = False
while True:
if event.type == pygame.KEYDOWN:
elif event.key == pygame.K_SPACE:
shoot = True
gameDisplay.fill(blue)
if shoot:
pygame.draw.line(gameDisplay,red,(shotStartX,shotStartY),(shotEndX,shotEndY),5)
shotStartY -= 10
shotEndY -= 10
gameDisplay.blit(rocketImg,(x,y))
pygame.display.update()
clock.tick(30)
解决方案
我会创建两个类,子弹和子弹,并将射击速度限制在某个时间。尝试这个:
import pygame
import time
# define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
W = 480
H = 720
FPS = 60
BULLET_SPEED = 5
BULLET_FIRING_RATE = 0.5 # seconds
class bullet:
def __init__(s, x, y): # x, y = starting point
s.x = x
s.y = y
s.dead = False
def draw(s):
global DS
global WHITE
pygame.draw.circle(DS, WHITE, (s.x, s.y), 10)
def move(s):
global BULLET_SPEED
s.y -= BULLET_SPEED
if s.y <= 0:
s.dead = True
class bullets:
def __init__(s):
s.container = []
s.lastBulletTime = time.time() -BULLET_FIRING_RATE
def add(s, x, y):
global BULLET_FIRING_RATE
now = time.time()
if now - s.lastBulletTime >= BULLET_FIRING_RATE:
s.container.append(bullet(x, y))
s.lastBulletTime = now
def do(s):
deadBullets = []
for b in s.container:
b.draw()
b.move()
if b.dead: deadBullets.append(b)
for db in deadBullets:
s.container.remove(db)
pygame.init()
DS = pygame.display.set_mode((W, H))
CLOCK = pygame.time.Clock()
BULLETS = bullets()
# press escape to exit
while True:
e = pygame.event.get()
if pygame.key.get_pressed()[pygame.K_ESCAPE]: break
mx, my = pygame.mouse.get_pos()
mb = pygame.mouse.get_pressed()
if mb[0]:
BULLETS.add(mx, my)
DS.fill(BLACK)
BULLETS.do()
pygame.draw.circle(DS, WHITE, (mx, my), 40)
pygame.display.update()
CLOCK.tick(FPS)
pygame.quit()