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. Note that the input function will return a string – we will convert it into an integer using the int function.

  4. Use the function random.randint(1,10) 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 inside of a for loop which iterates 3 times.

  8. Inside the for loop, use an accumulator variable and an if-statement to keep track of the number of times that the user won. Print out who won the best out of three, e.g., User won best out of 3! or Computer won best out of 3!

If you finish early

  1. Use the turtle module to draw a smiley face if the user wins, and a sad face if the computer wins.

  2. 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!”

  3. 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!