Binary Racing Game Backend
import random
num1 = random.randint(1, 10) ## Generates two numbers from 1 to 10
num2 = random.randint(1, 10)
answer = num1 + num2
x = random.randint(1, 5) ## These are placeholders for random values that will be used later
y = random.randint(-5, 0)
print(f"What is {num1} + {num2} =")
choices = [answer, answer + x, answer + y, answer - x] ## By using x and y it is possible to get more random answer choices
random.shuffle(choices) ## This re-orders the answer choices so that the answer is not always the first value
for choice in choices: ## Displays the choices
print(f"{choice}")
player_choice = input() ## This is where the user can input their answer
player_choice = int(player_choice) ## Determines if the answer is correct or not
if player_choice == answer:
print(f"You answered {player_choice}, that is CORRECT!")
else:
print(f"WRONG. The answer is {answer}, you put {player_choice}")
import random
num1 = random.randint(0, 32)
num2 = random.randint(0, 32)
binary1 = bin(num1)[2:].zfill(6)
binary2 = bin(num2)[2:].zfill(6)
print(f"What is {binary1} + {binary2} = ")
player_answer = input()
answer = bin(num1 + num2)[2:].zfill(6)
if player_answer == answer:
print(f"You answered {player_answer}, that is CORRECT!")
else:
print(f"INCORRECT. The correct answer was {answer}, you put {player_answer}.")
import random
def binary_game(): ## Changed to a class to make it easier to call many times
num1 = random.randint(0, 16) ## Generates a random number
num2 = random.randint(0, 16) ## 16 is set as the max
## The next part of the code allows the generated number to be changed into binary
## .zfill is used to make sure that the number goes up to 6-bits
binary1 = bin(num1)[2:].zfill(5) ## The string is sliced because the first two characters of the binary value were 0b
binary2 = bin(num2)[2:].zfill(5)
answer = bin(num1 + num2)[2:].zfill(5) ## Takes a sum
options = [answer]
while len(options) < 4: ## Makes it so that only 4 choices are generated
random_answer = bin(random.randint(0, 16))[2:].zfill(5)
if random_answer not in options:
options.append(random_answer)
random.shuffle(options) ## Shuffles the answer choices
print(f"{binary1} + {binary2} = ") ## Asks the question
for i, option in enumerate(options): ## Shows the list number
print(f"{i+1}. {option}")
player_answer = int(input("Enter your answer choice: "))
if options[player_answer-1] == answer:
print(f"You answered {player_answer}, that is CORRECT!")
else:
print(f"INCORRECT. The answer is {answer}, you put {player_answer}")
binary_game() ## Calls the function