Reputation: 25
the problem I'm having is that I can't seem to get the coins to flip at all.
I can populate the list but when the program gets to the flip funtion it crashes. I have no idea how to get this working.
this is the error I get:
Traceback (most recent call last):
File "/home/unseensnick/VS Code Projects/python projects/java assignments in python/assignment_3/Main.py", line 46, in <module>
case 1: coinsThreeInARow()
File "/home/unseensnick/VS Code Projects/python projects/java assignments in python/assignment_3/Main.py", line 25, in coinsThreeInARow
flip = coins[i].flip()
File "/home/unseensnick/VS Code Projects/python projects/java assignments in python/assignment_3/Coins.py", line 11, in flip
while (headsCount < 3):
UnboundLocalError: local variable 'headsCount' referenced before assignment
here is the code
Main.py
from Coins import Coins
currentWinner = 9223372036854775807
winningCoin = ""
winnerCount = 0
num = 1
coins = []
answer = int(input("how many coins do you want to flip? "))
#populate list
for i in range(0, answer):
ele = num+1
coins.append(Coins(ele))
#flip coins in list
#doesn't work at the moment
for i in range(0, len(coins)):
flip = coins[i].flip()
if (flip < currentWinner):
currentWinner = flip
winningCoin = coins[i].getName()
winnerCount = i
print(winningCoin+" is the winner.");
Coin.py
import math
class Coins:
def __init__(self, num):
self.name = "c",num
self.count = 0
def flip(self):
self.count
while (headsCount < 3):
face = (int)(math.random() * 2); # range [0, 1]
self.count+=1
if (face == 0):
headsCount+=1
else:
headsCount = 0;
print("name: "+self.name+" count: "+self.count);
return self.count
def getName(self):
return self.name
def isHeads(self):
return (self.face == self.HEADS);
Upvotes: 0
Views: 64
Reputation: 25
got it working thanks to @TomMcLean
here is the working code:
Main.py
from Coins import Coins
currentWinner = 9223372036854775807
winningCoin = ""
winnerCount = 0
num = 0
coins = []
answer = int(input("how many coins do you want to flip? "))
#populate list
for i in range(0, answer):
num+=1
coins.append(Coins(num))
#flip coins in list
#doesn't work at the moment
for i in range(0, len(coins)):
flip = coins[i].flip()
if (flip < currentWinner):
currentWinner = flip
winningCoin = coins[i].getName()
winnerCount = i
print(winningCoin," is the winner.")
Coin.py
import random
class Coins:
def __init__(self, num):
self.name = "c",num
self.count = 0
self.face = 0
self.HEADS = 0
def flip(self):
self.count
headsCount = 0
while (headsCount < 3):
face = (int)(random.randint(0,1)); # range [0, 1]
self.count+=1
if (face == 0):
headsCount+=1
else:
headsCount = 0
print("name:",self.name,"count:",self.count)
return self.count
def getName(self):
return self.name
def isHeads(self):
return (self.face == self.HEADS)
Upvotes: 1