(Python Crash Course) Alien Invasion Project - python

I would very appreciate if someone could tell me how to fix this error:
AttributeError: 'Ship' object has no attribute 'bullet_width'
I am starting to learn Python, and I'm not sure what the solution to this would be. This always happens when I press the space bar.
Below are the modules in this project:
alien_invasion.py:
import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
screen = pygame.display.set_mode((1100, 600))
pygame.display.set_caption("Alien Invasion")
bg_color = (230, 230, 230)
ship = Ship(screen, ai_settings)
bullets = Group()
while True:
gf.check_events(ship, screen, ai_settings, bullets)
ship.update()
bullets.update()
gf.update_screen(ai_settings, screen, ship, bullets)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(ai_settings.bg_color)
ship.blitme()
screen.fill(bg_color)
run_game()
ship.py:
import pygame
class Ship():
def __init__(self, screen, ai_settings):
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load('images/spaceship.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
self.center = float(self.rect.centerx)
self.moving_right = False
self.moving_left = False
def update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
self.rect.centerx = self.center
def blitme(self):
self.screen.blit(self.image, self.rect)
bullet.py:
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, ai_settings, screen, ship):
super(Bullet, self).__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,
ai_settings.bullet_height)
self.rect.centerx = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor
def update(self):
self.y -= self.speed_factor
self.rect.y = self.y
def draw_bullet(self):
pygame.draw.rect(self.screen, self.color, self.rect)
game_functions.py
import sys
import pygame
from bullet import Bullet
def check_keydown_events(event, ai_settings, screen, ship, bullets):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def check_keyup_events(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai_settings, screen, ship, bullets):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
def update_screen(ai_settings, screen, ship, bullets):
screen.fill(ai_settings.bg_color)
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
pygame.display.flip()
settings.py:
class Settings():
def __init__(self):
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 1.5
self.bullet_speed_factor = 1
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = 60, 60, 60

The order of the arguments is wrong when you call check_events:
check_events(ship, screen, ai_settings, bullets)
check_events(ai_settings, screen, ship, bullets)
The order of the arguments matters, except of Keyword Arguments.

Related

Creating a game in Pygame encountered an IndentationError error

