0

I'm trying to display a background image for my game but when I blit it, it only shows my main playable character on the screen with a black background. Can anyone help me please with this problem.

Here's the code:

import sys, pygame, os
pygame.init()

size = width, height = 320, 240
xREVERSEspeed = [-2, 0]
xspeed = [2, 0]

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")
os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

ball = pygame.image.load("turret.png").convert_alpha()
background = pygame.image.load("scoreframe.png").convert()
ballrect = ball.get_rect(center=(160, 231))
BACKGROUNDrect = background.get_rect()
clock = pygame.time.Clock()

while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()    
        if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                        print "I've pressed the LEFT arrow button."
                        ballrect = ballrect.move(xspeed)
                        print ballrect
                if event.key == pygame.K_RIGHT:
                        print "I've pressed the RIGHT arrow button."
                        ballrect = ballrect.move(xREVERSEspeed)
                        print ballrect

    screen.blit(ball, ballrect, background, BACKGROUNDrect)
    pygame.display.flip()
pradyunsg
  • 18,287
  • 11
  • 43
  • 96

2 Answers2

1

Firstly, your indentation is wrong, but i assume that this is a typo. Your event part is at the same level as your game while loop, it should be inside. The bliting and fliping too. I also see that you are using the blitting function wrong. From the pygame docs:

Surface.blit(source, dest, area=None, special_flags = 0): return Rect

which blits a surface source onto the Surface at the destination given by dest, with optionally an area which is rectangle that defines a subsurface of the source surface to be blitted. You have to blit the character and the background image seperately. So you should do it this way:

screen.blit(background,(0,0))
screen.blit(ball,ballrect)
Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75
1

I dont know if you messed up when you pasted here but your "if event.type" is not int the "while 1:"

Anyway try this:

while 1:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()


    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            print "I've pressed the LEFT arrow button."
            ballrect = ballrect.move(xspeed)
            print ballrect
        if event.key == pygame.K_RIGHT:
            print "I've pressed the RIGHT arrow button."
            ballrect = ballrect.move(xREVERSEspeed)
            print ballrect
    screen.blit(background,(BACKGROUNDrect))
    screen.blit(ball,(ballrect))
    pygame.display.flip()
tsa
  • 21
  • 1