6 Replies - 2620 Views - Last Post: 16 December 2012 - 11:11 PM Rate Topic: -----

#1 AulakhSam  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 11-November 12

Guess Number

Posted 16 December 2012 - 07:39 AM

This is my question:

Quote

CP1200 Assignment 1 - Number Guessing Game

You are to plan and then code a number guessing game, as described by the information and sample output below. Use what you have learned in class, including functions, but do not write any classes.

At the start of the program an appropriate welcome message with your name in it should be shown, then the user will be asked to enter their name. They then choose from a menu (see sample output for menu choices).
When the game is played, the computer randomly generates a number between lower and upper bounds (inclusive). These default to 1 and 42, but the user can choose to change them to any valid numbers between 0 and a number greater than the lower bound. The user must then guess a number. This guess should be error-checked until the user enters a valid guess. Error checking for all inputs should include handling non-numbers and blank entries. The user’s guess is then compared to the computer’s number, and the computer responds as below with higher or lower. When the guess is correct, the user is congratulated, told how many turns they took and offered the choice of saving their score to a file.
The file (as used for the sample output below) must be called scores.txt and is provided for you on LearnJCU. You must use this format. Each line contains the name of the player, a comma, a space, then the score. New entries are appended to the end of the file.
When the user chooses to view the scores from the menu, the scores are presented in sorted order (equal scores are listed with the more recent score(s) after the earlier ones), and in nicely aligned columns, as shown in the sample output.

You should make your program match the sample output from the program is below exactly (except for name and date). Do not add or remove anything from the program even if you think it would make it better. You must aim to have yours work and look just like this including spaces, spelling – everything.
Planning:
Write up the algorithms in pseudocode. For each function, you need separate pseudocode with a function header that shows any parameters. Follow the style of the answers provided for tutorial 5. You will also find the “Guide to Good Pseudocode” on LearnJCU helpful.
Please write your pseudocode in a docstring at the top of your code file.
You may show this part of the assignment to your tutor during practical time (after finishing your prac work) to get comments or suggestions. You can only get help from your tutors in practical time after your prac work is finished, and only if you show your planning.
No help will be given on code without seeing your planning first.

Program Code:
You need to hand in one complete, functional Python (.py) code file (version 3) containing appropriate comments (docstring with name, date, description at the top, planning docstring, and inline comments as appropriate). Please name this LastnameFirstnameA1.py

Submission:
Your single .py file should be submitted by uploading it in LearnJCU.

Due:
The assignment is to be submitted by Friday 4 PM week 9.
Submissions received after this date will incur late penalties as described in the subject guide.
Coding:
Part of the challenge (and assessment) for this assignment is for you to decide what programming constructs to use to solve the problem. Here are some guidelines:
• Use functions appropriately, where possible. Carefully think about the inputs and outputs for functions and ensure that they are useful and reusable, as discussed in class.
• Use one function for each menu option except quit, plus others as appropriate.
• You may find the string method isdigit() useful for error-checking.
• You may find a list of tuples is suitable for storing and sorting your high scores.
• Don't forget to close any files you open, at the appropriate spot(s) in your program.
• Use a default parameter for the scores filename. The user is not asked for the filename, but having it as a parameter to the function(s) that require the filename would make them more reusable.
• If you want to print a string within a variable width, you can use something like the following
print("%*s" % (width, name))
where width is an integer variable for the width and name is the string you want to print.


Sample Output (this forms part of the requirements):
(Bold text below shows user input. Where the user just pressed Enter, it says <blank>)


Welcome to the Greater CP1200 Guessing Game!
Written by Lindsay Ward, November 2012
See if you can get a high score
What is your name? <blank>
C'mon, tell me your name. Mark

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> v
High Scores:
John 3
Luke 6
Matthew 13

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> i
Invalid menu choice.

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> P
Please enter your guess, between 1 and 42: 20
My number is lower.
Please enter your guess, between 1 and 42: 10
My number is lower.
Please enter your guess, between 1 and 42: 5
My number is lower.
Please enter your guess, between 1 and 42: 3
My number is higher.
Please enter your guess, between 1 and 42: 4
You got it!
Well done, Mark. You guessed it in 5 guesses.

Would you like to save your score? (Y)es or (N)o: y
Saving high scores file...

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> V
High Scores:
John 3
Mark 5
Luke 6
Matthew 13

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> s
Setting Game Limits.
Low must be 0 or greater.
High must be greater than low.
Please enter a valid low bound integer: <blank>
Please enter a valid low bound integer: -5
Please enter a valid low bound integer: 0
Low bound is 0
Please enter a valid high bound integer greater than 0: 0
Please enter a valid high bound integer greater than 0: 5
High bound is 5

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> p
Please enter your guess, between 0 and 5: <blank>
Invalid guess.
Please enter your guess, between 0 and 5: 6
Invalid guess.
Please enter your guess, between 0 and 5: a
Invalid guess.
Please enter your guess, between 0 and 5: 1
My number is higher.
Please enter your guess, between 0 and 5: 2
My number is higher.
Please enter your guess, between 0 and 5: 3
You got it!
Well done, Mark. You guessed it in 3 guesses.

