我正在尝试在pygame中制作代码来拍摄子弹,但它没有工作,因为它给出了索引错误。这是我的代码。我究竟做错了什么?感谢。
while fire ==True:
print 'FIRE'
for bullet in bullets[:]:
nowtime=pygame.time.get_ticks()
if (nowtime-bullets[3])>1000:
bullets.pop(bullets.index(bullet))
if fire and not oldfire:
bullets.append([int(x_coord),int(y_coord),angle,pygame.time.get_ticks()])
oldfire=fire
screen.fill(white)
for bullet in bullets:
bx=bullet[0]
by=bullet[1]
ba=bullet[2]
bt=bullet[3]
rads=-(ba/360)*2*math.pi
x=int(bx+(blsp*bvel*0.36*math.cos(rads)))
y=int(by+(blsp*bvel*0.36*math.sin(rads)))
print x,y,ba,bt
pygame.draw.circle(screen,green,[x,y],8)
bullet[0]=x
bullet[1]=y
pygame.quit()
更新1
这是我的整个代码,可能会有所帮助。谢谢!
import pygame,math
from pygame import *
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
arrow=pygame.image.load('plane.png')
explosion=pygame.image.load('explosion.png')
explosion=pygame.transform.scale(explosion,(300,200))
arrow=pygame.transform.scale(arrow,(150,50))
pygame.init()
size=[1100,900]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
done=False
fire=False
clock=pygame.time.Clock()
pygame.mouse.set_visible(1)
x_speed=0
y_speed=0
x_coord=10
y_coord=10
bullets=[]
oldfire=[]
sp=9
angle=0
blsp=1
bvel=30
def pri():
rotarrow=pygame.transform.rotate(arrow, angle)
rotrec=rotarrow.get_rect()
rotrec.center=(x_coord,y_coord)
screen.blit(rotarrow,rotrec)
pygame.display.flip()
clock.tick(60)
def explode():
screen.fill([255,255,255])
screen.blit(explosion,(x_coord-150,700))
pygame.display.flip()
pygame.quit()
while done==False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
angle=angle+1
if event.key == pygame.K_RIGHT:
angle=angle-1
if event.key == pygame.K_UP:
sp=18
if event.key == pygame.K_DOWN:
sp=6
if event.key == pygame.K_SPACE:
fire=True
y_coord += (math.sin(-angle / (180/math.pi)) * sp)
x_coord += (math.cos(-angle / (180/math.pi)) * sp)
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
sp=9
if event.key == pygame.K_DOWN:
sp=9
y_coord+=5#gravity
if x_coord<80:
x_coord=80
if x_coord>size[0]-80:
x_coord=size[0]-80
if y_coord < 80:
y_coord=80
if y_coord>size[0]-80:
explode()
break
screen.fill(white)
pri()
while fire ==True:
print 'FIRE'
for bullet in bullets[:]:
nowtime=pygame.time.get_ticks()
if (nowtime-bullets[2])>1000:
bullets.pop(bullets.index(bullet))
if fire and not oldfire:
bullets.append([int(x_coord),int(y_coord),angle,pygame.time.get_ticks()])
oldfire=fire
screen.fill(white)
for bullet in bullets:
bx=bullet[0]
by=bullet[1]
ba=bullet[2]
bt=bullet[3]
rads=-(ba/360)*2*math.pi
x=int(bx+(blsp*bvel*0.36*math.cos(rads)))
y=int(by+(blsp*bvel*0.36*math.sin(rads)))
print x,y,ba,bt
pygame.draw.circle(screen,green,[x,y],8)
bullet[0]=x
bullet[1]=y
pygame.quit()
答案 0 :(得分:0)
虽然特定的堆栈跟踪会有所帮助,但您的问题可能源于此行:
if (nowtime-bullets[3])>1000:
我认为您的意思是检查项目符号数组的第四个参数(稍后您引用为bt
)。但是,那将是bullet[3]
,你有bullets[3]
,它正在检查第四个项目符号。如果您在阵列中没有那么多项目符号,则会产生索引错误。