Python Forum
Rocket will only move in two directions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rocket will only move in two directions
#1
I'm trying to make a simple game where a rocket can move in 4 directions. however currently it only moves left and right even when pressing the up or down keys. Can someone tell me why this is happening?

Here is my main code:

import sys
import pygame

from settings import Settings
from rocket_ship import RocketShip

class Rocket:
    """Overall class to manage rocket game."""

    def __init__(self):
        """Initialise the game and create game resources."""
        pygame.init() # initialise the background settings 
        # which the game needs to work properly
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        # tells pygame to figure out a window size to fill the screen
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        # updates the screen settings after fullscreen has been created
        pygame.display.set_caption("Rocket Game")

        self.rocket_ship = RocketShip(self)
    
    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self.check_events()
            self.rocket_ship.update()
            self.update_screen()

    def check_events(self):
        # Watch for 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):
        if event.key == pygame.K_RIGHT:
            # Move ship 1 to the right.
            self.rocket_ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.rocket_ship.moving_left = True
        elif event.key == pygame.K_UP:
            self.rocket_ship.moving_top = True
        elif event.key == pygame.K_DOWN:
            self.rocket_ship.moving_bottom = True 
        elif event.key == pygame.K_q:
            sys.exit()

    def check_keyup_events(self,event):
        if event.key == pygame.K_RIGHT:
            self.rocket_ship.moving_right = False 
        elif event.key == pygame.K_LEFT:
            self.rocket_ship.moving_left = False
        elif event.key == pygame.K_UP:
            self.rocket_ship.moving_top = False
        elif event.key == pygame.K_DOWN:
            self.rocket_ship.moving_bottom = False
    
    def update_screen(self):
        """Update images on the screenand flip to the new screen."""
        # redraw the screen during each pass through the loop 
        self.screen.fill(self.settings.bg_color)
        self.rocket_ship.blitme()
        #self.alien.blitme()

        # Make the most recently drawn screen visible.
        pygame.display.flip()

if __name__ == "__main__":
    # make a game instance and run the game
    ai = Rocket()
    ai.run_game()
Here is my code for the rocketship:

import pygame 

from settings import Settings

class RocketShip:
    """A class to manage the ship."""

    def __init__(self, ai_game):
        """Initialise the ship and its starting position."""
        self.screen = ai_game.screen
        self.settings = ai_game.settings
        self.screen_rect = ai_game.screen.get_rect()

        # Load the ship image and get its rect.
        self.image = pygame.image.load(
            (r'C:\Users\djwil\Documents\python\python crash course\Projects\Alien invasion\Images\ship.bmp')) 
        self.rect = self.image.get_rect()
        # Start each new ship at the bottom center of the screen.
        self.rect.center = self.screen_rect.center

        # Store a decimal value for the ship's horizontal position.
        self.x = float(self.rect.x)

        # Movement flag
        self.moving_right = False
        self.moving_left = False
        self.moving_top = False
        self.moving_bottom = False

    def update(self):
        """Update ships position based on movement flags."""
        # Update the ships x value not the rect.
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.rect.x += self.settings.ship_speed 
        if self.moving_left and self.rect.left > 0:
            self.rect.x -= self.settings.ship_speed
        if self.moving_top and self.rect.top  > 0:
            self.rect.x += self.settings.ship_speed
        if self.moving_bottom and self.rect.bottom < self.screen_rect.bottom:
            self.rect.x -= self.settings.ship_speed 

        
        # Update rect object from self.x
        #self.rect.x = self.x

    def blitme(self):
        """Draw the rocket at its current location."""
        self.screen.blit(self.image, self.rect)
and here's the code for my settings

class Settings:
    """A class to store all settings for Alien Invasion and Rocket."""

    def __init__(self):
        """Initialise the games settings."""
        self.screen_width = 1000
        self.screen_height = 600
        self.bg_color = (230, 230, 230)

        # Ship settings
        self.ship_speed = 1.5
Reply
#2
If you are going to do movement more complex than left/right, the simpler approach is to use the Pygame Vector2 class. Lets you do +/-/*// with 2D coordinates.

https://www.trccompsci.online/mediawiki/..._in_PyGame
Reply
#3
Thanks I will try that but is there anything else wrong with my code that you can see? I don't want to repeat errors later on.
Reply
#4
Looks like your code is way more complicated than necessary. Why just do something like,

if keystate[pygame.K_LEFT]:
  dx = -1
elif keystate[pygame.K_RIGHT]:
 dx = 1
elif keystate[pygame.K_UP]:
 dy = -1
...
Reply
#5
I've just tried what your suggesting and I get this error :

Error:
File "c:\Users\djwil\Documents\python\python crash course\Projects\Alien invasion\rocket3.py", line 43, in check_keydown_events if keystate[pygame.K_RIGHT]: NameError: name 'keystate' is not defined
This is my main code now:

import sys
import pygame

from settings import Settings
from rocket_ship import RocketShip

class Rocket:
    """Overall class to manage rocket game."""

    def __init__(self):
        """Initialise the game and create game resources."""
        pygame.init() # initialise the background settings 
        # which the game needs to work properly
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        # tells pygame to figure out a window size to fill the screen
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        # updates the screen settings after fullscreen has been created
        pygame.display.set_caption("Rocket Game")

        self.rocket_ship = RocketShip(self)
    
    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self.check_events()
            self.rocket_ship.update()
            self.update_screen()

    def check_events(self):
        # Watch for 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):
        if keystate[pygame.K_RIGHT]:
            # Move ship 1 to the right.
            dx = 1
        elif keystate[pygame.K_LEFT]:
            dx = -1 
        elif keystate[pygame.K_UP]:
            dy = - 1
        elif keystate[pygame.K_DOWN]:
            dy = 1 
        elif event.key == pygame.K_q:
            sys.exit()

    def check_keyup_events(self,event):
        if event.key == pygame.K_RIGHT:
            self.rocket_ship.moving_right = False 
        elif event.key == pygame.K_LEFT:
            self.rocket_ship.moving_left = False
        elif event.key == pygame.K_UP:
            self.rocket_ship.moving_top = False
        elif event.key == pygame.K_DOWN:
            self.rocket_ship.moving_bottom = False
    
    def update_screen(self):
        """Update images on the screenand flip to the new screen."""
        # redraw the screen during each pass through the loop 
        self.screen.fill(self.settings.bg_color)
        self.rocket_ship.blitme()
        #self.alien.blitme()

        # Make the most recently drawn screen visible.
        pygame.display.flip()

if __name__ == "__main__":
    # make a game instance and run the game
    ai = Rocket()
    ai.run_game()
Reply
#6
That is just part of the code. Add this ahead
keystate = pygame.key.get_pressed()
Reply
#7
You are moving rect.x and never rext.y even when moving up and down.
Recommended Tutorials:
Reply
#8
Thanks that sorted it Smile
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Snake not changing directions in Snake Game Bjdamaster 4 4,856 Aug-13-2018, 05:09 AM
Last Post: Bjdamaster

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020