Как добавить объект по переменной? - PullRequest
1 голос
/ 21 июня 2020

Мне было интересно, как мне добавлять «вещь» (имя объекта) на экран каждый раз, когда «уклонение» (оценка) увеличивается на 1? Поэтому я бы хотел, чтобы количество «вещей» было равно «уклонению» + 1 (когда оценка 0, количество вещей равно 1, когда оценка 1, количество вещей равно 2 и т. Д. c .). Вот полный код, я создаю код на основе серии sentdex «Разработка игр в Python 3 с Pygame» на youtube:

import pygame
import time
import random

pygame.init()

crash_sound = pygame.mixer.Sound("Crash.wav")
pygame.mixer.music.load("BackgroundMusic.wav")

display_width = 1200
display_height = 1000
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
bright_red = (255, 0, 0)
green = (0,200,0)
bright_green = (0, 255, 0)
blue = (0,0,255)
grey = (146, 159, 138)

car_width = 148
car_height = 200

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Racing game")
clock = pygame.time.Clock()

carImage = pygame.image.load("Car.png")
carIcon = pygame.image.load("caricon.png")
pygame.display.set_icon(carIcon)

pause = False

def things_dodged(count):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Dodged: " + str(count), True, black)
    gameDisplay.blit(text, (0, 0))

def things(thingx, thingy, thingw, thingh, color):
    pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])

def car(x,y):
    gameDisplay.blit(carImage, (x,y))

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def message_display(text):
    largeText = pygame.font.Font("freesansbold.ttf", 115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2), (display_height/2))
    gameDisplay.blit(TextSurf, TextRect)
    pygame.display.update()
    time.sleep(2)
    game_loop()

def crash():
    pygame.mixer.music.stop()
    pygame.mixer.Sound.play(crash_sound)
    
    message_display("You crashed!")

def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
            
    else:
        pygame.draw.rect(gameDisplay, ic, (x, y, w, h))

    if 900 + 100 > mouse[0] > 900 and 800 + 50 > mouse[1] > 800:
        pygame.draw.rect(gameDisplay, bright_red, (900, 800, 100, 50))
    else:
        pygame.draw.rect(gameDisplay, red, (900, 800, 100, 50))

    smallText = pygame.font.Font("freesansbold.ttf", 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x + (w/2)), (y + (h/2)))
    gameDisplay.blit(textSurf, textRect)

def quitgame():
    pygame.quit()
    quit()

def unpause():
    global pause

    pygame.mixer.music.unpause()
    
    pause = False

def paused():

    pygame.mixer.music.pause()

    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        gameDisplay.fill(white)
        largeText = pygame.font.Font("freesansbold.ttf", 115)
        TextSurf, TextRect = text_objects("Paused", largeText)
        TextRect.center = ((display_width/2), (display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

        pygame.draw.line(gameDisplay, black, (149, 799), (249, 799), 1)
        pygame.draw.line(gameDisplay, black, (250, 800), (250, 850), 1)
        pygame.draw.line(gameDisplay, black, (250, 850), (150, 850), 1)
        pygame.draw.line(gameDisplay, black, (149, 850), (149, 800), 1)
        pygame.draw.line(gameDisplay, black, (899, 799), (999, 799), 1)
        pygame.draw.line(gameDisplay, black, (1000, 800), (1000, 850), 1)
        pygame.draw.line(gameDisplay, black, (1000, 850), (900, 850), 1)
        pygame.draw.line(gameDisplay, black, (899, 850), (899, 800), 1)

        button("Continue", 150, 800, 100, 50, green, bright_green, unpause)
        button("Quit", 900, 800, 100, 50, red, bright_red, quitgame)
        
        pygame.display.update()
        clock.tick(15)

def game_intro():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        gameDisplay.fill(white)
        largeText = pygame.font.Font("freesansbold.ttf", 115)
        TextSurf, TextRect = text_objects("Racing game", largeText)
        TextRect.center = ((display_width/2), (display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

        pygame.draw.line(gameDisplay, black, (149, 799), (249, 799), 1)
        pygame.draw.line(gameDisplay, black, (250, 800), (250, 850), 1)
        pygame.draw.line(gameDisplay, black, (250, 850), (150, 850), 1)
        pygame.draw.line(gameDisplay, black, (149, 850), (149, 800), 1)
        pygame.draw.line(gameDisplay, black, (899, 799), (999, 799), 1)
        pygame.draw.line(gameDisplay, black, (1000, 800), (1000, 850), 1)
        pygame.draw.line(gameDisplay, black, (1000, 850), (900, 850), 1)
        pygame.draw.line(gameDisplay, black, (899, 850), (899, 800), 1)

        button("Start", 150, 800, 100, 50, green, bright_green, game_loop)
        button("Quit", 900, 800, 100, 50, red, bright_red, quitgame)
        
        pygame.display.update()
        clock.tick(15)

def game_loop():
    global pause

    pygame.mixer.music.play(-1)
    
    x = (display_width * 0.45)
    y = (display_height * 0.6)
    x_change = 0

    thing_startx = random.randrange(0, display_width)
    thing_starty = -600
    thing_speed = 3
    thing_width = 100
    thing_height = 100
    dodged = 0

    gameExit = False

    while not gameExit:
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5
                elif event.key == pygame.K_RIGHT:
                    x_change = 5
                if event.key == pygame.K_p:
                    pause = True
                    paused()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        x += x_change
        gameDisplay.fill(white)

        things(thing_startx, thing_starty, thing_width, thing_height, black)
        thing_starty += thing_speed
        car(x,y)
        things_dodged(dodged)

        if x > display_width - car_width or x <  0:
                crash()
        if thing_starty > display_height:
            thing_starty = 0
            thing_startx = random.randrange(0, display_width)
            dodged += 1
            if thing_speed < 12:
                thing_speed += 0.5
            
        if y < thing_starty+thing_height and y + car_height > thing_starty:
            print("")
            if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width:
                print("")
                crash()

        pygame.display.update()
        clock.tick(120)

game_intro()
game_loop()
pygame.quit()
quit()

Я представляю, вместо увеличения скорости « ", Мне пришлось бы создать переменную для количества" вещей "и каждый раз увеличивать ее на 1, но я все еще не уверен, как это сделать, не создавая ее вручную (например, 5 строк размещения 5 вещей на экране случайным образом, вместо этого я хочу автоматизировать).

1 Ответ

1 голос
/ 21 июня 2020

создайте список, содержащий один из объектов, которые вы хотите сохранить, например:

objects = [Object()]

Затем добавьте еще один объект в список, где бы вы ни увеличивали переменную уклонения:

if thing_starty > display_height:
    thing_starty = 0
    thing_startx = random.randrange(0, display_width)
    objects.append(Object())
    dodged += 1

и если вы хотите рисовать / копировать эти объекты на каждой итерации игры l oop, вы можете сделать что-то вроде этого:

for item in objects:
    gameDisplay.blit(item, (x,y))
...