With the help of some person now I can press key to shoot bullet in Pygame but I have met another new issue. I define this in class Bullet:
def move(self):
self.y -= self.speed
self.bullet.y=self.y
def draw(self,setting):
p.draw.rect(setting.screen,self.color,self.bullet)
def bullet_blit(self,bullets,setting):
for bullet in bullets.sprites():
p.draw.rect(setting.screen,self.color,self.bullet)
self.y -= self.speed
self.bullet.y=self.y
Finally when I just use the code bullet.bullet_blit(bullets,setting)
it will only one bullet when I press the key.
Instead I use
for bullet in bullets.sprites():
bullet.draw(setting)
bullet.move()
It worked correctly. I don't know why. They are the same, but their effect is not the same. Here's the code:
#! /usr/bin/python
import pygame as p
import sys
class Setting():
def __init__(self,width,height):
self.w=width
self.h=height
self.flag=p.RESIZABLE
self.color=(255,255,255)
self.speed=1
self.screen=p.display.set_mode((self.w,self.h),self.flag)
p.display.set_caption("Bullet")
self.bullet_s=1
self.bullet_w=5
self.bullet_h=30
self.bullet_c=(0,0,0)
class Bullet(p.sprite.Sprite):
def __init__(self,setting):
super().__init__()
self.screen_rect=setting.screen.get_rect()
self.screen_center=self.screen_rect.center
self.bullet=p.Rect((0,0),(setting.bullet_w,setting.bullet_h))
self.bullet.center=self.screen_center
self.bullet.bottom=self.screen_rect.bottom
self.color=setting.bullet_c
self.speed=setting.bullet_s
self.y=float(self.bullet.centery)
def bullet_check(self,bullets,setting):
for event in p.event.get():
if event.type == p.QUIT:
sys.exit()
elif event.type == p.KEYDOWN:
if event.key ==p.K_SPACE:
bullets.add(Bullet(setting))
def move(self):
self.y -= self.speed
self.bullet.y=self.y
def draw(self,setting):
p.draw.rect(setting.screen,self.color,self.bullet)
def bullet_blit(self,bullets,setting):
for bullet in bullets.sprites():
p.draw.rect(setting.screen,self.color,self.bullet)
self.y -= self.speed
self.bullet.y=self.y
def game():
p.init()
setting=Setting(1200,800)
bullet=Bullet(setting)
bullets=p.sprite.Group()
while True:
bullet.bullet_check(bullets,setting)
setting.screen.fill((255,0,0))
bullet.bullet_blit(bullets,setting) <—--this cant create many bullets,only one bullet
# for bullet in bullets.sprites():
# bullet.draw(setting)
# bullet.move()
p.display.flip()
game()