Reputation: 21
Hiii, I'm making a game in my computer science class and I need to figure out how to generate an image randomly somewhere on the screen in pygame. The game is a basically just a car moving around and you have to dodge to obstacles but i have no idea how to get my chosen obstacle randomly on the screen. this is what i have so far...
import pygame
import random
pygame.init()
myClock = pygame.time.Clock()
WIDTH = 450
HEIGHT = 450
screen = pygame.display.set_mode((WIDTH,HEIGHT))
#images
bg = pygame.image.load("roads.png")
car = pygame.image.load("barbiecar.png")
cone = pygame.image.load("cone.png")
carRect = car.get_rect()
coneRect = cone.get_rect()
bg = pygame.transform.scale(bg,(WIDTH,HEIGHT))
carRect = car.get_rect()
posX = 198
posY = 430
pos_back = 0
while True:
carRect.center = (posX,posY)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
posX=posX+7
elif event.key == pygame.K_w:
posY=posY-7
elif event.key == pygame.K_a:
posX = posX-7
elif event.key == pygame.K_s:
posY= posY + 7
screen.blit(bg,(0,pos_back))
screen.blit(bg,(0,pos_back-WIDTH))
#screen.blit(car,(posX,posY))
screen.blit(car,(carRect))
if pos_back == +WIDTH:
screen.blit(bg,(0,WIDTH+pos_back))
pos_back = 0
pos_back = pos_back+1
pygame.display.update()
myClock.tick(40)
Upvotes: 2
Views: 1024
Reputation: 360
maybe you can try using random
module
import random as rd
...
## then in your code
while True:
...
screen.blit(my_choosen_object, (rd.randint(0, WIDTH), rd.randint(0, HEIGHT)))
Upvotes: 1