CS 100

Logo

Scientific Computing

Activity 12 - A game! 🎲

  1. Create a file called game.py in cs100/ch2. Copy the following into your file. Your program will wait for you to type something in the shell area and press enter.
    answer = input("Type something in: ")
    print(answer)
    
  2. Try running it again, but this time type something different when prompted. What’s happening? Write in comments.

  3. Use this new input function to ask the user for a number between 1 and 10. Store the result in a variable guess.

  4. Use the function random.randint(1,11) to generate a random number between 1 and 10. Store the result in another variable answer.

  5. Print out whether the user’s guess matches the correct answer (if the user won or the computer won). Try playing your game!

  6. Put all of the code you wrote into a single function playGame() which returns True or False depending on whether the user won.

  7. Call your function three times. Print out who won the best out of three.

If you finish early

  1. Ask the user at the beginning of the game how many times they would like to play. Use this number to determine how many times you call the playGame() function. Adapt your final output so that it reads, for example, “Computer won 8/10; Human won 2/10. Computer wins!”

  2. Play this interactive text-based game. Notice how there’s a limited set of inputs that the user can type. Depending on what the user types, something happens. Think about how you might make an interactive story of your own!