簡體   English   中英

Python:幾秒鍾后將布爾值從 True 更改為 False

[英]Python: Make a boolean change from True to False after a few seconds

我有這個代碼,我正在為籃球比賽(一種街機風格的籃球比賽使用振動傳感器和 HC-SR04 來檢測籃板命中和得分投籃)。 我試圖弄清楚如何在幾秒鍾后將全局布爾值從 True 更改為 False。

因此,例如,球擊中籃板——這將全局籃板設置為 True——從那里它會保持 True 幾秒鍾,看看球是否從籃板反彈到網中。 如果當球穿過網時,籃板變量仍然為真,那么它就會知道這是一次離開籃板的射門,並且可以播放其他一些很酷的東西的特殊聲音效果。

現在在回調函數中,當球擊中籃板時,backboard 變量被設置為 True,但它會一直保持 True 直到玩家得分,而不是在幾秒鍾后變回 false。

這是代碼:

import RPi.GPIO as GPIO
from gpiozero import DistanceSensor
import pygame
import time

ultrasonic = DistanceSensor(echo=17, trigger=4)
ultrasonic.threshold_distance = 0.3
pygame.init()

#Global
backboard = False

#GPIO SETUP

channel = 22

GPIO.setmode(GPIO.BCM)

GPIO.setup(channel, GPIO.IN)

#music
score = pygame.mixer.Sound('net.wav')
bb = pygame.mixer.Sound("back.wav")

def scored():
        #the ball went through the net and trigged the HC-SR04
        global backboard
        if backboard == True:
                print("scored")
                backboard = False
                score.play()
                time.sleep(0.75)
        else:
                print("scored")  
                score.play()
                time.sleep(0.75)              

def callback(channel):
        #the ball hit the backboard and triggered the vibration sensor
        global backboard
        if GPIO.input(channel):
                backboard = True
                print("backboard")
                bb.play()
                time.sleep(0.75)


GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)  # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback)  # assign function to GPIO PIN, Run function on change
ultrasonic.when_in_range = scored

我建議簡單地實現一個計時器對象。 嘗試實現這個:

from threading import Timer
import time

def switchbool():
    backboard = false

t = Timer(3.0, switchbool) #will call the switchbool function after 3 seconds
t.start()

每當球擊中籃板時(每當您設置 backboard = true 時),只需創建一個類似於上面示例中的計時器對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM