Skip to content

Instantly share code, notes, and snippets.

@AnkDos
Last active July 3, 2021 17:47
Show Gist options
  • Save AnkDos/4ea89d8e9ba4f1fd13d8b50aeccac48b to your computer and use it in GitHub Desktop.
Save AnkDos/4ea89d8e9ba4f1fd13d8b50aeccac48b to your computer and use it in GitHub Desktop.
Simple python program to demonstrate the use of thread .
import threading
import sys
import time
import os
class ConsoleQuiz:
""""""
QUESTIONS = {
'01': {
'Question': {
'Captial Of India': {
'a': 'Delhi',
'b': 'Mumbai',
'c': 'Chennai',
'd': 'Kolkatta'
}},
'Answer': 'a'
},
'02': {
'Question': {
'Captial Of Pakistan': {
'a': 'Karanchi',
'b': 'Islmbd',
'c': 'Lahore',
'd': 'Baloch'
}},
'Answer': 'b'
},
'03': {
'Question': {
'Captial Of England': {
'a': 'Karanchi',
'b': 'Islmbd',
'c': 'London',
'd': 'Baloch'
}},
'Answer': 'c'
},
'04': {
'Question': {
'Captial Of America': {
'a': 'Karanchi',
'b': 'Islmbd',
'c': 'London',
'd': 'DC'
}},
'Answer': 'd'
}
}
def __init__(self):
""""""
self.score = 0
def timer(self):
""""""
for i in range(0, 11):
sys.stdout.write("\x1b7\x1b[%d;%df TIMER: %s\x1b8" % (1, 1, i))
sys.stdout.flush()
time.sleep(1)
self.exit()
def score_process(self):
""""""
while True:
sys.stdout.write(
"\x1b7\x1b[%d;%df CURRENT SCORE: %s\x1b8" % (2, 1, self.score))
sys.stdout.flush()
def start_threads(self):
""""""
timer_thread = threading.Thread(
target=self.timer,
)
score_thread = threading.Thread(
target=self.score_process,
)
timer_thread.start()
score_thread.start()
def play_game(self):
""""""
os.system('clear')
self.welcome_msg()
time.sleep(1)
self.start_threads()
try:
for key, value in self.QUESTIONS.items():
for question, option in value.get('Question', {}).items():
print('Question:')
print('---------')
print(f"{key}.", question)
print('Options: ')
for option_ind, option_name in option.items():
print(f"{option_ind}.", option_name)
print('---------')
ans = str(input('Answer: '))
if ans == 'q':
self.exit()
if ans == value.get('Answer'):
self.prompt(1)
else:
self.prompt(0)
except KeyboardInterrupt:
os.system('clear')
self.exit()
self.exit()
def exit(self):
""""""
print(f"Game Over, Score: {self.score}")
os._exit(0)
def prompt(self, ans):
""""""
if ans == 1:
self.score += 1
print("********************")
print("***Correct Answer***")
print("********************")
os.system('clear')
self.welcome_msg()
else:
print("XXXXXXXXXXXXXXXXXXXX")
print("XXXWroong AnswerXXX")
print("XXXXXXXXXXXXXXXXXXXX")
self.exit()
def welcome_msg(self):
print('')
print('')
print('\t \t \t Welcome to ConsoleQuiz \n')
print('\t \t \t------------------------ \n')
if __name__ == '__main__':
ob = ConsoleQuiz()
ob.play_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment