I've been coding a simple dice roll game to practice Python. I've got the basic mechanics worked out, but I want to have it so that the player receives 5 points every time the game is won. I've tried just simply adding 5 to the variable (PLAYER_TOTAL in the case), but when the code goes back to play another game it reverts back to 0.

Here's my code so far:

``````import random

def gameIntro():
print('''This is a dice roll game. Dice are rolled, and you recieve money
if you are equal to the total. Are you ready?''')
print('Yes or no?')
return input().lower().startswith('y')

def gamePlay():
PLAYER_TOTAL = 0
dieRoll = random.randint(1, 6)
dieRoll1 = random.randint(1, 6)
print()
print('Guess a number from 1 to 12')
playerGuess = int(input())
diceTotal = dieRoll + dieRoll1
if playerGuess == diceTotal:
print('Woo! You got it! Plus \$5 for you!')
PLAYER_TOTAL += 5
print()
print('You have ' + str(PLAYER_TOTAL))
else:
print('Sorry you didn\'t match the dice roll. Try again?')
input().lower().startswith('y')
while False:
print('Goodbye!')
break

gameIntro()
while True:
gamePlay()``````

I've been mainly using the pdf "Invent Your Own Computer Games With Python", which hasn't been much help on this topic. Any suggestions on how I can fix this?

6
Contributors
11
Replies
12
Views
8 Years
Discussion Span
Last Post by jcao219

The only way I can think of, is to save a file, perhaps named win.cfg. This file will contain how many points a person has. I'll explain the code using comments:

``````# First, check to see if the file exists
# If not, create the file, and open it again
while True:
try:
f = open("win.cfg", "r")
break
except:
f = open("win.cfg", "w")
f.write(0)
f.close

# Now, read the number inside the file
f.close()

# The game
import random

def gameIntro():
print('''This is a dice roll game. Dice are rolled, and you recieve money
if you are equal to the total. Are you ready?''')
print('Yes or no?')
return input().lower().startswith('y')

def gamePlay():
# Take this out
#PLAYER_TOTAL = 0
dieRoll = random.randint(1, 6)
dieRoll1 = random.randint(1, 6)
print()
print('Guess a number from 1 to 12')
playerGuess = int(input())
diceTotal = dieRoll + dieRoll1
if playerGuess == diceTotal:
print('Woo! You got it! Plus \$5 for you!')
PLAYER_TOTAL += 5
# This is where we write to the file
f = open("win.cfg", "w")
f.write(PLAYER_TOTAL)
f.close()
print()
print('You have ' + str(PLAYER_TOTAL))
else:
print('Sorry you didn\'t match the dice roll. Try again?')
input().lower().startswith('y')
while False:
print('Goodbye!')
break

gameIntro()
while True:
gamePlay()``````

Now, this is just a basic write to file, and load it. Very easy for someone to hack it, and make it seem like they got a higher score. That's where you can use pickle. Just `import pickle` , then `pickle.dump(PLAYER_TOTAL, f)` I think that's how the variables go, could be wrong. Anyways, still nto secure, because if you open the file, any programmer can still unpickle it. So, you could try this:

``````PTcode = ""
# Convert the number into ascii code
# In case it is larger than 9
# Also, we add 5 to make it harder to break
# Also, we add 0's to ensure they stay in the 10's place
for x in range(0, len(PLAYER_TOTAL)):
y = str(ord(PLAYER_TOTAL[x])+5)
if len(y) == 1:
y = "0" + y
PTcode += y``````

Then, just pickle.dump this file. To load the number, just do the operation in reverse, oppopsite of ord is chr.
I bet this has gone all over your head, I'm sorry :/ If you need me to explain more, I will
Also, I'm half asleep xD Don't try out my code, make your own, mine might not work, so no guarentees

Edited by hondros: n/a

To give you a more simple answer, your problem with the player's score is that you keep resetting it. Why not just pass it in as a function argument.

Your coding is a little strange...did you work with C before? I have just cleaned up what you have done a little.

``````#! /usr/bin/python
# dice.py

import random

def gameIntro():
print('''This is a dice roll game. Dice are rolled, and you recieve money
if you are equal to the total. Are you ready?''')

if raw_input("Yes or no?")[0].lower() == "y":
gamePlay(PLAYER_TOTAL=0)
else:
print "\nCheers\n"
exit()

def gamePlay(PLAYER_TOTAL=0):

dieRoll = random.randint(1, 6)
dieRoll1 = random.randint(1, 6)
print
print 'Guess a number from 1 to 12'
playerGuess = input()
diceTotal = dieRoll + dieRoll1
if playerGuess == diceTotal:
print 'Woo! You got it! Plus \$5 for you!'
PLAYER_TOTAL += 5
print
print 'You have ' + str(PLAYER_TOTAL)
else:
if raw_input('Sorry you didn\'t match the dice roll. Try again?')[0].lower() == "y":
return True
else:
print "Goodbey!"
exit()

gameIntro()
while True:
gamePlay()``````

It's still a little messy. You could make it a bit more simple, I think.

A rewrite with a class. I used the 'raw_input' function instead of the 'input' function.

``````import random

class Game():
def __init__(self):
self.player_total = 0

def gameIntro(self):
print('''This is a dice roll game. Dice are rolled, and you recieve money if you are equal to the total. Are you ready?''')
print('Yes or no?')
return raw_input().lower().startswith('y')

def gamePlay(self):
dieRoll = random.randint(1, 6)
dieRoll1 = random.randint(1, 6)
print()
print('Guess a number from 1 to 12')
playerGuess = int(input())
diceTotal = dieRoll + dieRoll1
if playerGuess == diceTotal:
print('Woo! You got it! Plus \$5 for you!')
self.player_total += 5
print()
print('You have ' + str(self.player_total))
else:
print('Sorry you didn\'t match the dice roll. Try again?')
if (raw_input().lower()[0] == 'y'):
return True
else:
print('Goodbye!')
exit(0)

if __name__ == '__main__':
game = Game()
game.gameIntro()
while True:
game.gamePlay()``````

When the code is that simple, you can get away with a global variable ...

``````import random

# this will be a global variable
PLAYER_TOTAL = 0

def gameIntro():
print('''This is a dice roll game. Dice are rolled, and you recieve money
if you are equal to the total. Are you ready?''')
print('Yes or no?')
# returns True if yes else False
return input().lower().startswith('y')

def gamePlay():
global PLAYER_TOTAL
dieRoll = random.randint(1, 6)
dieRoll1 = random.randint(1, 6)
print()
print('Guess a number from 1 to 12')
playerGuess = int(input())
diceTotal = dieRoll + dieRoll1
#diceTotal = 12  # for testing only
if playerGuess == diceTotal:
print('Woo! You got it! Plus \$5 for you!')
PLAYER_TOTAL += 5
print()
print('You have ' + str(PLAYER_TOTAL))
else:
print('Sorry you didn\'t match the dice roll. Try again?')
stop = input().lower().startswith('n')
if stop:
print('Goodbye!')
raise SystemExit

# act on result
if gameIntro():
while True:
gamePlay()``````

Normally globals are okay for constants and should be avoided for variables. So yes, it's best to use all capital letters.

If you want to avoid global variables, you can use a static variable in your function (created with a mutable object like a list) ...

``````import random

def gameIntro():
print('''This is a dice roll game. Dice are rolled, and you recieve money
if you are equal to the total. Are you ready?''')
print('Yes or no?')
# returns True if yes else False
return input().lower().startswith('y')

def gamePlay(total=[0]):
"""uses total[0] as a static variable"""
dieRoll = random.randint(1, 6)
dieRoll1 = random.randint(1, 6)
print()
print('Guess a number from 1 to 12')
playerGuess = int(input())
diceTotal = dieRoll + dieRoll1
#diceTotal = 12  # for testing only
if playerGuess == diceTotal:
print('Woo! You got it! Plus \$5 for you!')
total[0] += 5
print()
print('You have ' + str(total[0]))
else:
print('Sorry you didn\'t match the dice roll. Try again?')
stop = input().lower().startswith('n')
if stop:
print('Goodbye!')
raise SystemExit

# act on result
if gameIntro():
while True:
gamePlay()``````

Note: The e-book used by the OP is written in Python3 and you can look at it at:
http://inventwithpython.com/chapters/

Edited by vegaseat: ebook, static var

@hondros Since I don't really plan to do more with this except practice, this seems a little complicated. However, it does seem like a good way to accomplish this if I were to release a similar concept game!

@Namibnat It might have looked weird since I wrote it in Python 3, and it seems like you rewrote it for Python 2. But I should learn how to write it in both languages.

@Firewolf I need to look into classes, because I don't understand your code very well ;), but thanks for the input!

@vegaseat I tried to avoid to use a global variable so I don't get into the habit, but it looks like it would work. As for the static variable...*duh*.

Thanks everyone for the help!

Hey, someone thought my idea would come in handy later! *hi fives* But yeah, that'll come in handy for saving, say game saves, records, etc. And if you want to get really fancy, you can just append it to the end of your file. And make sure you specify it's a .exe if you compile it. Then people won't know how to get it xD. I''m sure they'd figure out, but oh well

Haha, I'm sure. The main reason I'm learning Python is because a friend and I are making an RPG in Blender and we're going to need Python scripts to do complex things. And the worst problem is for every 1 person who could figure it out there are 100 who will be all "OMG THIS IS TOO COMPLICATED THIS DOESN'T WORK."

xD Nice. I am in the middle of creating a text-based RPG all by myself. I'm thinking it'll take at least a month. Right now I have all the equipment done, and the character's format. Then that's how I save the character. I was taking a look at it, and it'd be somewhat easy to hack it, so I'm thinking about implementing my encryption program into my RPG, so if you change a number, it screws it up. Oh, it's matrix encoding, btw. I can send you the script if you want to see it

An RPG in Blender... nice... I also play a lot with Blender (and its game engine)... a very nice tool... and the interface of the 2.5 version is also a big improvement... looking forward to the release in 2010...

The classes thing... once you are familiar with oop, you will see the advantages.. but that's for later... ;)