pythonpygamerenderdrawrect

Can't draw rect in python pygame


I'm just getting started with PyGame. Here, I'm trying to draw a rectangle, but it's not rendering.

Here's the whole program.

import pygame
from pygame.locals import *
import sys
import random

pygame.init()

pygame.display.set_caption("Rafi's Game")

clock = pygame.time.Clock()

screen = pygame.display.set_mode((700, 500))




class Entity():

    def __init__(self, x, y):
    self.x = x
    self.y = y


class Hero(Entity):

    def __init__(self):
        Entity.__init__
        self.x = 0
        self.y = 0

    def draw(self):
        pygame.draw.rect(screen, (255, 0, 0), ((self.x, self.y), (50, 50)), 1)



hero = Hero()
#--------------Main Loop-----------------

while True:


    hero.draw()

    keysPressed = pygame.key.get_pressed()

    if keysPressed[K_a]:
        hero.x = hero.x - 3
    if keysPressed[K_d]:
        hero.x = hero.x + 3
    if keysPressed[K_w]:
        hero.y = hero.y - 3
    if keysPressed[K_s]:
        hero.y = hero.y + 3

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





    #Event Procesing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()


    #Event Processing End


    pygame.display.flip()

    clock.tick(20)

self.x and self.y are currently 0 and 0. Note that this is not a finished program, all it should do is draw a red square on a green background that can be controled by the WASD keys.


Solution

  • Let's look at a portion of your main loop:

    while True:
    
    
        hero.draw()
    
        keysPressed = pygame.key.get_pressed()
    
        if keysPressed[K_a]:
            hero.x = hero.x - 3
        if keysPressed[K_d]:
            hero.x = hero.x + 3
        if keysPressed[K_w]:
            hero.y = hero.y - 3
        if keysPressed[K_s]:
            hero.y = hero.y + 3
    
        screen.fill((0, 255, 0))
    

    Inside the Hero class's draw function, you are drawing the rect. In the main loop, you are calling hero.draw(), and then after handling your inputs, you are calling screen.fill(). This is drawing over the rect you just drew. Try this:

    while True:
    
        screen.fill((0, 255, 0))
        hero.draw()
    
        keysPressed = pygame.key.get_pressed()
        ....
    

    That will color the entire screen green, then draw your rect over the green screen.