我正在pygame中制作一个潜艇游戏,我试图让我的潜艇发射子弹。我试过我在另一个pygame项目中使用的代码,但它在这个项目中不起作用。编译器不会给出任何错误,但当我按下空格键时,它不会射击。我试图找出一个错误,但我找不到。我也试着浏览Stack Overflow,但没有找到我想要的答案。这是代码:
import pygame
pygame.init()
run = True
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption('Podmornca')
desno = pygame.image.load('podmornicaD.png')
levo = pygame.image.load('podmornica.png')
ozadje = pygame.image.load('ozadje.png')
torpedoD = pygame.image.load('torpedo.png')
torpedoL = pygame.image.load('torpedoL.png')
class podmornica():
def __init__(self, x, y, v):
self.x = x
self.y = y
self.v = v
self.ziv = 100
self.levo = False
self.desno = True
def naris(self):
if self.levo:
screen.blit(levo, (self.x, self.y))
elif self.desno:
screen.blit(desno, (self.x, self.y))
class torpedo():
def __init__(self, x, y, smer):
self.x = x
self.y = y
self.smer = smer
self.v = 5 * smer
def naris(self, screen):
if self.smer < 0:
screen.blit(torpedoD, (self.x, self.y))
else:
screen.blit(torpedoL, (self.x, self.y))
igralec = podmornica(150, 300, 10)
#the list of bullets:
metki = []
def grafika():
screen.blit(ozadje, (0,0))
igralec.naris()
#Here is code for displaying the bullets
for metek in metki:
metek.naris(screen)
pygame.display.flip()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#This piece of code is for moving of bullets:
for metek in metki:
if metek.x < 600 and metek.x > 0:
metek.x += metek.v
else:
metki.pop(metki.index(metek))
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP and igralec.y > 10:
igralec.y -= 3
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and igralec.y < 350:
igralec.y += 3
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
igralec.levo = True
igralec.desno = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
igralec.levo = False
igralec.desno = True
#the trigger for bullet:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
if igralec.levo:
smer = -1
else:
smer = 1
if len(metki) < 5:
metki.append(torpedo(igralec.x, igralec.y, smer))
grafika()
pygame.quit()
事件必须在事件循环中处理。如果你想实现平稳的运动,那么你必须通过pygame.key.get_pressed()
获得关键状态。此外,子弹的移动速度非常快。分别用CCD_ 2和CCD_。例如:
FPS = 60
clock = pygame.time.Clock()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
#the trigger for bullet:
if event.key == pygame.K_SPACE:
if igralec.levo:
smer = -1
else:
smer = 1
if len(metki) < 5:
metki.append(torpedo(igralec.x, igralec.y, smer))
# This piece of code is for moving of bullets:
for metek in metki[:]:
if metek.x < 600 and metek.x > 0:
metek.x += metek.v
else:
metki.remove(metek)
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and igralec.y > 10:
igralec.y -= 3
if keys[pygame.K_DOWN] and igralec.y < 350:
igralec.y += 3
if keys[pygame.K_LEFT]:
igralec.levo = True
igralec.desno = False
if keys[pygame.K_RIGHT]:
igralec.levo = False
igralec.desno = True
grafika()