How to draw a line in pygame that moves up the screen

偶尔善良 提交于 2020-01-25 06:45:25

问题


I have made a python game, and when you press space it shoots a bullet (a line). It is only able to shoot once though. I was wondering how I could make it shoot multiple times?

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)

回答1:


I would create two classes, bullet and bullets and limit the firing rate to a certain time. Try this:

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


来源:https://stackoverflow.com/questions/59554633/how-to-draw-a-line-in-pygame-that-moves-up-the-screen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!