2

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)
1
  • 1
    Generate a valid (x, y) point to place the obstacle at. If it doesn't meet the requirements, generate it again until it does. Then draw the obstacle at the specified coordinates. Commented Apr 26, 2022 at 22:23

1 Answer 1

1

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)))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.