AKcoArts AKcoArts - 25 days ago 8
Python Question

Moving A Rectangle in Pygame

I'm trying to make a game and encountered a problem... I cant move the rectangle, and it doesn't give me an error code either?.. I think the problem is that it keeps making the rectangle over and over again in the while loop... but I don't know how to fix this..

#! /usr/bin/env python

import os
import random
import pygame
import math
import sys

os.environ["SDL_VIDEO_CENTERED"] = "1"

screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("LEVEL 2 = Find the Correct Square!")

clock = pygame.time.Clock()

class Player(object):
def __init__(self):
self.rect = pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))

def handle_keys(self):
key = pygame.key.get_pressed()
dist = 1
if key[pygame.K_LEFT]:
self.rect.move(-1, 0)
if key[pygame.K_RIGHT]:
self.rect.move(1, 0)
if key[pygame.K_UP]:
self.rect.move(0, -1)
if key[pygame.K_DOWN]:
self.rect.move(0, 1)

def draw(self, surface):
pygame.draw.rect(screen, (0, 0, 128), (64, 54, 16, 16))

pygame.init()

player = Player()
clock = pygame.time.Clock()

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
running = False

screen.fill((255, 255, 255))

player.draw(screen)
player.handle_keys()
pygame.display.update()

clock.tick(40)

Answer

You need to make a few changes to your Player class. You either need to reassign self.rect to the result of self.rect.move() or use the inplace variant self.rect.move_ip()

class Player(object):
    def __init__(self):
        self.rect = pygame.rect.Rect((64, 54, 16, 16))

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_LEFT]:
           self.rect.move_ip(-1, 0)
        if key[pygame.K_RIGHT]:
           self.rect.move_ip(1, 0)
        if key[pygame.K_UP]:
           self.rect.move_ip(0, -1)
        if key[pygame.K_DOWN]:
           self.rect.move_ip(0, 1)

    def draw(self, surface):
        pygame.draw.rect(screen, (0, 0, 128), self.rect)

The rectangle will move once for each keypress. If you want to keep moving when you hold a key down, you need to dedent part of your main loop

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
            running = False

    screen.fill((255, 255, 255))

    player.draw(screen)
    player.handle_keys()
    pygame.display.update()

    clock.tick(40)