【问题标题】:How to draw a line in pygame that moves up the screen如何在pygame中画一条向上移动屏幕的线
【发布时间】:2020-01-02 04:10:42
【问题描述】:

我做了一个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)

【问题讨论】:

  • 我认为问题出在“elif event.key ...”中。它应该是“如果 event.key ...”。除此之外,在拍摄后设置“shoot = False”(我的意思是,在“如果拍摄”段落内)。
  • 不,只是让线条立即消失
  • 啊,我明白了。如果没有整个代码,我无法弄清楚您的实际意图。例如,如果 shotStartX 在您的程序中的某个地方(我的意思是在 while 循环内)从未发生变化,您将在同一位置对同一行进行 blitting,因此即使您一次 blitting 许多行,您也不会看到它。跨度>
  • 什么时候应该拍多次?如果该键被重复按下或按住或?

标签: python pygame


【解决方案1】:

我会创建两个类,子弹和子弹,并将射击速度限制在某个时间。试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多