-1

I'm trying to create this program

  • Print a welcome message, and then prompt the user to select a difficulty by entering 1, 2 or 3.
  • Use a loop to re-prompt the user until a valid response (1, 2 or 3) is entered.

Once a difficulty has been selected, print a message confirming the selected difficulty and set variables as follows:

  • 1 was chosen:
    lives = 3, max_num = 10 and questions = 5

  • 2 chosen:
    lives = 2, max_num = 25 and questions = 10

  • 3 was chosen:
    lives = 1, max_num = 50 and questions = 15

lives represents how many incorrect answers are permitted.
max_num represents the largest number enter code here used when generating a question.
questions represents the number of questions

The code below is what i have done so far

def input_valid_difficulty(prompt=''):
    while True:
        try:
            n = int(input(prompt))
            if n < 0 or n > 3:
                raise ValueError
                break
        except ValueError:
            print("Invalid choice! Enter 1,2 or 3.")
            prompt = "Select a difficulty?: (0 to exit):"
    return n

difficulty = input_valid_difficulty ("Select a difficulty?: (0 to exit):")
if difficulty == 0:
    quit()
elif difficulty == 1:
    print("Easy mode selected!")
elif difficulty == 2:
    print("Medium mode selected!")
elif difficulty == 3:
    print("Hard mode selected!")
Max
  • 6,821
  • 3
  • 43
  • 59
  • 1
    What problem are you having? Seems you could set lives and max_num based upon difficulty returned. – DarrylG Sep 14 '19 at 12:38
  • can you elaborate please. – Rory Breaker Sep 14 '19 at 13:08
  • Seems in you "elif" conditionals (where you have the print statements) you could set lives and max_num to the desired values to give you what you want. Am I missing something? – DarrylG Sep 14 '19 at 13:17
  • yes sorry. its meant to be a math game which will allow the user to answer math equations. i need the end product to look like: Welcome to test. Select difficulty.' user selects easy' and after that i need the game to go straight in "question 1 of 5. you have 3 lives remaining. What is 5-3? User gives answer and gets a response either its correct or incorrect. – Rory Breaker Sep 14 '19 at 13:29
  • Posted a possible implementation of your game. – DarrylG Sep 14 '19 at 14:16
  • Was it clear how I generated the total list of questions as (question, answer) tuples and then randomly selected a subset of these questions? – DarrylG Sep 14 '19 at 15:24
  • Welcome to Stack Overflow! I edited the title of your question to better understand what you asking, so more people with knowledge of the subject will see it. I also indented your code sample by 4 spaces so that it renders properly - please see the editing help for more information on formatting. Please edit in the specific error-message or problem you're encountering in case that's necessary to identify the specific problem. Good luck! – Max Sep 14 '19 at 22:52

1 Answers1

0

Here's an example of generating a game you descibed.

from random import sample

def input_valid_difficulty(prompt=''):
    while True:
        try:
            n = int(input(prompt))
            if n < 0 or n > 3:
                raise ValueError
            break
        except ValueError:
            print("Invalid choice! Enter 1,2 or 3.")
            prompt = "Select a difficulty?: (0 to exit):"
    return n

# Setup Difficult & Lives
difficulty = input_valid_difficulty ("Select a difficulty?: (0 to exit):")
if difficulty == 0:
    quit()
elif difficulty == 1:
    print("Easy mode selected!")
    lives, max_num, questions = 3, 10, 5
elif difficulty == 2:
    print("Medium mode selected!")
    lives, max_num, questions = 2, 25, 10
elif difficulty == 3:
    print("Hard mode selected!")
    lives, max_num, questions = 1, 50, 15

# Following line generates a list of 800 questions to choose from
operations = ['+', '-']  # testing addition and subtraction

#all_q_and_a = [(f"{i} {op} {j} = ?: ", eval(f"{i} {op} {j}")) for i in range(20) \
#                      for j in range(20) for op in operations]
# Following equivalent to above list comprehension
all_q_and_a = []
for i in range(20):
  for j in range(20):
    for op in operations:
      all_q_and_a.append((f"{i} {op} {j} = ?: ", eval(f"{i} {op} {j}")))

# Select random questions from list of all questions at random (note: 'questions' tells us how many questions to ask)
# 'Sample' selects a random list of unique questions from complete list
chosen_q_and_a = sample(all_q_and_a, questions)

# We now have a random set of questions and answers to present to 
# the user.  An example would be:
# [('18 + 19 = ?: ', 37), ('4 + 12 = ?: ', 16), ('8 + 2 = ?: ', 10), ('4 - 2 = ?: ', 2), ('1 + 3 = ?: ', 4)]

score = 0
for q in chosen_q_and_a:
  if lives == 0:
    break
  while lives > 0:
    answer = int(input(q[0]))
    if answer == q[1]:
      print("Correct")
      score += max_num  # increase score according to max_num 
                        #(wasn't sure if there was any
                        #other use of this variable)
      break
    else:
      lives -= 1
      print("Sorry, try again")

print(f"Your score was {score}")
DarrylG
  • 16,732
  • 2
  • 17
  • 23
  • i am receiving a error for all q_and_a= line, the error is on the 'for i in range'' – Rory Breaker Sep 14 '19 at 15:28
  • You're probably missing the continuation line indicator. Can you see and test the code here: https://repl.it/repls/SelfassuredIntentionalUsernames – DarrylG Sep 14 '19 at 15:46
  • Could be because i am using windows? – Rory Breaker Sep 14 '19 at 16:25
  • So am I. Does the link I provided work? That's on a cloud server and just uses your browser so it won't matter what you're on. If that works you can try on your machine with Jupyter notebooks, Pycharm, Visual Studio, etc. – DarrylG Sep 14 '19 at 16:31
  • You just have to hit the "run" button (greenish color) towards the top middle of the screen to run it. – DarrylG Sep 14 '19 at 16:32
  • it runs fine on there. why wouldn't it run on mine? – Rory Breaker Sep 14 '19 at 17:11
  • I replaced the triple long continuation line with a three lines for a triple for loop. You can see if this works better for you. – DarrylG Sep 14 '19 at 17:12
  • all_q_and_a = list() I made that change and it started working on my one. However it works for choice 2 and choice 3 but does not work for choice 1. – Rory Breaker Sep 15 '19 at 06:41
  • @RoryBreaker What error do you get for choice 1? Also not sure why changing from (1) all_q_and_a = [], to (2) all_q_and_a = list() would make any difference. They should be the same except (1) is faster per https://stackoverflow.com/questions/2972212/creating-an-empty-list-in-python. – DarrylG Sep 15 '19 at 08:57
  • yeah it works, spelling error is what was holding me back. – Rory Breaker Sep 15 '19 at 09:21
  • Hooray!!! By the way do you see how you can add additional operations such as multiply (i.e. ops = ['+', '-', '*']). Or, you can replace with your own question entirely by creating your own all_q_and_a of the same structure. – DarrylG Sep 15 '19 at 09:29