Hi Im getting this error : "SyntaxError: Invalid Syntax"
& C:/Users/unhackerguard/AppData/Local/Programs/Python/Python39/python.exe "c:/Users/unhackerguard/Documents/Alien invasion/alien_invasion.py"
File "<stdin>", line 1
& C:/Users/unhackerguard/AppData/Local/Programs/Python/Python39/python.exe
"c:/Users/unhackerguard/Documents/Alien invasion/alien_invasion.py"
(there is a carrot under the &) when Y am trying to my code, me and friend have to debug with no solution in site and tried to google to the best of my ability.
import sys
import pygame
# file imports
from settings import Settings
from ship import Ship
class AlienInvasion:
"""Overall class to manage game assets and behavior"""
def __init__(self):
"""Initialize the game, and create game resoures"""
pygame.init()
self.settings= Settings()
self.screen= pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship= Ship(self)
# Set Background color.
self.bg_color= (230,230,230)
def run_game(self):
"""Start the main loop for the game"""
while True:
self._check_events
self.ship.update
self._update_screen
def _check_events(self):
# responds to keypresses and mouse events.
for event in pygame.event.get():
if event.type== pygame.QUIT:
sys.exit()
elif event.type== pygame.KEYDOWN:
if event.key== pygame.K_RIGHT:
self.ship.moving_right= True
elif event.key== pygame.K_LEFT:
self.ship.moving_left= True
elif event.type== pygame.KEYUP:
if event.key== pygame.K_RIGHT:
self.ship.moving_right= False
elif event.type== pygame.K_LEFT:
self.ship.moving_left= False
print(event)
def _update_screen(self):
# Redraw the screen during each pass though the loop
self.screen.fill(self.bg_color)
self.ship.blitme()
"""update images on the screen, and flip to the new screen"""
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()```
```import pygame
class Ship:
""" a class to manage ship."""
def __init__(self, ai_game):
"""initialize the ship and set its starting positition."""
self.screen= ai_game.screen
self.screen_rect= ai_game.screen.get_rect()
#load the ship image and get its rect.
self.image= pygame.image.load('C:/Users/unhackerguard/AppData/Local/Programs/Python/Python39/Lib/site-packages/pygame/examples/data/ship.bmp')
self.rect= self.image.get_rect()
# start each new ship at the bottom center of the screen.
self.rect.midbottom= self.screen_rect.midbottom
#movent flag
self.moving_right= False
self.moving_left= False
def update(self):
"""update the ships posotion based on the movent flag"""
if self.moving_right:
self.rect.x+= 1
if self.moving_left:
self.rect.x-= 1
def blitme(self):
"""draw the ship at its current location"""
self.screen.blit(self.image, self.rect)```
```class Settings:
""" A class to store all the settings for alien invasion"""
def __init__(self):
"""Initialize the game settings"""
# Screen Settings
self.screen_width= 1200
self.screen_height= 800
self.bg_color= (230,230,230)
```
Related
I'm working on the Alien Invasion from "Python Crash Course" by Erick Matthes. I've bogged down on trying to make a ship move across a screen. Most of time, the ship moves as expected. However, after reaching the very right corner of the screen, the ship ceases to react to pressed keys. Pressing a left arrow key on keyboard doesn't move the ship leftwards at all. What's wrong with my code?
alien_invasion.py
"""The main module of the Alien Invasion"""
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion():
"""A class storing and managing all game's functionality."""
def __init__(self):
"""Initialize essential settings."""
self.settings = Settings()
self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
self.settings.window_width = self.screen.get_rect().width
self.settings.window_height = self.screen.get_rect().height
pygame.display.set_caption(self.settings.game_title)
self.ship = Ship(self)
self._run_game()
def _end_game(self):
"""Close the game's window."""
pygame.quit()
sys.exit()
def _check_events(self):
"""Check events and react to them."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._end_game()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_keydown_events(self, event):
"""Detect pressed keys and react accordingly."""
if event.key == pygame.K_q:
self._end_game()
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
if event.key == pygame.K_LEFT:
self.ship.moving_left = True
def _check_keyup_events(self, event):
"""Detect released keys and react accordingly."""
if event.key == pygame.K_RIGHT:
self.ship_moving_right = False
if event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _update_screen(self):
"""Draw the most recent surface on the screen."""
self.screen.fill(self.settings.background_colour)
self.ship.update()
self.ship.blitme()
pygame.display.flip()
def _run_game(self):
"""Start a new game"""
while True:
#Main loop
self._check_events()
self._update_screen()
ai = AlienInvasion()
ship.py
"""A module containing a Ship class"""
import pygame
class Ship():
"""A simple attempt to represent a ship."""
def __init__(self, ai):
"""Initialize a ship's settings."""
self.ai = ai
self.screen = self.ai.screen
self.image = pygame.image.load('ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = self.screen.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
#Motions' attributes
self.moving_right = False
self.moving_left = False
self.x = float(self.rect.x)
self.speed = self.ai.settings.ship_speed
def blitme(self):
"""Draw a ship on the screen."""
self.screen.blit(self.image, self.rect)
def update(self):
"""Update a ship's position on the screen."""
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.speed
if self.moving_left and self.rect.left > 0:
self.x -= self.speed
self.rect.x = self.x
settings.py
"""Module containing a Settings class"""
class Settings():
"""A module managing all game's essential settings."""
def __init__(self):
"""Initialize settings."""
self.background_colour = (230, 230, 230)
self.game_title = 'Alien Invasion'
self.window_width = 1200
self.window_height = 600
self.window_size = (self.window_width, self.window_height)
#Ship's settings
self.ship_speed = 1.5
The ship won't move left, which means it's probably stuck moving right. That points to an issue in releasing the movement to the right, which happens in _check_keydown_events():
def _check_keyup_events(self, event):
"""Detect released keys and react accordingly."""
if event.key == pygame.K_RIGHT:
self.ship_moving_right = False
if event.key == pygame.K_LEFT:
self.ship.moving_left = False
Here's the problematic line:
self.ship_moving_right = False
This should be self.ship.moving_right, not self.ship_moving_right. The correct version finds the ship attribute of the game, and sets the ship's moving_right attribute to False. The incorrect version creates a new game attribute ship_moving_right, and sets it to False; it never changes the value of self.ship.moving_right. So, the ship tries to move right for the rest of the game. This is a great example of how one character can produce no Python errors, but has a significant impact on the overall behavior of the game.
I am learning Python from the book, "PYTHON CRASH COURSE: A Hands-On, Project-Based Introduction to Programming", 2E.
In that while making game, I am getting the error
Traceback (most recent call last):
File "d:\BOOKS\python\my-projects\AlienInvasion\tempCodeRunnerFile.py", line 69, in <module>
alinv = AlienInvasion()
File "d:\BOOKS\python\my-projects\AlienInvasion\tempCodeRunnerFile.py", line 22, in __init__
self.ship = Ship(self.screen)
File "d:\BOOKS\python\my-projects\AlienInvasion\ship.py", line 10, in __init__
self.screen = alinv_game.screen
AttributeError: 'pygame.Surface' object has no attribute 'screen'
My Code is:
AlienInvasion.py
# Importing modules
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
'''Class to manage game assets and behavior'''
def __init__(self):
'''Constructor to initialize the game and its assets'''
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self.screen)
def run_game(self):
'''Starts the main loop for the game'''
while True:
self._check_events()
self.ship.update()
self._update_screen()
def _check_events(self):
'''Watch for the keyboard and mouse events'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_keydown_events(self, event):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_ESCAPE:
sys.exit()
def _check_keyup_events(self, event):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _update_screen(self):
'''Redraw the screen during each pass of the loop'''
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
'''Make the most recently drawn screen visible'''
pygame.display.flip()
if __name__ == '__main__':
'''Make a game instance, and run the game'''
alinv = AlienInvasion()
alinv.run_game()
ship.py
import pygame
class Ship:
'''A class to manage the ship'''
def __init__(self, alinv_game):
'''Initialize the ship and set its starting position'''
self.screen = alinv_game.screen
self.settings = alinv_game.settings
self.screen_rect = alinv_game.screen.get_rect()
'''Load the ship image and get its rect'''
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
'''Start each new ship at the bottom-center of the screen'''
self.rect.midbottom = self.screen_rect.midbottom
'''Store a decimal value for ship's horizontal position'''
self.x = float(self.rect.x)
'''Movement Flag'''
self.moving_right = False
self.moving_left = False
def update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.x -= self.settings.ship_speed
'''Update rect obj from self.x'''
self.rect.x = self.x
def blitme(self):
'''Draw the ship at its current location.'''
self.screen.blit(self.image, self.rect)
In the update method of class Ship, I Implemented two separate blocks to allow ship.rect.x value
to be increased and then decreased when both left and right
arrow keys are pressed. Otherwise, the self.moving_right will
have more priority if 'elif' is implemented.
settings.py
class Settings:
'''A class to store all settings for Alien Invasion Game.'''
def __init__(self):
'''Initialize the game's settings'''
# Screen Settings:
self.screen_width = 1280
self.screen_height = 720
self.bg_color = (230, 230, 230)
# Ship Settings:
self.ship_speed = 1.5
I think the error should be with the screen declaration because I think Pygame.Surface do not have 'screen' attribute but we can though get it by get_rect method. Kindly help me finding the bug. I am not able to solve the issue.
I believe you meant to make the line self.ship = Ship(self.screen) say self.ship = Ship(self). That way the Ship object can access all of the attributes of the AlienInvasion object, instead of just it's screen attribute (and that attribute doesn't have a screen attribute, thus the error).
I just get the general "finished with exit code 0" Not sure why its not printing the screen anymore. What would cause this?
If anyone has any input as to why this would be, i'd very much appreciate it so i can move forward & finish the project!
From what ive read, its hard to go on without knowing what actually is causing the "none-error"
import sys
import pygame
from settings import Settings
from ship import Ship
class Alieninvasion:
"""overall class to manage game assets & behaviors"""
def __init__(self):
"""initialize the game & create game resources"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
self.screen = pygame.display.set_mode((1000, 600)) # the self.screen portion makes it available in all methods in the class
pygame.display.set_caption("Alien Invasion!!!") # the self.settings & self.screen can possibly replace the
# screen & bg_color that doesn't include the settings syntax
self.ship = Ship(self)
# set the background color
self.bg_color = (230, 230, 230)
def run_game(self):
"""starting the main loop for the game"""
while True:
self._check_events()
self.update_screen()
# redraw the screen during each pass through the loop
self.screen.fill(self.bg_color)
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
def _check_events(self):
"""responds to keypresses & mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT():
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key ==pygame.K_RIGHT:
# move the ship to the right
self.ship.rect.x += 1
# makes the most recently drawn screen visible. Continually updates the display to show new game position elements and hide old ones.
pygame.display.flip()
def update_screen(self):
"""update images on the screen & flip to a new screen"""
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
pygame.display.flip()
if __name__ == 'main':
# make a game instance and run the game.
ai = Alieninvasion()
ai.run_game()
"""the run_game as part of the if block ensures it only runs if the file is called directly"""
I am using a book called Python Crash Course by Eric Matthes. A part of the book deals with python code projects and I started coding for an Alien Invasion Game. I attached the code written so far for the game to work but whenever I run the code, the spaceship does not move regardless of whether I press my keyboard's right or left key. I have ran the code several times but my editor doesn't indicate that there are errors. Is there something I need to fix in my code? I would greatly appreciate it if someone knows how to fix this.
Alien_invasion.py code:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
# Set the background color.
self.bg_color = (230, 230, 230)
def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
self.ship.update()
self._update_screen()
# Redraw the screen during each pass through the loop.
def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
# Move the ship to the right.
self.ship.rect.x += 1
def _update_screen(self):
"""Update images on the screen, and flip to the new screen."""
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
Ship.py code:
import pygame
class Ship:
"""A class to manage the ship."""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position."""
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
# Movement flags
self.moving_right = False
self.moving_left = False
def update(self):
"""Update the ship's position based on the movement flag."""
if self.moving_right:
self.rect.x += 1
if self.moving_left:
self.rect.x -= 1
# Start each new ship at the bottom center of the screen.
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
"""Draw the ship at its current location."""
self.screen.blit(self.image, self.rect)
Settings.py code:
class Settings:
"""A class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's settings."""
# Screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
I got the code working, it was a typo error.
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if **event.key** == pygame.K_RIGHT:
self.ship.moving_right = True
elif **event.key** == pygame.K_LEFT:
self.ship.moving_left = True
elif event.type == pygame.KEYUP:
if **event.key** == pygame.K_RIGHT:
self.ship.moving_right = False
elif **event.key** == pygame.K_LEFT:
self.ship.moving_left = False
Earlier I coded event.type instead of event.key
The code is working now, will continue working on the project.
At the moment, I am learning from the Python Crash Course Intro Book By Eric Matthes. I am on the section about making a game with Pygame. The second they added keyup and keydown my code stopped letting me move the ship right and left. Beforehand I was able to move the ship without the additional functions.
I have tried looking on the web. I have tried messing around with the code to fit the situation. I, however, have not tried another IDE. I apologize in advance if this is not properly formatted, I am a noob to this website. Thanks!
===================
alien_invaion.py
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
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")
# Make a ship.
ship = Ship(ai_settings, screen)
# Start the main loop of the game.
while True:
gf.check_events(ship)
ship.update
gf.update_screen(ai_settings, screen, ship)
run_game()
ship.py
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 is 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 ship's center.
# Movement flags
self.moving_right = False
def update(self):
"""Update the ship's position based on the movement flag."""
# Update the ship's center value, not rect.
if self.moving_right:
self.rect.centerx += 1
# Update rect object from self.center.
def blitme(self):
"""Draw the ship at its current location.""
self.screen.blit(self.image, self.rect)
settings.py
class Settings():
"""A class to store all settings for Alien Invasion"""
def __init__(self):
"""Initialize the game's settings."""
# Screen Settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (0, 23, 233)
# Ship settings
game_functions.py
import sys
import pygame
def check_events(ship):
"""respond to keypresss's and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
ship.moving_right = False
def update_screen(ai_settings, screen, ship):
"""Update images on the 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()
No error messages... I expect the ship to be able to move when I hold the left and right keys down and the ship to stop moving when I release said keys.
You missed the parentheses when the update method is called:
ship.update
ship.update()