M
M
mcmikey2020-11-17 19:48:08
Python
mcmikey, 2020-11-17 19:48:08

Why is there a black screen instead of images in pygame?

I wrote a code to control the sprite of the car against the background of the city according to the guide from YouTube. But on startup it shows a black screen. The comments advised to write drawWindow() at the end, but that didn't help either.
Here is the code -

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Adventure")

walkRight = [pygame.image.load('car_right_1.png'), pygame.image.load('car_right_2.png')]
walkLeft = [pygame.image.load('car_left_1.png'), pygame.image.load('car_left_2.png')]
playerStand = [pygame.image.load('car_.png')]
bg = pygame.image.load('bg.jpg')

clock = pygame.time.Clock()

x = 50 
y = 450
width = 91
height = 67
speed = 5

isJump = False
JumpCount = 10

animCount = 0
left = False
right = False

def drawWindow():
    global animCount

    win.blit(bg,(0, 0))
    if animCount + 1 >= 30:
        animCount = 0

    if left:
        win.blit(walkLeft[animCount // 5], (x,y))
        animCount += 1
    elif right:
        win.blit(walkRight[animCount // 5], (x,y))
        animCount += 1
    else:
        win.blit(playerStand[animCount // 5], (x,y))
        animCount = 0

    pygame.display.update()

run = True

while run:
    clock.tick(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and x > 5:
        x -= speed
        left = True
        right = False
    elif keys[pygame.K_RIGHT] and x < 500 - width - 5:
        x += speed
        left = False
        right = True
    else:
        left = False
        right = False
        animCount = 0
    if not(isJump):
        if keys[pygame.K_SPACE]:
            isJump = True
            left = False
            right = False
            animCount = 0
    else:
        if JumpCount >= -10:
            if JumpCount < 0:
                y += (JumpCount ** 2) / 2
            else:    
                y -= (JumpCount ** 2) / 2
            JumpCount -= 1
        else:
            isJump = False
            JumpCount = 10

drawWindow()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2020-11-17
@o5a

The drawing of drawWindow () should happen inside the main game loop (i.e. adjust the padding).

R
Roma Kotolup, 2021-04-30
@roma2

o5a , wrote correctly! But your code is not working!
Errors everywhere! You need to learn what one piece means, and learn to write it in different forms, and not download the code!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question