I ran into an indentation problem, but I rechecked my code and couldn't find the error, please help
Game:
import pygame, controls
from gun import Gun
from pygame.sprite import Group
from stats import Stats
def run():
pygame.init()
screen = pygame.display.set_mode((700, 600))
pygame.display.set_caption('Game1')
bg_color = (0, 0, 0)
gun = Gun(screen)
bullets = Group()
inos = Group()
controls.create_army(screen, inos)
stats = Stats()
while True:
controls.events(screen, gun, bullets)
gun.update_gun()
controls.update(bg_color, screen, gun, inos, bullets)
controls.update_bullets(inos, bullets)
controls.update_inos(stats, screen, gun, inos, bullets)
run()
Gun:
import pygame
class Gun():
def __init__(self, screen):
self.screen = screen
self.image = pygame.image.load(r"C:\Users\ralph\Downloads\Python\Game\Image\t2.png")
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.center = float(self.rect.centerx)
self.rect.bottom = self.screen_rect.bottom
self.mright = False
self.mleft = False
def output(self):
self.screen.blit(self.image, self.rect)
def update_gun(self):
if self.mright and self.rect.right < self.screen_rect.right:
self.center += 1.5
if self.mleft and self.rect.left > 0:
self.center -= 1.5
self.rect.centerx = self.center
def create_gun(self):
self.center = self.screen_rect.centerx
Bullet:
import pygame
class Bullet(pygame.sprite.Sprite):
def __init__(self, screen, gun):
super(Bullet, self).__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, 3, 12)
self.color = 150, 150, 150
self.speed = 1.5
self.rect.centerx = gun.rect.centerx
self.rect.top = gun.rect.top
self.y = float(self.rect.y)
def update(self):
self.y -= self.speed
self.rect.y = self.y
def draw_bullet(self):
pygame.draw.rect(self.screen, self.color, self.rect)
Control:
import pygame
import sys
from bullet import Bullet
from ino import Ino
import time
def events(screen, gun, bullets):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
gun.mright = True
elif event.key == pygame.K_a:
gun.mleft = True
elif event.key == pygame.K_SPACE:
new_bullet = Bullet(screen, gun)
bullets.add(new_bullet)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_d:
gun.mright = False
elif event.key == pygame.K_a:
gun.mleft = False
def update(bg_color, screen, gun, inos, bullets):
screen.fill(bg_color)
for bullet in bullets.sprites():
bullet.draw_bullet()
gun.output()
inos.draw(screen)
pygame.display.flip()
def update_bullets(inos, bullets):
bullets.update()
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
collisions = pygame.sprite.groupcollide(bullets, inos, True, True)
def gun_kill(stats, screen, gun, inos, bullets):
stats.guns_left -= 1
inos.empty()
bullets.empty()
create_army(screen, inos)
gun.create_gun()
time.sleep(2)
def update_inos(stats, screen, gun, inos, bullets):
inos.update()
if pygame.sprite.spritecollideany(gun, inos):
gun_kill(stats, screen, gun, inos, bullets)
def create_army(screen, inos):
ino = Ino(screen)
ino_width = ino.rect.width
number_ino_x = int((700 - 2 * ino_width) / ino_width)
ino_height = ino.rect.height
number_ino_y = int((800 - 300 - 2 * ino_height) / ino_height)
for row_number in range(number_ino_y):
for ino_number in range(number_ino_x):
ino = Ino(screen)
ino.x = ino_width + (ino_width * ino_number)
ino.y = ino_height + (ino_height * row_number)
ino.rect.x = ino.x
ino.rect.y = ino.rect.height + (ino.rect.height * row_number)
inos.add(ino)
Army:
import pygame
class Ino(pygame.sprite.Sprite):
def __init__(self, screen):
super(Ino, self).__init__()
self.screen = screen
self.image = pygame.image.load(r'C:\Users\ralph\Downloads\Python\Game\Image\solder.png')
self.rect = self.image.get_rect()
self.rect.x = self.rect.width
self.rect.y = self.rect.height
self.x = float(self.rect.x)
self.y = float(self.rect.y)
def draw(self):
self.screen.blit(self.image, self.rect)
def update(self):
self.y += 0.05
self.rect.y = self.y
Stat
class Stats():
def __init__(self):
def reset_stats(self):
self.guns_left = 2
Error:
Traceback (most recent call last):
File "C:\Users\ralph\Downloads\Python\Game\game1.py", line 4, in
from stats import Stats
File "C:\Users\ralph\Downloads\Python\Game\stats.py", line 7
def reset_stats(self):
^
IndentationError: expected an indented block after function definition on line 3
I couldn't find the cause of the error but I believe the whole code is correct

Pygame keyup/keydown sometimes works [duplicate]

