# Guess Number

Page 1 of 1

## 6 Replies - 5198 Views - Last Post: 16 December 2012 - 11:11 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=304104&amp;s=33bc3dd76404d2ea8d36e07e581bcbcd&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 AulakhSam

Reputation: 0
• 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.
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:

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
C'mon, tell me your name. Mark

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

(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> i

(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> P
My number is lower.
My number is lower.
My number is lower.
My number is higher.
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...

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

(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

(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> p
Invalid guess.
Invalid guess.
Invalid guess.
My number is higher.
My number is higher.
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...

(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

(V)iew High Scores
(P)lay Game
(S)et Game Limits
(Q)uit
>>> p
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

(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

(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
(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"
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')
scoresFile.close()
score_name = []
for line in scores.split('\n'):
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:

```

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

• D.I.C Lover

Reputation: 2579
• Posts: 4,123
• Joined: 21-June 11

## Re: Guess Number

Posted 16 December 2012 - 07:46 AM

Which error are you getting on line 18?

### #3 AulakhSam

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

## Re: Guess Number

Posted 16 December 2012 - 08:07 AM

sepp2k, 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>
ValueError: need more than 1 value to unpack
>>>
```

### #4 sepp2k

• D.I.C Lover

Reputation: 2579
• Posts: 4,123
• 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.

### #5 Nallo

• D.I.C Regular

Reputation: 165
• Posts: 258
• 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:
```...
print repr(scores)
...

```

### #6 AulakhSam

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

## Re: Guess Number

Posted 16 December 2012 - 08:54 PM

```import random

smallestNum = 1
largestNum = 42
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:
else:

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:
line = line.replace ("\n", "")
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:

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:
else:

```

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

Question: Question

### #7 jon.kiparsky

• Beginner

Reputation: 11022
• Posts: 18,805
• 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?