Learn Python With Dhawal -10- Chapter - Write A Code For Stone Paper Scissor Game


CHAPTER 10

I feel we have been far enough in our python journey to write a short little fun game to play when we get bored coding. This is a very short program to play Stone, Paper, Scissors with your computer using python. Remember, we aren't on that level where we start working on UI/UX and make a proper app. This would be a barebones app that can run in any terminal or IDLE. This fun little exercise will help you to build your logic further stronger. Obviously on later stages we might use graphical APIs to make a UI for it and make it a real app instead of barebones working code. But for now let's begin with it.

Input :


  1. import random
  2. computerScore=0
  3. userScore=0
  4. continuePlaying=1
  5. Guide={1:"Stone",2:"Paper",3:"Scissor"}

  6. #function to determine who wins and calculate the score
  7. def game(user,computer):
  8.     global computerScore
  9.     global userScore
  10.     if(user==computer):
  11.         print("It's a tie, please play again.")
  12.     elif(user==1 and computer==2):
  13.         print("Computer Wins")
  14.         computerScore+=1
  15.     elif(user==1 and computer==3):
  16.         print("User wins")
  17.         userScore+=1
  18.     elif(user==2 and computer==1):
  19.         print("User wins")
  20.         userScore+=1
  21.     elif(user==2 and computer==3):
  22.         print("Computer Wins")
  23.         computerScore+=1
  24.     elif(user==3 and computer==1):
  25.         print("Computer Wins")
  26.         computerScore+=1
  27.     elif(user==3 and computer==2):
  28.         print("User wins")
  29.         userScore+=1


  30. while(continuePlaying==1):
  31.     #User takes a number from 1-3
  32.     user=int(input("Enter your Choice\n1. Stone\n2. Paper\n3. Scissors\n"))
  33.     #Now we will check for wrong inputs
  34.     if(user>0 and user<4):
  35.         #Now Computer will make a random choice from 1-3
  36.         computer=random.randint(1,3)
  37.         print("User: ",Guide[user],"Computer: ",Guide[computer])
  38.         game(user,computer)
  39.     else:
  40.         print("Invalid Choice, Please Enter A Valid Choice")
  41.         
  42.     continuePlaying=int(input("Do you wish to Continue Playing?\nEnter 1 for Yes and 0 for No\n"))


  43. print("The total scores are : ")
  44. print("User :",userScore)
  45. print("Computer :",computerScore)

  46. if(userScore>computerScore):
  47.     print("User Wins")
  48. elif(computerScore>userScore):
  49.     print("Computer Wins")
  50. else:
  51.     print("It's a tie")
Output:
  1. Enter your Choice
  2. 1. Stone
  3. 2. Paper
  4. 3. Scissors
  5. 1
  6. User:  Stone Computer:  Scissor
  7. User wins
  8. Do you wish to Continue Playing?
  9. Enter 1 for Yes and 0 for No
  10. 0
  11. The total scores are : 
  12. User : 1
  13. Computer : 0
  14. User Wins


  1.  As you can see in line number one we import random, now random is a library we use just like math to bring on some functions that we need to use. You'd see where we are using random in next few lines of code.
  2. Next we create variables computerScore and userScore and initialize both of them to a value 0. Then we create a variable continuePlaying and assign 1 as value to it.
  3. Then we create a dictionary named Guide and assign the key-value pairs. You can skip this step if you want to but later on you'd require to make changes in code. It just makes the game look more real and connecting hence it isn't affecting the actual code even if you remove it. The main logic of the game would still work fine.
  4. Now we build the main logic of our game. It is most easiest as well as complicated part of the code. Easiest as you already know how the Stone, Paper, Scissor game works but complicated part would be implementing that on a computer and make it understand how to play it fair and square.
  5. We define a function named game and pass two variables user and computer as arguments. Remember, we always write the definition of a function before we call it. So if you miss the sequence you might be getting an error. Python is interpreted language and it would cause issue. So we have to write the code in this sequence. 
  6. Next you'd notice something funny. I have written global before the variable computerScore and userScore. Global variables are the ones which can be accessed anywhere in the program. When you create a variable inside the function it's scope aka its life is just inside the function. So when you want to call a global variable inside a function you need to mention that its a global variable that you're using and not creating a new variable with a same name.
  7. Similarly the variables user and computer that we would be using have their scope limited to the function. We just have created the variables using the same name so as to avoid the confusion. You can make new names for the variables that we would be using inside the function if you want, but for simplicity I have kept it the same.
  8. Then we build our IF...ELSE condition staircase to determine the results of the game depending upon the inputs given by user and computer. First we check whether both inputs are same if so we say 'it is a tie' and then we ask user to enter the input once again.
  9. If the inputs are fine and both computer and user input aren't same then we proceed to check who is the winner. We have assigned values to Stone as 1, Paper as 2 and Scissor as 3 for simplicity. You can take the literal names for this purpose as well but it would be a hassle to type and check strings as inputs and make the game slower without any specific benefits for it.
  10. Just build your IF...ELSE nested logic and finish the code. When user wins we increase the userScore variable by 1 and same goes for computer as when computer wins we increase the computerScore variable by 1.
  11. Now our main logic of the game which will decide who wins is done. Next step is that we have to take inputs both from computer and user.
  12. For that I am using a while loop which will keep running as long as the value of continuePlaying variable is 1. Now I have not used the trick like previous codes below as here we are taking user input and if user enters 1 it acts as a boolean true and if user enters 0 it acts as a boolean false but what if user enters something rubbish? The program will crash. Hence if user enters anything else than 1, the game will wind up and just display the final scores and results.
  13. Now we ask user for an input and take it into a variable like we usually do. Then we check if the entered input is greater than 0 and less than 4 which means it can be any of 1,2 or 3 and not anything rubbish. If it is anything else, we will display error message and ask user to enter the input again.
  14. Now if the user input is within range(1,3) we continue and ask computer to generate a integer number between 1 to 3. for that we would use random.randint() method and pass (1,3) as range inside as arguments. This will generate a random number from 1-3 anytime we execute this line of code.
  15. Now, this step is just for fun. We want to know what we gave as input and what computer gave as output. So we will print the names using the Guide that we had previously created and pass the key values as variables user and computer here. This will print what a user has chosen and what computer has chosen i.e. if the user entered 1 as input it will print stone and if computer entered input as 2 it will print paper using 1 and 2 as key values from our dictionary Guide.
  16. Now we call the function game and pass the inputs as arguments. Once it runs then we will ask the user if the want to play again or quit the game. If input is 1 it will run again and else it'll move on to next step.
  17. Now we print the individual scores of user and computer then we create IF....ELSE nested ladder to find out who is the winner and if its a tie and print the result accordingly.
  18. As further touch up steps you can add more conditions and make it much more complex as you want. Like if there's no input from user even once you can say the game was never played. You can add one more variable and loop for it or just one if condition and print statement. Play around with the code and enjoy.



I hope you enjoyed as much as I did writing this chapter. Here you learnt something more about loops, variables as well as functions in a gist and how to go about using them and build your own logic for various things.

<< PREVIOUS CHAPTER || NEXT CHAPTER >>

~*~*~*~

This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it.

~*~*~*~

Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Are you getting regular fresh content updates? If not click on the button below.

0 comments:

Post a Comment

Do comment and share your thoughts.