0

In playing around with pygame capabilities I prepare to code a game of my own. While most of pygame's examples display surfaces like squares, I'd like to run with a rectangular shape resembling that of a cell phone screen. Initially, I'd expect that simply reshaping a GfG example picked up on the internet would do the job, yet I realize that objects do not stay inside the new rectangular shape when moving a sprite around with keyboard arrows.

I attempted to adjust width and height of surface (changed from (500, 500)):

# Global Variables
COLOR = (255, 100, 98)
SURFACE_COLOR = (167, 255, 100)
WIDTH = 580
HEIGHT = 250

But the squared object that I can control keeps continuing outside the new rect shape.

Any suggestions on how to proceed?

My playground code picked up on www.geeksforgeeks.org looks as follows:

import random
import pygame

# Global Variables
COLOR = (255, 100, 98)
SURFACE_COLOR = (167, 255, 100)
WIDTH = 580
HEIGHT = 250

# Object class
class Sprite(pygame.sprite.Sprite):
    def __init__(self, color, height, width):
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(SURFACE_COLOR)
        self.image.set_colorkey(COLOR)

        pygame.draw.rect(self.image,
                        color,
                        pygame.Rect(0, 0, width, height))

        self.rect = self.image.get_rect()

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

    def moveForward(self, speed):
        self.rect.y += speed * speed/10

    def moveBack(self, speed):
        self.rect.y -= speed * speed/10


pygame.init()


RED = (255, 0, 0)


size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Controlling Sprite")


all_sprites_list = pygame.sprite.Group()

playerCar = Sprite(RED, 20, 30)
playerCar.rect.x = 150
playerCar.rect.y = 150


all_sprites_list.add(playerCar)

exit = True
clock = pygame.time.Clock()

while exit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_x:
                exit = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        playerCar.moveLeft(5)
    if keys[pygame.K_RIGHT]:
        playerCar.moveRight(5)
    if keys[pygame.K_DOWN]:
        playerCar.moveForward(5)
    if keys[pygame.K_UP]:
        playerCar.moveBack(5)

    all_sprites_list.update()
    screen.fill(SURFACE_COLOR)
    all_sprites_list.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Newbie
  • 61
  • 1
  • 1
  • 6
  • Thx, Rabbid76, the post leading to ' Setting up an invisible boundary for my sprite (1 answer) ' solved my issue entirely...;o) – Newbie Feb 08 '23 at 07:44

0 Answers0