Follow the book i have a confused
the book says delete the bullet in bullets copy instead of the group it self
but i try for both two effect ,it really the same??
so what is the difference between these two codes??
for bullet in bullets.copy():
if bullet.rect.y <= 0:
bullets.remove(bullet)
==========================================
for bullet in bullets():
if bullet.rect.y <= 0:
bullets.remove(bullet)
==========================================
here's the whole 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.rect=p.Rect((0,0),(setting.bullet_w,setting.bullet_h))
self.rect.center=self.screen_center
self.rect.bottom=self.screen_rect.bottom
self.color=setting.bullet_c
self.speed=setting.bullet_s
self.y=float(self.rect.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.rect.y=self.y
def draw(self,setting):
p.draw.rect(setting.screen,self.color,self.rect)
def bullet_blit(self,bullets,setting):
for bullet in bullets.sprites():
bullet.draw(setting)
bullet.move()
for bullet in bullets.copy(): **<-- for bullet in bullets: really same effect**
if bullet.rect.y <= 0:
bullets.remove(bullet)
print(len(bullets))
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)
p.display.flip()
game()