Good evening,
I am creating a side-scroller game in Pygame but I am running into trouble adjusting the ships speed and limiting the range. I am new to python and still in the learning process.
I keep getting an AttributeError: 'Ship' object has no attribute 'screen_rect'
Please I am stuck and need to understand what I'm doing wrong.
This is the code I have so far:
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.settings = ai_game.settings
# Load the ship image and get its rect.
self.image = pygame.image.load('images/Blue-5.bmp')
self.rect = self.image.get_rect()
# Start each new ship at center left of screen.
self.rect.midleft = self.screen_rect.midleft
# Store a decimal value for the ship's horizontal position.
self.x = float(self.rect.x)
self.y = float(self.rect.y)
# Movement Flag
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
def update(self):
"""Update the ship's position based on the movement flag."""
# Update the ship's x value, not the rect
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
if self.moving_up and self.rect.up < self.screen_rect.up:
self.y -= self.settings.ship_speed
if self.moving_down and self.rect.down > 0:
self.y += self.settings.ship_speed
# Update rect object from self.x.
self.rect.x = self.x
self.rect.y = self.y
def blitme(self):
"""Draw the ship at its current location."""
self.screen.blit(self.image, self.rect)
Use
pygame.time.Clock
to control the frames per second and thus the game speed.The method
tick()
of apygame.time.Clock
object, delays the game in that way, that every iteration of the loop consumes the same period of time.That means that the loop:
runs 60 times per second.
pygame.time.Clock.tick
returns the number of milliseconds passed since the previous call. If you call it in the application loop, then this is the number of milliseconds passed since the last frame.Multiply the velocity of the player by the passed time per frame, to get a constant movement independent on the FPS.
For instance define the distance in number of pixel, which the player should move per second (
move_per_second
). Then compute the distance per frame in the application loop: