0

I'm new to programming and to help learn it I have been building an 'escape room' game using Python. I have the following that runs the bomb on a seperate thread.

import time
import threading
from threading import Thread

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        time.sleep(1)
        t -= 1
    print  """
    The bomb goes off
    GAME OVER
    """

Then in the main programme

t=3600 #60 minute game
game_thread=Thread(target=countdown,args=(t,))
game_thread.start()

What I would like to do is make it possible for the player to check how much time is left on the timer and for the timer to stop when the player has defused the bomb. Does anyone have any advice on how I can do that?

Thanks

OBu
  • 4,977
  • 3
  • 29
  • 45

2 Answers2

0
# default value
t = 3600

def countdown():
    global t
        while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        time.sleep(1)
        t -= 1

I assume you got a trigger that the user defused the bomb.

def on_bomb_defuse():
    time_used = t
    # kill countdown thread

Even though it is a bad pattern to kill threads you may kill the countdown thread since you retrieved the required time already (How to kill a thread in python).

ZKDev
  • 315
  • 2
  • 9
  • I'm using an if command to check if the user has input the correct disarm code, is that where I would place the kill countdown command? – Alastair.Tyson Oct 15 '19 at 00:13
  • Also, when I entered the global t to the countdown, I got an error message saying that t couldn't be local and global. Should global t be placed before the countdown function? – Alastair.Tyson Oct 15 '19 at 00:13
0

I have managed to find a solution to stopping the timer when bomb is defused:

bomb_timer=["Trigger"] #Creates a list items containing the trigger
def countdown():
  while t:
    mins, secs = divmod(t, 60)
    timeformat = '{:02d}:{:02d}'.format(mins, secs)
    time.sleep(1)
    if "Trigger" in bomb_timer: #Countdown runs as long as trigger is present
      t -= 1

When user has entered correct code

bomb_timer.remove("Trigger") #Removes Trigger from timer which halts the countdown