Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable Resetting Issue
#1
I ran into some issues here, when i typed 'back' to return to the main menu of my program it reset my credits. it does this every time and i can't seem to figure out why. would anyone be able to help me with this? thanks!

#Final Project
# 1/17/2018
#This program is an arcade, with a credit system and 3 different gamemodes
#---------------------------------------------------------------------
def ws(): 
  print(" ")
import random
import time
credits = 10000         #Currency in the game 
deposit = 0 
 

def coinflip(credits,deposit):
  print("Welcome to CoinFlip!")
  print("================================")
  print("Credits:", credits)
  print("================================")
  print("Winnings Info")
  print("================================")
  print("Picking the correct side will grant you double the credits")
  ws()
  ws()
  guess = input("heads or tails? or type 'back' to go to the main menu")  #user inputs heads or tails, if they type back they will return to main menu
  if guess == "back":
    start()
  deposit = float(input("How much would you like to bet?"))               #user picks his bet ammount, and that ammount is removed from his balance
  c = ["heads", "tails"]
  coin = random.choice(c)
  credits -= deposit
  def flip():
    print("Flipping....")
    time.sleep(1.5)
    print("The coin lands on", coin)
    ws()
  
  
  if coin == "heads" and guess == "heads":
    flip()
    credits += deposit*2
    print("You Guessed Right!")
    time.sleep(1.5)
    print("You Earned", deposit*2, "Credits")
    time.sleep(1)
    print("Your Balance is now", credits, "Credits")
    time.sleep(3)
    ws()
    ws()
    ws()    
    coinflip(credits, deposit)
  elif coin == "tails" and guess == "tails":
    flip()
    credits += deposit*2
    print("You Guessed Right!")
    time.sleep(1.5)
    print("You Earned", deposit*2, "Credits")
    time.sleep(1)
    print("Your Balance is now", credits, "Credits")
    ws()
    ws()
    ws()
    coinflip(credits, deposit)
    
  else:
    flip()
    print("Sadly, you lost!")
    print("You lost", deposit, "Credits")
    print("Your balance is now", credits, "credits")
    ws()
    ws()
    ws()
    coinflip(credits, deposit)
      
 
def RPS(credits, deposit):
 ws()
 ws()
 print("Welcome to Rock, Paper, Scissors")
 print("========================================")
 print("Credits:", credits)
 print("========================================")
 print("Winnings Info")
 print("========================================")
 print("You recieve double your money for winning RPS")
 print("========================================")
 ws()
 ws()
 
 o = ["rock", "paper", "scissors"]
 comppick = random.choice(o)
           
 player = input("rock, paper, scissors? Or Type 'back' to go to the main menu")
 if player == "back":
  start()
 deposit = float(input("How much would you like to bet?"))
 player = player.lower()
 credits -= deposit
 
 def throw():
   print("Rock")
   time.sleep(0.6)
   print("Paper")
   time.sleep(0.6)
   print("Scissors")
   time.sleep(0.6)
   print("Shoot!")
   ws()



 if player == comppick:
  throw()
  credits += deposit
  print("You Chose", player)
  print("The Computer Chose", comppick)
  print("Its a tie!")
  time.sleep(3)
  RPS(credits, deposit)
  
 elif player == "rock" and comppick == "paper":
  throw()
  print("You Chose", player)
  print("The Computer Chose", comppick)
  print("You Lost!")
  time.sleep(3)
  RPS(credits, deposit)
  
 elif player == "rock" and comppick == "scissors":
  throw()
  credits += deposit * 2
  print("You Chose", player)
  print("The Computer Chose", comppick)
  print("You Win!")
  RPS(credits, deposit)
 
 elif player == "paper" and comppick == "rock":
  throw()
  credits += deposit * 2
  print("You Chose", player)
  print("The Computer Chose", comppick)
  print("You Win!")
  RPS(credits, deposit)  
 
 elif player == "paper" and comppick == "scissors":
  throw()
  print("You Chose", player)
  print("The Computer Chose", comppick)
  print("You Lost!")
  time.sleep(3)
  RPS(credits, deposit)
 
 elif player == "scissors" and comppick == "rock":
  throw()
  print("You Chose", player)
  print("The Computer Chose", comppick)
  print("You Lost!")
  time.sleep(3)
  RPS(credits, deposit)  
 
 elif player == "scissors" and comppick == "paper":
  throw()
  credits += deposit * 2
  print("You Chose", player)
  print("The Computer Chose", comppick)
  print("You Win!")
  RPS(credits, deposit)
  
  
def roulette(credits,deposit):       
  print("Roulette")
  print("===============")
  print("Credits:", credits)
  print("===============")
  print("Winnings Info")
  print("===============")
  
  print("If you land on odd or even you get 2x your credits!")
  print("If you land on your specific number you get 28x your money")
  ws()
  ws()
  num = random.randint(0,36)
  def roll():
    ws()
    print("Spinning...")
    time.sleep(1.5)
    print("It has passed", random.randint(0, 36))                           #displays to the user what the correct number is
    time.sleep(1.5)
    print("Almost lands on", random.randint(0, 36))
    time.sleep(1.6)
    print("It landed on", num)
    ws()
    ws()
  bet = input("Type 'odd', 'even' or 'specific' to pick a certain number. Or type 'back' to return to the menu.")
  if bet == "back":
    start()
  deposit = float(input("Type in how much you want to bet: "))
  credits -= deposit
      
    
  if bet == "specific":
    bet = input("Choose a number between 0 and 36")
    ws()
    
  if bet == num:                       # if bet number is = to what is rolled you win 28x your money
    credits += deposit *28
    print("Wow! You won! The number was", num)
    print("You receive", int(deposit)*28, "credits!")
    print("Your balance is now", credits, "credits")
    time.sleep(2)
    ws()
    roulette(credits,deposit)
    
        
  if num % 2 == 0 and bet == "even":    #If the number is even and you pick even you win
    roll()
    credits += deposit * 2
    print("Wow! You won! It was an even number!")
    print("You receive", int(deposit)*2, "credits!")
    print("Your balance is now", credits, "credits")
    time.sleep(2)
    ws()
    roulette(credits,deposit)      
      
  elif num % 2 != 0 and bet == "odd":
    roll()
    credits += deposit * 2                          #If the number is odd and you pick odd you win
    print("Wow! You won! It was an odd number!")
    print("You receive", int(deposit)*2, "credits!")
    print("Your balance is now", credits, "credits")
    time.sleep(2)
    ws()
    roulette(credits,deposit)      
      
  else:                                               #if the if statements above were not correct then you lost
    roll()
    print("Sadly, you lost!")
    print("You lost", deposit, "Credits")
    print("Your balance is now", credits, "credits")
    time.sleep(2)
    ws()
    roulette(credits,deposit)
 
 
 
def start():
  print("THE ARCADE")
  print("==============================")
  print("Credits:", credits)
  print("==============================")
  print("Gamemodes")
  print("==============================")
  print("coinflip")
  ws()
  print("rps")
  ws()
  print("roulette")
  print("==============================")
  ws()
  gamemode = input("Enter Desired Gamemode: ")
  if gamemode == "coinflip":
    print("You Picked CoinFlip!")
    ws()
    ws()
    ws()
    coinflip(credits, deposit)
  
  if gamemode == "rps":
    print("You Picked RPS")
    ws()
    ws()
    ws()
    RPS(credits,deposit)
  
  if gamemode == "roulette":
    print("You Picked Roulette")
    ws()
    ws()
    ws()
    roulette(credits,deposit)
start()
Reply
#2
It is because of variable scope. When you enter one of the functions (games), credits variable defined on top of your file is used. If you modify credits, it only stays modified as long as you are inside the same function. Once a function (game) exits, whatever you were doing with credits locally is lost. And next time when you enter a new function/game, credits is 10000 again, because that is how it is defined globally.
Reply
#3
(Jan-20-2018, 07:15 PM)j.crater Wrote: It is because of variable scope. When you enter one of the functions (games), credits variable defined on top of your file is used. If you modify credits, it only stays modified as long as you are inside the same function. Once a function (game) exits, whatever you were doing with credits locally is lost. And next time when you enter a new function/game, credits is 10000 again, because that is how it is defined globally.

how can i fix this then?
Reply
#4
With using return statement. At the end of game, return the new credits value. And when you call a function (game) use credits = function(credits, deposit), to keep the updated value of credits after that particulare game is finished.
The program is not designed most elegantly, so implementing this solution may give a few headaches, but it is doable =)
In learning Python, you have probably not reached the topic of object oriented programming yet. Nonetheless, I think it's good to know that this program would be coded much easier and nicer using OOP.

Edit: I guess you want to return deposit value also, so return a tuple (both values)
Reply
#5
i just started learning python and am very new to it, i spent quite a few hours working on this for a project in school and i don't have a lot of time left before its due, so what your suggesting is a replace the credit variable at the top with a function? sorry i'm just not really understanding exactly what i have to do
Reply
#6
This is a very basic subject about functions, so you would be best off by reading some beginner tutorial's functions section. But here is some code, to give you a little hint of what I have in mind:

credits = 10000
deposit = 0
print("starting credits and deposit: ", credits, deposit)

def my_function(credits, deposit):
    credits = credits + 2000
    deposit = deposit + 100
    return credits, deposit

credits, deposit = my_function(credits, deposit)
print("final credits and deposit: ", credits, deposit)
Reply
#7
i tried implementing this but i don't really see how this works with my code, my deposit function takes the bet amount the person chooses and uses it to decide if the credits need to be added or subtracted from the overall balance, i'm not sure how i could implement that into every function so it affects it like a global variable
Reply
#8
I did not try to mimic exactly what you need to do with deposit. I just borrowed variable names "credits" and "deposit", since they appear in your code. That might've caused confusion, sorry in that case. The code example attempts to show how you can return a value from function back into program loop and keep it "updated" that way.

If you allow me to comment on program design, the way you nest calls to "start" functions is very impratctical, to put it mildly. User begins in "start" function. When user is finished with one game and enters "back", it just calls "start" again, and goes one level deeper into it. And then again, when exiting out of next game with "back", it goes one more level deeper in "start". I know you said you are tight on schedule. But if you try to reimplement your program using a loop instead of nesting calls to start, code will be easier to understand and debug. Beside earning you a higher grade ;) And it shouldn't take that long, much of the game logic you have written can be kept as it is.
Reply
#9
Here is an outline of how I would approach the task:

Output:
imports initial variable assignments define rps (input current credits) play a round return new credits define roulette (input current credits) play a round return new credits define coinflip (input current credits) play a round return new credits loop: choose game mode play a game play another round or go back to loop
It is very simplified, but I think you can get some good ideas from the example.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Commas issue in variable ddahlman 6 383 Apr-05-2024, 03:45 PM
Last Post: deanhystad
  resetting an iterator to full Skaperen 7 6,956 Feb-20-2022, 11:11 PM
Last Post: Skaperen
  Variable scope issue melvin13 2 1,529 Nov-29-2021, 08:26 PM
Last Post: melvin13
  variables vcnt, ocnt, and mcnt adding previous values and not resetting to 0 archanut 2 1,924 Feb-12-2021, 06:56 PM
Last Post: deanhystad
  Variable Issue slackerman73 2 1,919 Nov-09-2019, 04:34 PM
Last Post: slackerman73
  Issue with affecting numbers to a variable Adem 3 2,288 Sep-24-2019, 07:48 AM
Last Post: Adem
  Mixed string,Integer input variable issue maderdash 2 2,745 Nov-06-2018, 09:46 AM
Last Post: snippsat
  Resetting Global Variables? WuchaDoin 11 11,572 Sep-28-2018, 08:41 PM
Last Post: WuchaDoin
  netCDF issue with filling a variable HeavyLoads 1 11,426 Oct-03-2016, 08:34 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020