I'm having a problem trying to create a game.
the point of the game is to guess a random number.
i'm learning python and i tought it would be a good exercise.
everything went fine (if you dont count syntax errors :))
until i tried to save the program.
i can't get it to create a list without putting another pair of [] around the scores.
and the part where i use c ==x doesn't work wel.
can somebody help me with this?
the program is in dutch

def readScore(lol):
  import os
  if os.path.exists(file):
    store = open(file,"r")
    for line in store:
      naam = line.rstrip()
      entry = store.next().rstrip()
      score = [entry]#after 2 times of opening the score is surrounded by a lot of []
      topscore[naam]=score
    store.close()


import os
import sys
topscore ={}
name = raw_input("wat is je naam?""\n")
score =[]

def addScore(lol):
  if topscore.has_key(name):
    score = topscore[name]
    score.append(n)
    topscore[name]=score
  else:
    score = []
    score.append(n)
    topscore[name]=score
    
    

file = "score.dat"

def saveScore(lol):
    store = open(file,"w")
    for naam,lijst in topscore.items():
        store.write(naam+"\n")
        store.write(str(lijst)+"\n")
    store.close()

 

c = 1
import random
menu = """
  1)nog eens spelen
  2) stoppen
  3) print scores
"""
a = random.randint(0,1000)
while a !=0 :
  print " nieuw spel begint"
  readScore(topscore)
  n = 0
  b=int(raw_input("kies een nummer tussen 0 en 1000"  '\n'   ))
  while b !=0 :
    n +=1
    if b>a :
      print " te veel"
    elif b<a :
      print " te weinig"
    elif b==a:
      addScore(topscore)
      saveScore(topscore)
      print " gelukt"
      print " je deed het in %d beeurten" %n
      print"-------------------------------"
      c = int(raw_input(menu))
      if c ==2 :
        exit()   
      else : 
        if c ==3 :
          print topscore
          c = int(raw_input(menu))
        else :
          if c == 1 :#if you print the scores before you use this you stil get the same number
            n=0
            print " nieuwe spel begint nu"
            a = random.randint(0,1000)
          else : 
            print " verkeerde input"
            c = int(raw_input(menu))
    else :
      print " verkeerd cijfer"
    b= int(raw_input("kies een nummer tussen 0 en 1000"   '\n'        ))

thanks

Look through the projects for beginner thread. This or something similiar is sure to be there.

It's funny to me that, armed with English and German, I can read printed Dutch pretty well...but spoken Dutch might as well be Arabic to me!

Several things strike me about the code.

(1) All import statements should occur at the top of the main code, before functions are defined (there are rare exceptions to this practice, but that's the rule). So: move lines 13, 14, and 43 to the top, and eliminate line 2.

(2) Generally, I try to get the skeleton framework for the code working before I get the whole thing working. In your case, you want to (a) have the user guess a number, (b) keep track of all of the user scores in a round, and (c) store the user scores in a file.

Create your program in that order. Get a basic guess-the-number program working. Then create a program that gets the user's name and keeps track of his scores within the round. Then finally, add the file functionality.

(3) Your topscore dictionary appears to be like this: {"name1": score1, "name2": score2, ...}. I would recommend reversing that: {score1: "name1", score2: "name2", score3: "name3", ...}.

By doing so, you can sort the keys and take, say, the top ten, eliminating the rest.

Hope it helps,
Jeff

import random

secret = random.randint(1,100)
guesses = 0

while True:
    guess = raw_input("I'm thinking of an integer between 1 and 100.  What is it? ")
    if guess == "quit":
        break
    try:
        guess = int(guess)
    except:
        print "Please enter an integer!"
        continue
    guesses += 1
    if guess > secret:
        print "Too high!"
    elif guess < secret:
        print "Too low!"
    else:
        break
if guess == secret:
    print "You got it!  It took you %d tries." % guesses
else:
    print "Sorry!  Better luck next time!"

>>> 
I'm thinking of an integer between 1 and 100.  What is it? two
Please enter an integer!
I'm thinking of an integer between 1 and 100.  What is it? 50
Too low!
I'm thinking of an integer between 1 and 100.  What is it? 75
Too high!
I'm thinking of an integer between 1 and 100.  What is it? 65
Too high!
I'm thinking of an integer between 1 and 100.  What is it? 60
Too low!
I'm thinking of an integer between 1 and 100.  What is it? 63
Too high!
I'm thinking of an integer between 1 and 100.  What is it? 62
Too high!
I'm thinking of an integer between 1 and 100.  What is it? 61
You got it!  It took you 7 tries.
>>>

thanks for the advice
it's very helpful
i think i should be able to finish it now

It works great when you use the score as the key in the dictionary thanks
now all i need to do is try to sort the results:)

Start here:

keys = mydict.keys()  # List of keys
keys.sort()  # Sorts keys[] in-place

for k in keys:
    print k, mydict[k]

found it myself!
and used it but the 10,11 appear before the 6,9
like this:
10 : mathijs
11 : mathijs
13 : mathijs
6 : mathijs
8 : mathijs
9 : mathijs
and i can't seem to get the c-loop working without errors
tought i did make some improvements

c = int(raw_input(menu))
      while c !="":
        if c ==2 :
          exit()   
        elif c ==3 :
          printScore()
          c = int(raw_input(menu))
        elif c == 1 :
          n=0
          print " nieuwe spel begint nu"
          a = random.randint(0,1000)
          break
        else : 
          print " verkeerde input"
        c = int(raw_input(menu))

and the sort+print code

def printScore():
  keylist = topscore.keys()
  keylist.sort()
  for key in keylist:
    print " %s : %s " %(key,topscore[key]

I want to thank everyone for the support and help!!

You will not exit the while() loop because c is never "", you want to use
while c > 2: as 1 is a break (exits the while loop), and 2 is what executes exit()-and do you want sys.exit(0) instead to exit the program?

c=3
      while c > 2:
         c = int(raw_input(menu))
         if c ==2 :
           exit()   
         elif c ==3 :
           printScore()
         elif c == 1 :
             n=0
             print " nieuwe spel begint nu"
             a = random.randint(0,1000)
             break
         else : 
            print " verkeerde input"

but the 10,11 appear before the 6,9
like this:
10 : mathijs
11 : mathijs
13 : mathijs
6 : mathijs
8 : mathijs
9 : mathijs
and the sort+print code

A string like you are using in key list sorts left to right so the "1" in "10" is less than the 9. Convert to an int. This would not be necessary if you can use an int for the dictionary key to begin with.

def printScore():
   keylist = [int(key) for key in topscore.keys()]
   keylist.sort()
   for key in keylist:
      print " %d : %s " %(key,topscore[str(key)]

Now it work's !!!!
thanks everyone!!
added the finished version translated to english
and marked the post as solved
many thanks

mathijs

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.