Reputation: 23
This is my code so far but I'm wondering if I can just set an image as a background. I've just started using pygame and I don't know much about it
import pygame
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load('space.gif')
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = (display_width * 0.001)
y = (display_height * 0.01)
Upvotes: 1
Views: 1827
Reputation: 162
A solution using Python Image Library aka PIL:
from PIL import Image
import pygame
#link to cat image:https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png
w,h = 500,500
win = pygame.display.set_mode((w,h))
#open the image
img = Image.open("cute-cat.png")
#resize the image
img = img.resize((w,h))
#convert to a pygame surface
img = pygame.image.frombuffer(img.tobytes(),(w,h),"RGB")
#blit to screen
win.blit(img,(0,0))
#update the screen
pygame.display.flip()
Upvotes: 0
Reputation: 210876
Load a back ground image (e.g. 'background.jpg'), scale it to the size of the screen with pygame.transform.smoothscale
and blit
it on the display surface:
background = pygame.image.load('background.jpg').convert()
background = pygame.transform.smoothscale(background, gameDisplay.get_size())
gameDisplay.blit(background, (0, 0))
Furthermore you have to implement and application loop and the scene has toi be redrawn in every frame. The typical PyGame application loop has to:
pygame.event.pump()
or pygame.event.get()
.
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
blit
all the objects)pygame.display.update()
or pygame.display.flip()
import pygame
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
background = pygame.image.load('background.jpg').convert()
background = pygame.transform.smoothscale(background, gameDisplay.get_size())
black = (0,0,0)
white = (255,255,255)
crashed = False
carImg = pygame.image.load('space.gif')
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = round(display_width * 0.001)
y = round(display_height * 0.01)
run = True
while run:
clock.tick(60)
# handle the events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# update the game states and positions of objects
keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 5
y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 5
x = x % gameDisplay.get_width()
y = y % gameDisplay.get_height()
# draw the background
gameDisplay.blit(background, (0, 0))
# draw the entire scene
car(x, y)
# update the display
pygame.display.flip()
Upvotes: 1