OK. So here I am with the first game ” Guess The Number “, from Al Sweigart’s book Invent Your Own Computer Games With Python.  Chapter No 4. Page 28 to 49.

This is a cool guessing game, which gives a player six chances to guess a random number chosen by the computer from 0 to 20. With each guess the computer provides hint whether the guessed number is high or low to the chosen number thereby helping the user to come  closer to the number.

I suggest reading the above mentioned pages for the detailed explanation of how the program works. It is a great example to practice conditional statement, loops, accepting user input and print statement.

Well as mentioned in my previous post Making Games In Python, all programs are in python3. I did this program with python2.7 and it worked well.Following needs to be done to tweak it for python2.7

  • The random module works fine.
  • Instead of input we need to use raw_input
  • and instead of print(‘foo’) we need to use print ‘foo’ i.e. no parenthesis
  • No changes in if statements and while loop

Here goes the code:

#This is a guess the number game
#Adopted from Al Sweigart book Invent your own Computer Games with Python.Chapter 4

import random

guessTaken=0

print “Hello! What is your name?”

myName=raw_input()

number = random.randint(1,20)

print “Well, “+myName +” ,I am thinking of a number between 1 and 20″

while guessTaken <6:
print “Take a guess”
guess=raw_input()
guess=int(guess)

guessTaken=guessTaken + 1

if guess<number:
print “Your Guess is low”

if guess> number:
print “Your Guess is High”

if guess == number:
break

if guess==number:
guessesTaken=str(guessTaken)
print “Good Job, “+myName+”! You guessed my number in “\
+guessesTaken+” guesses.”

if guess!=number:
number=str(number)
print “Nope. The number I was thinking of was “+number

And here is the output . I guessed the number correctly in the first run :D

Hello! What is your name?
Deepak
Well, Deepak ,I am thinking of a number between 1 and 20
Take a guess
10
Your Guess is low
Take a guess
18
Your Guess is High
Take a guess
13
Your Guess is low
Take a guess
16
Good Job, Deepak! You guessed my number in 4 guesses.

Its a simple game and from my experience simple games are the ones that are most addictive. Try out this game and suggest me if you have any ideas to extend this game further.

Till then Happy Hacking :)

About these ads