我正在嘗試在遊戲中製作槍支,但遇到麻煩。我無法弄清楚如何在while循環中追加一個矩形,當我點擊空格鍵之類的東西時。它在JavaScript中工作,但body.append()函數在python中不存在,所以我想怎麼做呢?追加一個對象到遊戲循環上按鈕單擊?
在此先感謝
編輯:
我想通了。
import pygame
import sys
class Application(object):
def __init__(self,screen=None):
self.screen = screen
self.fps = 30
self.clock = pygame.time.Clock()
self.buffer()
def buffer(self):
self.char = Character(self.screen)
self.gun = Gun(self.screen)
while 1:
self.key = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if len(self.gun.ammo) <= 10 and self.gun.magazine_count > 0:
self.gun.ammo.append(self.gun.bullet_position(self.char.x+20,self.char.y+10))
elif len(self.gun.ammo) > 10:
self.gun.magazine_count -= 1
if self.gun.magazine_count > 0:
print("reloading")
self.gun.ammo = []
else:
print("out of magazines < press UP arrow to restock >")
if event.key == pygame.K_UP:
if self.gun.magazine_count == 0:
self.gun.magazine_count = 4
self.screen.fill((0,0,0))
self.char.draw_char()
for x in range(len(self.gun.ammo)):
self.gun.bullet_create(self.gun.ammo[x],5)
self.gun.ammo[x][0] += 25
pygame.display.update()
self.clock.tick(self.fps)
pygame.quit()
sys.exit()
quit()
class Character(object):
def __init__(self,screen):
self.screen = screen
self.w, self.h = 20, 20
self.x, self.y = 0, int(self.screen.get_height()/2-self.h)
def draw_char(self):
player = pygame.draw.rect(self.screen,(255,0,0),[self.x,self.y,self.w,self.h])
class Gun(object):
def __init__(self,screen):
self.screen = screen
self.magazine_count = 4
self.ammo = []
def bullet_position(self,x,y):
return [x,y]
def bullet_create(self,dimensions,radius):
pygame.draw.circle(self.screen,(255,255,255),(dimensions),radius)
def Main():
pygame.init()
screen = pygame.display.set_mode((500,400))
app = Application(screen)
if __name__ == "__main__":
Main()
您的代碼在哪裏? – furas
我沒有任何這就是爲什麼我要求一些例子 – Micron