Having trouble coding a beginner game

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Hamy Li
    New Member
    • Mar 2008
    • 15

    Having trouble coding a beginner game

    In a book that I'm learning, there is a project which I have to create a game called "Guess my number". In this game, I pick a number from 1 to 100 and let the computer guess my number. I don't know how code control the numbers i type

    Code:
    .
    
    number = raw_input("Enter a Number: ")
    if number < "1":
      print "invalid"
    if number > "100":
      print "invalid
    else:
      print "continue"
    i don't know what is wrong with this
    can anyone please help. will really appreciate
    I'm using python 2.5
  • dazzler
    New Member
    • Nov 2007
    • 75

    #2
    [CODE=python].

    number = raw_input("Ente r a Number: ")
    if number < "1":
    print "invalid"
    if number > "100":
    print "invalid
    else:
    print "continue"

    [/CODE]

    instead of if number < "1":
    try this if number < 1:
    if you use "" it means that it is text not numbers

    and now your raw_input will be saved as text (string) also, and it can't compare text and numbers, so you have to convert it to numeric using float() or int()

    number = float(raw_input ("enter number"))

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #3
      You need to convert your raw_input to an integer with the int() function. Thus, you can use integer comparisons (which will give the correct results), not string comparisons.

      [CODE=python]
      >>>number = raw_input("Plea se enter a number: ")
      Please enter a number: 14
      >>>print number
      14
      >>>number < "100"
      False
      >>>number > "1"
      True
      >>>number = int(raw_input(" Please enter a number: ")
      Please enter a number: 14
      >>>number < 100
      True
      [/CODE]

      The >>> means this is code that I ran on the Python interactive shell.

      Comment

      • Hamy Li
        New Member
        • Mar 2008
        • 15

        #4
        thank you very much for all your help. really saved my time.
        I also have a new question based on the same game.

        Code:
        import random
        print "\tWelcome to 'Guess My Number'!"
        print "\nI'm thinking of a number between 1 and 100."
        print "Try to guess it in as few attempts as possible.\n"
        # set the initial values
        the_number = random.randrange(100) + 1
        guess = int(raw_input("Take a guess: "))
        tries = 1
        # guessing loop
        while (guess != the_number):
            if (guess > the_number):
                print "Lower..."
            else:
                print "Higher..."
        
            guess = int(raw_input("Take a guess: "))
            tries += 1
        print "You guessed it! The number was", the_number
        print "And it only took you", tries, "tries!\n"
        how do i reverse this game so that i pick a number and the computer has to guess what number it is.
        I tried to code it but i got stuck.
        any help would be grateful

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Here I will use random.choice for the computer to select a number. I will give the computer a hint 'lower' and 'higher' each time. Each choice will be removed from the possible choices.[code=Python]import random

          def guess_number_re v(lower=1, upper=100):
          number = int(raw_input(' Enter a number between %d and %d' % (lower, upper)))
          # list of possible guesses
          guessList = (range(lower,up per+1))
          if number not in guessList:
          print 'Invalid entry! Exiting...'
          return
          # get a random number
          guess = random.choice(r ange(lower,uppe r+1))
          # remove first guess
          guessList.remov e(guess)
          # create a list of guesses the computer made
          guesses = [guess, ]
          while True:
          if guess > number:
          guess = random.choice([num for num in guessList if num < guess])
          elif guess < number:
          guess = random.choice([num for num in guessList if num > guess])
          else:
          break
          guessList.remov e(guess)
          guesses.append( guess)
          print 'The number entered: %d' % number
          print 'It took the computer %d guesses' % (len(guesses))
          print 'Guesses made:\n%s' % '\n'.join([str(n) for n in guesses])

          guess_number_re v()
          [/code]

          Sample output:
          >>> The number entered: 67
          It took the computer 8 guesses
          Guesses made:
          49
          79
          23
          29
          61
          94
          62
          67
          >>>

          Comment

          • Hamy Li
            New Member
            • Mar 2008
            • 15

            #6
            thanks for the help. may I ask what version of python you are using?
            because when i wrote the code in python and tried to run it
            if comes up with this error

            Token Error: EOF in multi-line statement

            what does this error mean?

            Comment

            • Laharl
              Recognized Expert Contributor
              • Sep 2007
              • 849

              #7
              Check your indentation/spacing at the very end of the file, as you've probably got something screwed up there.

              Comment

              • Hamy Li
                New Member
                • Mar 2008
                • 15

                #8
                A new question.
                In a book I'm using, It has a few challenges every chapter. In the chapter I'm reviewing right now, It wants me make a program where the computer lets the user write a message the then prints the message backwards. I know this may sound very easy, but all i can use in my coding is the skills in that chapter.
                the skills included in that chapter is
                indexing
                slicing
                for loops
                random.choice
                creating tuples
                using tuples.

                using only these skills, i can't seem to figure how to print a message backwards.

                Code:
                print "Welcome to the backward machine. "
                print "Write in a message and the computer will print it backwards"
                
                message = raw_input("Enter a message: ")
                there were my first 3 lines. after that, I tried using indexing and for loops but non came out right.
                Please help.

                thank you

                Comment

                • Laharl
                  Recognized Expert Contributor
                  • Sep 2007
                  • 849

                  #9
                  Did your book cover reverse/negative indexing? That might be of use...

                  Comment

                  • jlm699
                    Contributor
                    • Jul 2007
                    • 314

                    #10
                    Are you allowed to use list reversal?

                    [code=python]print 'Welcome to the backward machine.'
                    print 'Write in a message and the computer will print it backwards'

                    message = raw_input('Ente r a message: ')
                    new_msg = ''
                    rev_idx = range(len(messa ge))
                    rev_idx.reverse ()
                    for idx in rev_idx:
                    new_msg += message[idx]

                    print 'The backwards message is:', new_msg[/code]
                    Output:
                    Code:
                    Microsoft Windows XP [Version 5.1.2600]
                    (C) Copyright 1985-2001 Microsoft Corp.
                    
                    C:\Documents and Settings\Administrator\Desktop\pythtests>python bckmch.py
                    Welcome to the backward machine.
                    Write in a message and the computer will print it backwards
                    Enter a message: wtf
                    The backwards message is: ftw
                    
                    C:\Documents and Settings\Administrator\Desktop\pythtests>

                    Comment

                    • bvdet
                      Recognized Expert Specialist
                      • Oct 2006
                      • 2851

                      #11
                      Here is another possibility:
                      [code=Python]>>> word = 'supposition'
                      >>> print ''.join([word[i] for i in range(len(word)-1, -1, -1)])
                      noitisoppus
                      >>> [/code]

                      Comment

                      • Hamy Li
                        New Member
                        • Mar 2008
                        • 15

                        #12
                        thanks alot to all of you.
                        great help.

                        Comment

                        • Hamy Li
                          New Member
                          • Mar 2008
                          • 15

                          #13
                          the below program chooses a random word then asks the user to guess a letter.
                          the user has 5 tries to guess a letter. After 5 tries, the user has to guess the word its self. I tried coding this program. It worked, but i want to know if there is a better way of writing this program. because as you can see, it is very long for such a small program. how can a loop be used in this program instead of the separate 5 if-else commands.

                          Code:
                          import random
                          WORDS = ("happy", "sad", "congratulations", "normal", "bad", "smart")
                          word = random.choice(WORDS)
                          tries = 1
                          print "There are", len(word), "letters in this word."
                          
                          guess = raw_input("Enter the letter you want to guess: ")
                          if guess in word:
                              print "\nthe letter you picked is in the word. "
                          else:
                              print "\nthe letter is not in the word"
                          tries += 1
                          
                          guess = raw_input("Enter the letter you want to guess: ")
                          if guess in word:
                              print "\nthe letter you picked is in the word. "
                          else:
                              print "\nthe letter is not in the word"
                          tries += 1
                          
                          guess = raw_input("Enter the letter you want to guess: ")
                          if guess in word:
                              print "\nthe letter you picked is in the word. "
                          else:
                              print "\nthe letter is not in the word"
                          tries += 1
                          
                          guess = raw_input("Enter the letter you want to guess: ")
                          if guess in word:
                              print "\nthe letter you picked is in the word. "
                          else:
                              print "\nthe letter is not in the word"
                          tries += 1
                          
                          guess = raw_input("Enter the letter you want to guess: ")
                          if guess in word:
                              print "\nthe letter you picked is in the word. "
                          else:
                              print "\nthe letter is not in the word"
                          tries += 1
                          
                          print " you do not have any more guesses"
                          print "please guesses the word"
                          guess_words = raw_input("\nEnter you guess of the word: ")
                          if guess_words == word:
                              print "Congratulations, you guessed it"
                          else:
                              print "sorry, you failed"
                          
                          raw_input("\n\nPress the Enter key to exit")

                          thanks

                          ohh. and how do i post codes as python codes so the color shows?

                          Comment

                          • Subsciber123
                            New Member
                            • Nov 2006
                            • 87

                            #14
                            Firstly, you show python code by using the code tags, but putting "=python" after the word "CODE"

                            Secondly, yes, you can use loops.

                            The first thing you should do is get rid of the variable "tries". You don't use it for anything.
                            Next, put one of your if statements inside a for loop as so, and get rid of the rest of them:
                            [CODE=python]for i in range(5):
                            guess = raw_input("Ente r the letter you want to guess: ")
                            if guess in word:
                            print "\nthe letter you picked is in the word."
                            else:
                            print "\nthe letter is not in the word"[/CODE]

                            Comment

                            Working...