简体   繁体   English

在2张图像之间来回切换

[英]Switching back and forth between 2 images

My friend and I were bored the other day and decided to make a simple game in python. 前几天,我和我的朋友很无聊,决定用python做一个简单的游戏。 Objects fall from the top of the display window and the user must control a box to catch them before they hit the ground. 物体从显示窗口的顶部掉落,用户必须控制一个盒子才能抓住它们,然后再将其撞到地面上。 We decided we would have different objects that are worth more points than others. 我们决定我们将拥有比其他物品更有价值的不同物品。 My question is, how do you have one instance of an object falling randomly switch images. 我的问题是,您如何让一个对象随机掉入一个实例,切换图像。

I tried to do this myself using a variable that is a random integer between 0-10. 我试图自己使用一个变量,该变量是一个介于0到10之间的随机整数。 If the integer is less than 5, the picture is set as a bat. 如果整数小于5,则将图片设置为蝙蝠。 If the integer is above 5, the picture is set as a ghost. 如果整数大于5,则图片被设置为重影。

My attempted coding is as follows: 我尝试的编码如下:

    #Detect if user has missed a bomb#

    bomb_img = 0
    bomb_y += vel_y
    if bomb_y > 500:
        bomb_x = random.randint(0, 500)
        bomb_y = -50
        bomb_img = random.randint(0,10)
        lives -= 1
        if lives == 0:
            game_lost = True

    #Detect if user has saved a bomb#
    elif bomb_y > pos_y:
        if bomb_x > pos_x and bomb_x < pos_x + 120:
            score += 10
            bomb_x= random.randint(0,500)
            bomb_y = -50
            bomb_img = random.randint(0,10)

    #Change bomb img#       
    ghost = pygame.image.load("ghost2.png").convert_alpha()
    bat = pygame.image.load("bat2.png").convert_alpha()
    bat_resize = pygame.transform.scale(bat, (133,95))
    if bomb_img <= 5:
        _display_window.blit(bat_resize, (bomb_x, bomb_y))
    else:
        _display_window.blit(ghost, (bomb_x, bomb_y))

However, this does not work as expected when ran. 但是,这无法正常运行。 The picture does change to a ghost, but only for a split second before changing back to the bat as it continues to fall. 画面确实变成了幻影,但只是持续了一秒钟,然后随着蝙蝠的持续下落而变回蝙蝠。

I also tried switching the following lines of code around: 我还尝试过切换以下代码行:

if bomb_img <= 5:
    _display_window.blit(ghost, (bomb_x, bomb_y))
else:
    _display_window.blit(bat_resize, (bomb_x, bomb_y))

In this case the picture will randomly change to the bat for a split second, before changing back into the ghost 在这种情况下,图片将随机变为蝙蝠一秒钟,然后再变为幻影

Basically I can get the image to change, but only for a quick second. 基本上,我可以更改图像,但是仅需一秒钟。 Any thoughts? 有什么想法吗?

It looks like the issue is that you reset bomb_img at the start of your loop, ie the first line of your code: 看来问题在于您在循环的开始(即代码的第一行)重置了bomb_img:

bomb_img = 0
...

You should pull that line outside your loop. 您应该将那条线拉出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM