Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

python - how to handle time for different components in pygame

I'm making a pygame game where a person can purchase bombs from a shop. The player can also drop as many bombs as he buys. I need a way to make each bomb disappear after 3 seconds of it being dropped. In the following code I am just able to drop the bombs however I have tried various methods and failed.

import pygame
import random

pygame.font.init()

width = 900
height = 600

screen = pygame.display.set_mode([width, height])

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]

walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
bomb_explosion = pygame.transform.scale(pygame.image.load('explosion1.png'), (40,40))
# char_rect = char.get_rect()


enemy_Left = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'),
            pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'),
            pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png')] 



x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0

enemy_vel = 2
enemy_list = []

shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))

clock = pygame.time.Clock()
FPS = 60

font = pygame.font.Font('freesansbold.ttf', 32)
items_font = pygame.font.Font('freesansbold.ttf', 16)

bombs =[]
bag = {'bomb': 0}
print(bag["bomb"])


class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):

        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 20)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (
                self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))


def shop_run():
    shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_b")
    bright_green = (0, 255, 0)
    green = (0, 200, 0)
    shop_bomb.draw(screen)


def redrawGameWindow():
    global walkCount
    global font
    global bag
    global items_font
    global enemy_list
    screen.fill([166, 166, 166])
    for five_enemies in range(6):
        random_enemy_location_y = random.randrange(100, 400)
        random_enemy_location_x = random.randrange(800, 840)
        enemy_list.append([random_enemy_location_x, random_enemy_location_y])

    for enemies in range(6):
        screen.blit(enemy_Left[enemies], enemy_list[enemies])
        enemy_list[enemies][0] -= 0.3



    pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
    if x + char.get_width() < 60 and y + char.get_height() < 60:
        shop_run()

    screen.blit(shop, (0, 0))
    screen.blit(font.render("Menu", True, (255,255,255)),(805, 10))
    screen.blit(items_font.render("Bombs: "+ str(bag["bomb"]), True, (255, 255, 255)), (805, 550))
    # screen.blit(bomb_explosion, (450, 300))
    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        screen.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1

    elif right:
        screen.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1

    elif down:
        screen.blit(char, (x, y))
        walkcount = 0

    elif up:
        screen.blit(char, (x, y))
        walkcount = 0

    else:
        screen.blit(char, (x, y))
        walkCount = 0


    for pos in bombs:
        screen.blit(bomb_pic, pos)




    pygame.display.update()

def main():
    run = True
    # shopper()
    pygame.display.set_caption("bomb-mania")

    global x
    global y
    global width
    global height
    global vel

    global isJump
    global jumpCount

    global left
    global right
    global down
    global up

    global walkCount

    global bomb_pic

    global font
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False


            if x + char.get_width() < 60 and y + char.get_height() < 60:
                buy = pygame.key.get_pressed()
                if buy[pygame.K_b]:
                    bag["bomb"] += 1
                    print(bag["bomb"])

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
                    bombs.append(((x + (char.get_width()/2)),( y + (char.get_height() - 20))))
                    bag["bomb"] -= 1

        redrawGameWindow()



        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel - 15:
            x -= vel
            left = True
            right = False
            down = False
            up = False



        elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
            x += vel
            left = False
            right = True
            down = False
            up = False

        elif keys[pygame.K_DOWN] and y < 600 - height:
            y += vel
            left = False
            right = False
            down = True
            up = False

        elif keys[pygame.K_UP] and y > vel - 15:
            y -= vel
            left = False
            right = False
            down = False
            up = True

        else:
            left = False
            right = False
            down = False
            up = False
            walkCount = 0

        clock.tick(FPS)
        pygame.display.flip()


main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use pygame.time.get_ticks() to get the current time in milliseconds. Compute the time when the bomb has to disappear. Store the time to the list bombs. The list bombs has to contain a tuple of position and time.
If the time is elapsed, then remove the bomb from the list:

def redrawGameWindow():
    current_time = pygame.time.get_ticks()
    # [...]

    for i in reversed(range(len(bombs))):
        pos, end_time = bombs[i]
        if current_time > end_time
            bombs.pop(i)
        else:
            screen.blit(bomb_pic, pos)
def main():
    # [...]

    while run:

        current_time = pygame.time.get_ticks()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            # [...]

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
                    pos = x + char.get_width()/2, y + char.get_height() - 20
                    end_time = current_time + 3000 # 3000 milliseconds = 3 seconds
                    bombs.append((pos, end_time))
                    bag["bomb"] -= 1

        redrawGameWindow()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...