Would you like to save your score? (Y)es or (N)o: Y
Saving high scores file...

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> s
Setting Game Limits.
Low must be 0 or greater.
High must be greater than low.
Please enter a valid low bound integer: 1
Low bound is 1
Please enter a valid high bound integer greater than 1: 2
High bound is 2

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> p
Please enter your guess, between 1 and 2: 1
You got it!
Well done, Mark. You guessed it in 1 guesses.

Would you like to save your score? (Y)es or (N)o: n

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> v
High Scores:
John 3
Mark 3
Mark 5
Luke 6
Matthew 13

Menu:
(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> Q
Thank you for playing, Mark.


Marking scheme follows on the next page…
Marking Scheme
Take note of the following marking criteria so that you know what needs to be done for marks.
Don't just try and get your program to work, but instead do proper planning followed by careful coding. Make sure you give attention to what is rewarded here. You may notice that you don’t get a whole lot of marks for just getting it to work.

Requirement Marks Out Of
Algorithm – Pseudocode – for each function, including main
(clear, complete, well-formatted, consistent, accurate) 4
Program Execution
Setting game limits 1
Displaying high scores file 1
Saving high scores file 1
Playing the guessing game 1
Similarity to sample output (including all formatting) 1
Quality of Code
Meaningful identifiers (variables, constants, functions) 1
Code readability: formatting, indentation, line spacing, etc. 1
Useful, descriptive comments
(good amount & quality – docstring at top and for each function + inline comments) 2
Code Constructs
Use of functions (inputs, outputs, logical choices of functions) 2
Method for storing and sorting high scores 2
Method for handling invalid data 2
Default parameter for filename 1
Deductions
Inappropriate or sloppy code, global variables,
literals used where constants would be better, other bad things… -2
Incorrect submission (must be 1 Python file) -1
Total 20


import random
print "Welcome to the Great CP1200 Guessing Game! \nWritten by Aulakh Sam..., November 2012 \nSee if you can get a high score"
userName = raw_input("What is your name: ")
while True:
    print "\nMenu: \n(V)iew High Scores \n(P)lay Game \n(Q)uit"
    userCommand = raw_input(">>>")
    userCommand = userCommand.upper()
    if userCommand == 'Q':
        print "Thankyou for playing."
        break
    elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores.txt", 'r')
        scores = scoresFile.read()
        scoresFile.close()
        score_name = []
        for line in scores.split('\n'):
            userName, score = line.split(',')
            score = int(score)
            score_name.append((score, userScore))
        for score, userScore in sorted(score_name):
            print "%-18s %s" % (userScore, score)
            
    elif userCommand == 'P':
        smallestNum = 1
        largestNum = 42
        randomNumber = random.randint(smallestNum, largestNum)
        numGuesses =0
        while True:
            numGuesses += 1
            userGuess = input("Please enter a number between %s and %s:" % (smallestNum, largestNum))
            
            if userGuess <smallestNum or userGuess >largestNum:
                print "Invalid guess."
            elif userGuess > randomNumber:
                print "My number is lower"
            elif userGuess < randomNumber:
              print "My number is higher"
            else:
                print "You got it! \nWell done,", userName + ". " "You guessed it in", numGuesses, "guesses. \n"
                saveScore = raw_input("Would you like to save your score? (Y)es or (N)o: ")
                saveScore = saveScore.upper()
                if saveScore == 'N':
                    break
                elif saveScore == 'Y':
                    print "Saving high scores file..."
                    highScore = userName + ", " + str(numGuesses)
                    highScore = str(highScore)
                    scoresFile = open("scores.txt", 'a')
                    scoresFile.write('\n' + highScore)
                    scoresFile.close()
                    break
            
    else:
        print "Invalid menu choice."



I am getting error on line 18 and secondly please help me how to write: (S)et Game Limits

Is This A Good Question/Topic? 0
  • +

Replies To: Guess Number

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2143
  • View blog
  • Posts: 3,295
  • Joined: 21-June 11

Re: Guess Number

Posted 16 December 2012 - 07:46 AM

Which error are you getting on line 18?
Was This Post Helpful? 0
  • +
  • -

#3 AulakhSam  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 11-November 12

Re: Guess Number

Posted 16 December 2012 - 08:07 AM

View Postsepp2k, on 16 December 2012 - 07:46 AM, said:

Which error are you getting on line 18?

Traceback (most recent call last):
  File "C:/Python27/Ch-1/Assignment 1.py", line 18, in <module>
    userName, score = line.split(',')
ValueError: need more than 1 value to unpack
>>> 

Was This Post Helpful? 0
  • +
  • -

#4 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2143
  • View blog
  • Posts: 3,295
  • Joined: 21-June 11

Re: Guess Number

Posted 16 December 2012 - 08:30 AM

That error message is telling you that line.split(',') must return a list containing more than item in order for the mass-assignment userName, scoe = line.split(',') to work. So apparently line.split(',') returned a list with only one item, which means that the line did not contain a comma.
Was This Post Helpful? 1
  • +
  • -

#5 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: Guess Number

Posted 16 December 2012 - 12:13 PM

A little more hint:

Think about what the read() call on line 14 actually returns. You may put a print repr() statement on the following line for debugging to see what is wrong. That way you will see all those "\n" on which you split:
...
scores = scoresFile.read()
print repr(scores)
...


Was This Post Helpful? 1
  • +
  • -

#6 AulakhSam  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 11-November 12

Re: Guess Number

Posted 16 December 2012 - 08:54 PM

import random

smallestNum = 1
largestNum = 42
userName = ""
print ("Welcome to the Great CP1200 Guessing Game! \nWritten by Aulakh Sam..., November 2012 \nSee if you can get a high score")
n = 0
while True:
    n = n + 1
    if n > 1:
        userName = raw_input("C'mon, tell me your name.")
    else:
        userName = raw_input("What is your name: ")
    if userName.isalpha():
      
      break
    
      
while True:
    print ("\nMenu: \n(V)iew High Scores \n(P)lay Game \n(S)et Game Limits \n(Q)uit")
    userCommand = raw_input(">>>")
    userCommand = userCommand.upper()
    if userCommand == 'Q':
      print ("Thankyou for playing.")
      break
    elif userCommand == 'V':
      print ("High Scores:")
      filename = ("scores.txt")
      scoreDict = dict()
      try:
        file = open(filename, "r")
      except:
        print("error to open file")
      try:
        for line in file.readlines():
          line = line.replace ("\n", "")
          userName, scoreValue = line.split(',')
          scoreDict[userName] = scoreValue
          for key, value in sorted(scoreDict.items(), key = (lambda k: k[1])):
            print ("%s, %s" % (key, value))
      except IOError:
        print ("Error in reading data from %s" %file)

      file.close()

    elif userCommand == 'S':
        print ("Setting Game Limits. \nLow must be 0 or greater. \nHigh must be greater than low.")
        while True:
          smallestNum = raw_input("Please enter a valid low bound integer:")
          largestNum = raw_input("Please enter a valid high bound integer greater than 0:")
          if smallestNum.isdigit() and largestNum.isdigit:
            smallestNum = int(smallestNum)
            largestNum = int(largestNum)
            if smallestNum < 0:
              print ("low bound must be greater than 0")
            elif largestNum < 0:
              print ("high bound must be greater than 0")
            elif largestNum <= smallestNum:
              print ("high bound must be greater than low bound")
            else:
              print ("new Bounds are set")
              break
          else:
            print ("Please enter a Integer")

    elif userCommand == 'P':
      randomNumber = random.randint(smallestNum, largestNum)
      numGuesses = int(0)
      while True:
        userGuess = raw_input("Please enter a number between %s and %s:" % (smallestNum, largestNum))
        if userGuess.isdigit():
          userGuess = int(userGuess)
          if userGuess < smallestNum or userGuess > largestNum:
            print ("Invalid guess.")
          elif userGuess > randomNumber:
            print ("My number is lower")
          elif userGuess < randomNumber:
            print ("My number is higher")
          else:
            print ("You got it! \nWell done,", userName + ". " "You guessed it in", numGuesses, "guesses. \n")
            saveScore = raw_input("Would you like to save your score? (Y)es or (N)o: ")
            saveScore = saveScore.upper()
            if saveScore == 'N':
              break
            elif saveScore == 'Y':
              print ("Saving high scores file...")
              highScore = userName + ", " + str(numGuesses)
              highScore = str(highScore)
              scoresFile = open("scores.txt", 'a')
              scoresFile.write('\n' + highScore)
              scoresFile.close()
              break
        else:
          print ("Please enter a Integer")
    else:
      print ("Invalid menu choice.")



The above is the code i have written so far but can some one check whether it meets the questions requirement.

Question: Question
Was This Post Helpful? 0
  • +
  • -

#7 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7947
  • View blog
  • Posts: 13,531
  • Joined: 19-March 11

Re: Guess Number

Posted 16 December 2012 - 11:11 PM

If you run it and follow the script given in the question as you posted it, do you get the right responses?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1