This question already has an answer here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Closed 2 years ago.
I am working on the Alien Invasion game from Python Crash Course.pdf
import sys
import pygame
def check_events(ship):
"""respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ship)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
def check_keydown_events(event, ship):
"""respond to keypresses."""
if event.key == pygame.K_d:
ship.moving_right = True
if event.key == pygame.K_a:
ship.moving_left = True
def check_keyup_events(event, ship):
"""respond to key releases."""
if event.key == pygame.K_d:
ship.moving_right = False
if event.key == pygame.K_a:
ship.moving_left = False
# Move the ship to the right.
#ship.rect.centerx += 1
def update_screen(ai_settings, screen, ship):
"""update images on screen and flip to the new screen"""
#redraw the screen during each pass through the loop.
screen.fill(ai_settings.bg_color)
ship.blitme()
#make the most recently drawn screen visible.
pygame.display.flip()
#alien invasion
import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
#intialize pygame, settings , and screen object
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Make a Ship
ship = Ship(ai_settings, screen)
#set the background color
#bg_color = (52, 86, 139)
# start the main loop for the game
while True:
gf.check_events(ship)
ship.update()
gf.update_screen(ai_settings, screen, ship)
#watch for keyboard and mouse events.
#redraw the screen during each pass through the loop.
screen.fill(ai_settings.bg_color)
ship.blitme()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#make the most recently drawn screen visible
pygame.display.flip()
run_game()
import pygame
class Ship():
def __init__(self, ai_settings, screen):
"""initialize the ship and set its starting position."""
self.screen = screen
self.ai_settings = ai_settings
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
# Start each new ship at the bottom center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#store a decimal value for the ships center
self.center = float(self.rect.centerx)
#Movement flags
self.moving_right = False
self.moving_left = False
def update(self):
"""update the ships position based on the movement flag"""
# Update the ships center value, not the rect.
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
# Update rect object from self.center
self.rect.centerx = self.center
if self.moving_right:
self.rect.centerx += 1
if self.moving_left:
self.rect.centerx -= 1
def blitme(self):
"""Draw the ship at its current location."""
# pygame.draw.rect(self, (255,0,0), (100, 100), 36)
self.screen.blit(self.image, self.rect)
class Settings():
"""A class to store all settings for Alien Invasion"""
def __init__(self):
"""intialize the games settings."""
# Screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (52, 86, 139)
#ship settings
self.ship_speed_factor = 1.5
This is the code from my game_functions class
When I press 'D', 85% of the time nothing happens. Sometimes it non stop slides to the left or right, either or. Same thing when pressing "A".
Why is this happening? What am I doing wrong in this code? This code is fairly basic I just want it to move left or right.
Their is no code that turns self.moving_right and self.moving_left to
false to stop them from moving.
I would use something like this:
if event.type == pygame.KEYUP :
if event.key == pygame.K_RIGHT:
self.moving_right = False
elif event.key == pygame.K_ESCAPE :
self.moving_left = False
Here's the documantation:
https://www.pygame.org/docs/ref/key.html

Alien Invasion Python Crash Course | After firing bullets, the ship starts slowing down

There's no error in the code. I've fixed lots of errors before but it doesn't pop up any error. I've also checked the game_functions to see if it had something do to with that, but everything seems to be perfectly fine.
The error is that when I click the spacebar to shoot the bullets, the ship starts slowing down.
main code (alien_invasion.py):
import sys
import game_functions as gf
import pygame
from settings import Settings
from ship import Ship
from pygame.sprite import Group
def run_game():
# Initialize pygame, settings, and screen object.
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
screen.fill(ai_settings.bg_color)
# Make a ship.
ship = Ship(ai_settings, screen)
bullets = Group()
# Background color
bg_color = (230, 230, 230)
while True:
gf.check_events(ai_settings, screen, ship, bullets)
gf.update_screen(ai_settings, bullets, screen, ship)
ship.update(ai_settings)
bullets.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(ai_settings.bg_color)
ship.blitme(screen)
pygame.display.flip()
run_game()
Bullet code (bullet.py):
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, ai_settings, screen, ship):
super().__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.ship_speed_factor = ai_settings.bullet_speed_factor
def update(self):
self.y -= self.ship_speed_factor
self.rect.y = self.y
def draw_bullet(self):
pygame.draw.rect(self.screen, self.color, self.rect)
game_functions.py:
import pygame
from bullet import Bullet
def check_keydown_events(event, ship, ai_settings, screen, bullets):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def check_keyup_events(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai_settings, screen, ship, bullets):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event,ship, ai_settings, screen, bullets)
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def update_screen(ai_settings, bullets, screen, ship):
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme(screen)
pygame.display.flip()
settings code (settings.py):
class Settings():
def __init__(self):
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 10
self.bullet_speed_factor = 1
self.bullet_width = 3
self.bullet_height = 12
self.bullet_color = (60, 60, 60)
self.bullet_limit = 5
ship code (ship.py):
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
def __init__(self, ai_settings, screen):
super(Ship, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load(r'C:\Users\user\Desktop\alien invasion\ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
self.moving_right = False
self.moving_left = False
self.center = float(self.rect.centerx)
self.center += self.ai_settings.ship_speed_factor
def update(self, ai_settings):
self.ai_settings = ai_settings
if self.moving_right and self.rect.right < self.screen_rect.right:
self.rect.centerx += 1
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
self.rect.centerx -= 1
def blitme(self, screen):
self.screen.blit(self.image, self.rect)
Any help I would really appreciate it thank you!
The update_screen function looks suspicious here - redrawing the ship and flipping the display for every bullet is probably not what was intended. Moving those lines outside the loop should help:
def update_screen(ai_settings, bullets, screen, ship):
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme(screen)
pygame.display.flip()

(PythonCrashCourse) Alien Invasion Ship Movement [duplicate]

This question already has an answer here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Closed 2 years ago.
My problem with the code is that the ship's movement is strange; sometimes when I press the left or right arrow key it doesn't move the correct way. Or, the ship doesn't move at all. In this project I have the modules alien.py, alien_invasion.py, bullet.py, button.py, gamefunctions.py, game_stats.py, scoreboard.py, settings.py, and ship.py. However, I will only provide the most relevant ones.
ship.py:
import pygame
class Ship():
def __init__(self, screen, ai_settings):
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load('images/spaceship.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
self.center = float(self.rect.centerx)
self.moving_right = False
self.moving_left = False
def update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
self.rect.centerx = self.center
def blitme(self):
self.screen.blit(self.image, self.rect)
def center_ship(self):
self.center = self.screen_rect.centerx
game_functions.py:
import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep
def check_keydown_events(event, ai_settings, screen, ship, bullets):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
fire_bullet(ai_settings, screen, ship, bullets)
def check_keyup_events(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
alien_invasion.py:
import sys
import pygame
import game_functions as gf
from settings import Settings
from ship import Ship
from pygame.sprite import Group
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
screen = pygame.display.set_mode((1200, 650))
pygame.display.set_caption("Alien Invasion")
while True:
gf.check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets)
if stats.game_active:
ship.update()
gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets)
gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(ai_settings.bg_color)
ship.blitme()
screen.fill(bg_color)
run_game()
The problem is caused by multiple calls to pygame.event.get().
pygame.event.get() get all the messages and remove them from the queuepygame.event.get() get all the messages and remove them from the queue. See the documentation:
This will get all the messages and remove them from the queue. [...]
If pygame.event.get() is called in multiple event loops, only one loop receives the events, but never all loops receive all events. As a result, some events appear to be missed.
Get the events once and use them in multiple loops or pass the list or events to functions and methods where they are handled:
def check_events(event_list, ai_settings, screen, stats, play_button, ship, aliens, bullets):
for event in event_list:
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
def run_game():
# [...]
while True:
event_list = pygame.event.get()
gf.check_events(event_list, ai_settings, screen, stats, play_button, ship, aliens, bullets)
# [...]
for event in event_list :
if event.type == pygame.QUIT:
sys.exit()
# [...]

AttributeError: 'Group' object has no attribute 'update_bullets'

As a beginner, I was trying the "Alien invasion' project in the python crash course a hands-on project-based introduction to programming and got stuck, I was just trying to copy the code but it always get the same feedback:
Traceback (most recent call last):
File "D:/snake/venv/Alien_Invasion/main_game.py", line 29, in <module>
run_game()
File "D:/snake/venv/Alien_Invasion/main_game.py", line 26, in run_game
bullets.update_bullets()
AttributeError: 'Group' object has no attribute 'update_bullets'
and here's my code:
main_game.py
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
import bullet
def run_game():
#初始化游戏并创建一个屏幕对象
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
pygame.display.set_caption("Alien_Invasion")
#创建一艘飞船
ship = Ship(ai_settings, screen)
#创建一个子弹编组
bullets = pygame.sprite.Group()
#游戏主循环
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update_ship()
bullets.update_bullets()
gf.update_screen(ai_settings, screen, ship, bullets)
run_game()
bullet.py
import pygame
class Bullet(pygame.sprite.Sprite):
"""一个对飞船发射的子弹管理的类"""
def __init__(self, ai_settings, screen, ship):
"""在飞船所在位置创建一个子弹对象"""
self.screen = screen
super(Bullet, self).__init__()
#在(0,0)处创建一个表示子弹的矩形,在放置到正确的位置
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,
ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
#存储用小数表示的子弹位置
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor
def update_bullets(self):
"""向上移动子弹"""
#更新浮点数的子弹纵坐标
self.y -= self.speed_factor
#更新子弹纵坐标位置
self.rect.y = self.y
def draw_bullet(self):
"""在屏幕上绘制子弹"""
pygame.draw.rect(screen, self.color, self.rect)
game_functions.py
import sys
import pygame
def check_keydown_event(event, ai_settings, screen, ship, bullets):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
#创建一个子弹,并加入bullets编组
elif event.key == pygame.K_SPACE:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def check_keyup_event(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai_settings, screen, ship, bullets):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_event(ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_event(event, ship)
def update_screen(ai_settings, screen, ship, bullets):
"""更新屏幕上的图像并切换到新屏幕"""
#每次循环时都重新绘制屏幕
screen.fill(ai_settings.bg_color)
#在飞船和外星人后面重绘所有子弹
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
#最近绘制屏幕可见
pygame.display.flip()
there are two other files, but I don't think they are related to this problem.
settings.py
class Settings():
"""存储所有设置的类"""
def __init__(self):
"""初始化屏幕设置"""
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
#飞船速度
self.ship_speed_factor = 1.5
#子弹设置
self.bullet_speed_factor = 1
self.bullet_width = 3
self.bullet_heght = 15
self.bullet_color = 60, 60, 60
ship.py
import pygame
class Ship():
def __init__(self, ai_settings, screen):
self.screen = screen
self.ai_settings = ai_settings
""""加载飞船并获取其外接矩形"""
self.image = pygame.image.load("images/ship.bmp")
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
"""将每艘飞船放在屏幕中央底部"""
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#创建属性center存储坐标小数值
self.center = float(self.rect.centerx)
#飞船移动标志
self.moving_right = False
self.moving_left = False
def update_ship(self):
"""根据移动标志调整飞船位置"""
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
#根据center更新rect.centerx值
self.rect.centerx = self.center
def blitme(self):
"""在指定位置绘制飞船"""
self.screen.blit(self.image, self.rect)
Can someone please tell me what I did wrong here? It would be much appreciated!
In your traceback error it says:
Traceback (most recent call last):
File "D:/snake/venv/Alien_Invasion/main_game.py", line 2, in <module>
from pygame import Group
importError: cannot import name 'Group' from 'pygame' (D:\snake\venv\lib\site-packages\pygame\__init__.py)
Which says there should be this line:
from pygame import Group
on line 2 of your main_game.py module. However in the code you have included, that is not there:
main_game.py
import pygame
from settings import Settings
from ship import Ship
Are you sure you are showing he correct code?
Ignoring the code and just looking at the error message it shows that you had this line:
from pygame import Group
There is no pygame.Group which is why you are getting the error telling you that. I think you are looking for pygame.sprite.Group
Edit
Now that we have the right code and the right question :-)
Sprite groups have some built-in methods which can be seen in the docs here. One of these is update() which will then call the update() function in all the sprites in the group. Your problem is that you named your sprite function update_bullets() not just update() and then you tried to call update_bullets() on the group and the group does not have that method.
So to fix your code you have to rename your Bullet method to just update() and then call the sprite.Group method update() to have it called on all the bullets in the group.
You have the same issue with your draw_bullet() method but you worked around it by iterating over the group and calling your method. That works, but you should correct it to take advantage of the builtin group method. You need to change it to just draw() and then you can call it on all the bullets by just calling bullets.draw(). As I said, in your code now, because you are not using the name that the sprite.Group knows how to find, you are iterating over the group. If you rename it, you can then replace this:
for bullet in bullets.sprites():
bullet.draw_bullet()
with just:
bullets.draw()

Categories