I'm trying to do a scroller type game but I need help with the coins spawning.
This is my code:
import os
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode(((0, 0)), pygame.FULLSCREEN)
pygame.display.set_caption('First game')
image = pygame.image.load('Game_icon.png')
pygame.display.set_icon(image)
GREEN = (0, 150, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0,)
FPS = 60
FPS_SLOMO = 30
VEL = 5
PLAYER_WIDTH, PLAYER_HEIGHT = 55, 55
COIN_WIDTH, COIN_HEIGHT = 20, 20
PLAYER_IMAGE = pygame.image.load(os.path.join('Assets', 'Player.png'))
PLAYER = pygame.transform.rotate(pygame.transform.scale(
PLAYER_IMAGE, (PLAYER_WIDTH, PLAYER_HEIGHT)), 0)
COIN_IMAGE = pygame.image.load(os.path.join("Assets", 'coin.png'))
COIN = pygame.transform.rotate(pygame.transform.scale(
COIN_IMAGE, (COIN_WIDTH, COIN_HEIGHT)), 0)
def draw_window(player, coin):
WIN.fill(GREEN)
WIN.blit(PLAYER, (player.x, player.y))
WIN.blit(COIN, (coin.x, coin.y))
pygame.display.update()
def main():
player = pygame.Rect(100, 300, PLAYER_WIDTH, PLAYER_HEIGHT)
coin = pygame.Rect(100, 100, COIN_WIDTH, COIN_HEIGHT)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_a]:
player.x -= VEL
if keys_pressed[pygame.K_d]:
player.x += VEL
if keys_pressed[pygame.K_w]:
player.y -= VEL
if keys_pressed[pygame.K_s]:
player.y += VEL
if keys_pressed[pygame.K_LSHIFT]:
clock.tick(FPS_SLOMO)
draw_window(player, coin)
pygame.quit()
if __name__ == "__main__":
main()
If I understand your problem well, it could be solved like this:
import random
NUM_COINS = 100
coins = [[
random.randint(0, WIDTH), random.randint(0, HEIGHT)] for _ in range(NUM_COINS)]
def draw_window(player):
WIN.fill(GREEN)
WIN.blit(PLAYER, (player.x, player.y))
for pos in coins:
WIN.blit(COIN, (pos[0], pos[1]))
pygame.display.update()
I hope it will help you, Adam.
PS: I would recommend reducing the VEL and increasing the FPS for a better game experience
Una manera de cargar imagenes aleatoriomente seria recurriendo al modul os por ejemplo:
def extraer_imagenes(ruta_imagenes):
listado_de_img = os.listdir("ruta_imagenes") #Listara todos los nombres de las imagenes
img_aleatoria = random.choice(listado_de_img)
return img_aleatoria
De esta manera obtendras una ruta aleatoria de las imagenes que quieres que se carguen
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.