Poker Hand Win Logic doesn't work correctly - python

Something's wrong with how the winner is determined in my poker game.
I've tried checking that the player score value is reset from the loop
and that all other logic related variables are too
TableCards = []
for Card in Flop:
TableCards.append(Card)
TableCards.append(Turn)
TableCards.append(River)
for Card in Player.Hand:
TableCards.append(Card)
TableCardValues = []
TableCardSuits = []
for Card in TableCards:
TableCardValues.append(Card.Value)
TableCardSuits.append(Card.Suit)
TableCardValues.sort()
TableCardSuits.sort()
ArrayLengthI = len(TableCardValues)
Straight = False
Flush = False
Pairs = []
ThreeOfAKinds = []
FourOfAKinds = []
StraightCount = 0
PlayerHandValues = []
DealerHandValues = []
for Card in Player.Hand:
PlayerHandValues.append(Card.Value)
for Card in Dealer.Hand:
DealerHandValues.append(Card.Value)
for X in range(ArrayLengthI - 1):
if TableCardValues[X + 1] == TableCardValues[X] + 1:
StraightCount += 1
if StraightCount >= 5:
Straight == True
for Suit in TableCardSuits:
if TableCardSuits.count(Suit) >= 5:
Flush = True
for Value in set(TableCardValues):
if TableCardValues.count(Value) == 2:
Pairs.append(Value)
elif TableCardValues.count(Value) == 3:
ThreeOfAKinds.append(Value)
elif TableCardValues.count(Value) == 4:
FourOfAKinds.append(Value)
if Straight == True or Flush == True:
if Straight == True and Flush == True:
Player.HandScore = PokerHands.StraightFlush * max(PlayerHandValues)
elif Straight == True:
Player.HandScore = PokerHands.Straight * max(PlayerHandValues)
elif Flush == True:
Player.HandScore = PokerHands.Flush * max(PlayerHandValues)
elif FourOfAKinds != []:
Player.HandScore = PokerHands.FourOfAKind * max(PlayerHandValues)
elif ThreeOfAKinds != []:
if len(Pairs) >= 1:
Player.HandScore = PokerHands.FullHouse * max(PlayerHandValues)
else:
Player.HandScore = PokerHands.ThreeOfAKind * max(PlayerHandValues)
elif len(Pairs) == 2:
Player.HandScore = PokerHands.TwoPair * max(PlayerHandValues)
elif len(Pairs) == 1:
Player.HandScore = PokerHands.OnePair * max(PlayerHandValues)
else:
Player.HandScore = PokerHands.HighCard * max(PlayerHandValues)
TableCardsDealer = []
TableCardValuesDealer = []
TableCardSuitsDealer = []
for Card in Flop:
TableCardsDealer.append(Card)
TableCardsDealer.append(Turn)
TableCardsDealer.append(River)
DealerStraight = False
DealerFlush = False
DealerStraightCount = 0
DealerPairs = []
DealerThreeOfAKinds = []
DealerFourOfAKinds = []
for Card in Dealer.Hand:
TableCardsDealer.append(Card)
for Card in TableCards:
TableCardValuesDealer.append(Card.Value)
TableCardSuitsDealer.append(Card.Suit)
TableCardSuitsDealer.sort()
TableCardValuesDealer.sort()
TableCardsDealerLength = len(TableCardSuitsDealer)
for X in range(TableCardsDealerLength - 1):
if TableCardValuesDealer[X + 1] == TableCardValuesDealer[X] + 1:
DealerStraightCount += 1
if DealerStraightCount >= 5:
DealerStraight == True
for Suit in TableCardSuitsDealer:
if TableCardSuitsDealer.count(Suit) >= 5:
DealerFlush == True
for Value in set(TableCardValuesDealer):
if TableCardValuesDealer.count(Value) == 2:
DealerPairs.append(Value)
elif TableCardValuesDealer.count(Value) == 3:
DealerThreeOfAKinds.append(Value)
elif TableCardValuesDealer.count(Value) == 4:
DealerFourOfAKinds.append(Value)
if DealerStraight == True or DealerFlush == True:
if DealerStraight == True and DealerFlush == True:
Dealer.HandScore = PokerHands.StraightFlush * max(DealerHandValues)
elif DealerStraight == True:
Dealer.HandScore = PokerHands.Straight * max(DealerHandValues)
elif DealerFlush == True:
Dealer.HandScore = PokerHands.Flush * max(DealerHandValues)
elif DealerFourOfAKinds != []:
Dealer.HandScore = PokerHands.FourOfAKind * max(DealerHandValues)
elif DealerThreeOfAKinds != []:
if len(DealerPairs) >= 1:
Dealer.HandScore = PokerHands.FullHouse * max(DealerHandValues)
else:
Dealer.HandScore = PokerHands.ThreeOfAKind * max(DealerHandValues)
elif len(DealerPairs) == 2:
Dealer.HandScore = PokerHands.TwoPair * max(DealerHandValues)
elif len(DealerPairs) == 1:
Dealer.HandScore = PokerHands.OnePair * max(DealerHandValues)
else:
Dealer.HandScore = PokerHands.HighCard * max(DealerHandValues)
if Player.HandScore > Dealer.HandScore:
print("Well Done, sir. You've won.")
Player.Money += Pot
Pot = 0
elif Player.HandScore < Dealer.HandScore:
print("I Apologise, but you've lost.")
Dealer.Money += Pot
Pot = 0
elif Player.HandScore == Dealer.HandScore:
print("You've tied")
Pot = 0
Junk = input()
Player.HandScore = 0
Dealer.HandScore = 0
system("cls")
There are no error messages, but it seems to determine the winner wrong, and I can't exactly pinpoint the reason why.

Related

python IndexError that I cannot resolve with dictionaries

I have a simple problem, and I need a pari of fresh eyes for this. I have a dictionary for my world:
world = {}
and a function that fills rooms in that dictionary based on a 2d array:
def makeRoomsForLevel():
counter = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[c][r] == 1:
world[f"room{counter}"] = Room(
f"room{counter}",
"",
{},
False,
None,
False,
None,
False,
None,
True,
(r, c)
)
counter += 1
And yet another function that I am working on to find the exits for the room:
def findExits():
counter = 1;
for x in range(len(world)):
if rooms[world[f"room{counter}"]].coords[0] + 1 == 1:
pass
I tried running this before I filled in the if statement, and it gave me this error:
IndexError: only integers, slices (':'), ellipsis ('...'), numpy.newaxis ('None') and integer or boolean arrays are valid indicies
I kinda know what it means, but it hasn't given me any problems with this before hand.
Here is the room class:
class Room():
def __init__(self, name, description, exits, hasWeapon, weapon, hasItem, item, hasEnemy, enemy, isFirstVisit, coords):
self.name = name
self.description = description
self.exits = exits
self.hasWeapon = hasWeapon
self.weapon = weapon
self.hasItem = hasItem
self.item = item
self.hasEnemy = hasEnemy
self.enemy = enemy
self.isFirstVisit = isFirstVisit
self.coords = coords
And here is what "rooms" is:
rooms = np.zeros((11, 11))
Here is the full generation code:
rooms = np.zeros((11, 11))
maxRooms = 7
possibleNextRoom = []
world = {}
def startLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
halfHeight = int(len(rooms[1]) / 2)
halfWidth = int(len(rooms[0]) / 2)
rooms[halfWidth][halfHeight] = 1
def resetLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
def countRooms():
roomCount = 0
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[r][c] == 1:
roomCount += 1
return roomCount
def findPossibleRooms():
for r in range(len(rooms) - 1):
for c in range(len(rooms) - 1):
if rooms[r][c] == 1:
if rooms[r][c+1] != 1:
possibleNextRoom.append((r, c+1))
if rooms[r][c-1] != 1:
possibleNextRoom.append((r, c-1))
if rooms[r-1][c] != 1:
possibleNextRoom.append((r-1, c))
if rooms[r+1][c] != 1:
possibleNextRoom.append((r+1, c))
def addRoom():
x = random.randrange(0, len(possibleNextRoom))
rooms[possibleNextRoom[x][0]][possibleNextRoom[x][1]] = 1
possibleNextRoom.pop(x)
def generateLevel():
global x, possibleNextRoom
startLevel()
while countRooms() < maxRooms:
countRooms()
findPossibleRooms()
addRoom()
def makeRoomsForLevel():
counter = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[c][r] == 1:
world[f"room{counter}"] = Room(
f"room{counter}",
"",
{},
False,
None,
False,
None,
False,
None,
True,
(r, c)
)
counter += 1
def findExits():
counter = 1;
for x in range(len(world)):
if rooms[world[f"room{counter}"].coords[0]] + 1 == 1:
pass
def fillRooms():
counter = 1
for x in range(len(world)):
x = random.randrange(1, 2)
if x == 1:
world[f"room{counter}"].hasItem = True
x = random.randrange(1, 10)
if x == 1:
world[f"room{counter}"].hasWeapon = True
x = random.randrange(1, 4)
if x == 1:
world[f"room{counter}"].hasEnemy = True
counter += 1
And here is the entire code:
import random
import numpy as np
world = {}
class Player():
def __init__(self, health, maxHealth, baseDmg, dmg, name, weapons, items, isAlive, previousRoom, roomName):
self.health = health
self.maxHealth = maxHealth
self.baseDmg = baseDmg
self.dmg = dmg
self.name = name
self.weapons = weapons
self.items = items
self.isAlive = isAlive
self.previousRoom = previousRoom
self.room = world[roomName]
def Move(self, direction):
if direction not in self.room.exits:
print("Cannot Move In That Direction!")
return
newRoomName = self.room.exits[direction]
self.previousRoom = world[self.room.name]
print("Moving to", newRoomName)
self.room = world[newRoomName]
def MoveBack(self):
self.room = world[self.previousRoom.name]
print("Moving to", self.room.name)
class Enemy():
def __init__(self, health, dmg, hasLoot, lootItem, isAlive):
self.health = health
self.dmg = dmg
self.hasLoot = hasLoot
self.lootItem = lootItem
self.isAlive = isAlive
class Weapon():
def __init__(self, name, dmg, description):
self.name = name
self.dmg = dmg
self.description = description
class Item():
def __init__(self, name, amt, description):
self.name = name
self.amt = amt
self.description = description
class Room():
def __init__(self, name, description, exits, hasWeapon, weapon, hasItem, item, hasEnemy, enemy, isFirstVisit, coords):
self.name = name
self.description = description
self.exits = exits
self.hasWeapon = hasWeapon
self.weapon = weapon
self.hasItem = hasItem
self.item = item
self.hasEnemy = hasEnemy
self.enemy = enemy
self.isFirstVisit = isFirstVisit
self.coords = coords
#######################Dungeon Generation###################
rooms = np.zeros((11, 11))
maxRooms = 7
possibleNextRoom = []
def startLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
halfHeight = int(len(rooms[1]) / 2)
halfWidth = int(len(rooms[0]) / 2)
rooms[halfWidth][halfHeight] = 1
def resetLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
def countRooms():
roomCount = 0
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[r][c] == 1:
roomCount += 1
return roomCount
def findPossibleRooms():
for r in range(len(rooms) - 1):
for c in range(len(rooms) - 1):
if rooms[r][c] == 1:
if rooms[r][c+1] != 1:
possibleNextRoom.append((r, c+1))
if rooms[r][c-1] != 1:
possibleNextRoom.append((r, c-1))
if rooms[r-1][c] != 1:
possibleNextRoom.append((r-1, c))
if rooms[r+1][c] != 1:
possibleNextRoom.append((r+1, c))
def addRoom():
x = random.randrange(0, len(possibleNextRoom))
rooms[possibleNextRoom[x][0]][possibleNextRoom[x][1]] = 1
possibleNextRoom.pop(x)
def generateLevel():
global x, possibleNextRoom
startLevel()
while countRooms() < maxRooms:
countRooms()
findPossibleRooms()
addRoom()
def makeRoomsForLevel():
counter = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[c][r] == 1:
world[f"room{counter}"] = Room(
f"room{counter}",
"",
{},
False,
None,
False,
None,
False,
None,
True,
(r, c)
)
counter += 1
def findExits():
counter = 1;
for x in range(len(world)):
if rooms[world[f"room{counter}"].coords[0]] + 1 == 1:
pass
def fillRooms():
counter = 1
for x in range(len(world)):
x = random.randrange(1, 2)
if x == 1:
world[f"room{counter}"].hasItem = True
x = random.randrange(1, 10)
if x == 1:
world[f"room{counter}"].hasWeapon = True
x = random.randrange(1, 4)
if x == 1:
world[f"room{counter}"].hasEnemy = True
counter += 1
############################################################
generateLevel()
makeRoomsForLevel()
findExits()
WoodenSword = Weapon("Wooden Sword", 5, "A wooden sword. Looks like a kid's toy.")
IronDagger = Weapon("Iron Dagger", 8, "Small, sharp, and pointy. Good for fighting monsters!")
HealthPot = Item("Health Potion", 1, "A Potion of Instant Health. Restores 10 Health.")
goblin1 = Enemy(25, 2, True, [HealthPot, IronDagger], True)
player = Player(10, 10, 5, 5, "", [], [], True, "room1", "room1")
def ShowInv():
print("*******************************")
print("Name:", player.name)
print("Health:", player.health)
print("Weapons:")
for i in player.weapons:
print(" ===============================")
print(" Weapon:", i.name)
print(" Description:", i.description)
print(" Damage:", i.dmg)
print(" ===============================")
print("Items:")
for i in player.items:
print(" ===============================")
print(" Item:", i.name)
print(" Amount:", i.amt)
print(" Description:", i.description)
print(" ===============================")
print("*******************************")
def testItems(item):
exists = item in player.items
return exists
def fight(enemy):
print("Your Health:", player.health)
print("Enemy Health:", enemy.health)
ans = input("What would you like to do?\n>>")
if ans == "attack":
chance = random.randrange(1, 20)
if chance >= 10:
enemy.health -= player.dmg
else:
print("You did not roll high enough...\nYour turn has been passed...")
if ans == "heal":
chance = random.randrange(1, 20)
if testItems(HealthPot):
if chance >= 10:
x = 0
for item in player.items:
if item == HealthPot:
player.health += 10
if player.health > player.maxHealth:
player.health = player.maxHealth
item.amt -= 1
if item.amt <= 0:
player.items.pop(x)
break
x += 1
else:
print("You did not roll high enough...\nYour turn has been passed...")
if ans == "run":
chance = random.randrange(1, 20)
if chance >= 10:
player.MoveBack()
else:
print("You did not roll high enough...\nYour turn has been passed...")
if enemy.health > 0 and player.health > 0:
chance = random.randrange(1, 20)
if chance >= 10:
player.health -= enemy.dmg
else:
if enemy.health <= 0:
enemy.isAvile = False;
def testRoom():
if player.room.hasWeapon:
if player.room.isFirstVisit:
player.weapons.append(player.room.weapon)
if player.room.hasItem:
if player.room.isFirstVisit:
player.items.append(player.room.item)
if player.room.hasEnemy:
if player.room.isFirstVisit:
while player.room.enemy.health > 0:
fight(player.room.enemy)
player.room.isFirstVisit = False
while True:
command = input(">>")
if command in {"N", "S", "E", "W"}:
player.Move(command)
testRoom()
elif command == "look":
print(player.room.description)
print("Exits:", *','.join(list(player.room.exits.keys())))
elif command == "inv":
ShowInv()
elif command == "heal":
if testItems(HealthPot):
player.health += 10
if player.health > player.maxHealth:
player.health = player.maxHealth
else:
print("You don't have any", HealthPot.name, "\bs")
else:
print("Invalid Command")
IIUC, you need something like:
#find the name of the room given the coordinates
def findRoom(x, y):
for i in range(len(world)):
if world[f"room{i+1}"].coords == (x, y):
return f"room{i+1}"
return None
def findExits():
for i in range(len(world)):
x, y = world[f"room{i+1}"].coords
exits = dict()
#east
if rooms[x, y+1] == 1:
exits["E"] = findRoom(x, y+1)
#south
if rooms[x+1, y] == 1:
exits["S"] = findRoom(x+1, y)
#west
if rooms[x, y-1] == 1:
exits["W"] = findRoom(x, y-1)
#north
if rooms[x-1, y] == 1:
exits["N"] = findRoom(x-1, y)
world[f"room{i+1}"].exits = exits
After running the above, the exits for room1 look like:
>>> world["room1"].exits
{'E': 'room2', 'S': 'room4'}
You can work with the above structure, changing the keys and values as needed.

Monte Carlo tree search keeps giving the same result

I wrote a Monte Carlo tree search algorithm (based on https://en.wikipedia.org/wiki/Monte_Carlo_tree_search), and connected it with the "python-chess" library.
Basically, the algorithm gets stuck somewhere, because it keeps printing as output "1/2-1/2" (draw).
There's probably an issue with the expansion function, but I don't really know where.
Here's the code:
class MonteCarloTreeSearch():
def __init__(self):
self.board = chess.Board()
self.results = []
self.total_matches = 0
def expansion(self, leaf):
done = False
if not (self.board.is_game_over()):
if len(leaf.children != 0):
possible = np.array([i for i in self.board.legal_moves])
actual = []
for i in range(len(possible)):
test = possible[i]
cnt = 0
for j in range(len(leaf.children)):
if (not test == leaf.children[j].value) and cnt == 0:
actual.append(test)
cnt += 1
move = random.choice(actual)
else:
move = random.choice([i for i in self.board.legal_moves])
self.board.push(move)
if self.board.is_game_over():
done = True
child = Node(move, player="white" if leaf.player=="black" else "black", parent=[leaf], score=0)
leaf.children = np.append(leaf.children, child)
if not done:
return self.expansion(child)
return leaf
def playout(self, starting_node):
childr = self.expansion(starting_node)
result = self.board.result()
if result == "1-0":
result = 1
elif result == "0-1":
result = -1
elif result == "1/2-1/2":
result = .5
elif result == "*":
raise Exception("ERROR: Game was not over, but playout stopped.")
else:
raise Exception("ERROR: Playout process error.")
return childr, result, starting_node
def expansion_playout_backpropagation(self, start):
node, result, starting_node = self.playout(start)
i = 0
while i == 0:
node.matches += 1
if node.player == "white":
if result == 1:
node.score += 1
if node.matches > 0:
node.winp = node.score / node.matches
else:
node.winp = 0
elif node.player == "black":
if result == -1:
node.score += 1
if node.matches > 0:
node.winp = node.score / node.matches
else:
node.winp = 0
else:
raise Exception("ERROR: Invalid player selection.")
if node.is_equal(starting_node):
i += 1
else:
node = node.parent[0]
self.results.append(self.board.result())
print(self.board.result())
self.board.reset_board()
self.total_matches += 1
def backpropagation(self, node, result, starting_node):
i = 0
while i == 0:
node.matches += 1
if node.player == "white":
if result == 1:
node.score += 1
if node.matches > 0:
node.winp = node.score / node.matches
else:
node.winp = 0
elif node.player == "black":
if result == -1:
node.score += 1
if node.matches > 0:
node.winp = node.score / node.matches
else:
node.winp = 0
else:
raise Exception("ERROR: Invalid player selection.")
if node.is_equal(starting_node):
i += 1
else:
node = node.parent[0]
self.results.append(self.board.result())
print(self.board.result())
self.board.reset_board()
self.total_matches += 1
def fitness(self, node):
p = node.winp
simulations = node.matches
parent_simulations = node.parent[0].matches if node.parent[0] != None else self.matches
c = math.sqrt(2)
if simulations > 0 and parent_simulations > 0:
formula = p + c * math.sqrt((np.log(parent_simulations)) / simulations)
else:
formula = p
return formula

Display problems with end= '' and while loops. Want it to go to a new line when finished

With the display I want the Banking command: input to start on a new string but when it gets to the display elif it does not. I know why, its because of the end= '' but I need to have the display be in one line for the assignment and I cant figure out a solution. Thanks for the help.
def main():
number_of_accounts = int(input("Number of accounts:\n"))
accounts = [0.0] * number_of_accounts
banking_command(accounts)
def banking_command(accounts):
from os import _exit as exit
active = True
while active:
banking_command = input('Banking command:\n')
banking_command = banking_command.split(' ')
if banking_command[0] == 'add':
monetary_amount = float(banking_command[2])
account_being_changed = int(banking_command[1])
accounts[account_being_changed - 1] += monetary_amount
elif banking_command[0] == 'subtract':
monetary_amount = float(banking_command[2])
account_being_changed = int(banking_command[1])
accounts[account_being_changed - 1] -= monetary_amount
elif banking_command[0] == 'move':
monetary_amount = float(banking_command[3])
transfer_money_out = int(banking_command[1])
transfer_money_in = int(banking_command[2])
accounts[transfer_money_out - 1] -= monetary_amount
accounts[transfer_money_in - 1] += monetary_amount
elif banking_command[0] == 'display':
i = 0
while i < len(accounts):
account_number = i + 1
print(str(account_number) + ":$" + str(accounts[i]) + " ", end= '')
i += 1
elif banking_command[0] == 'exit':
exit(0)
main()
Add a print() after the while loop.
elif banking_command[0] == 'display':
i = 0
while i < len(accounts):
account_number = i + 1
print(str(account_number) + ":$" + str(accounts[i]) + " ", end= '')
i += 1
print() # <-- end the line with the account display

Creating nested loops or functions

Is it possible to create a chain of loops or functions that are all nested within another. Using an if statement as an example, I want to chain...
if x == 0:
print(x)
while nesting them like this...
if x == 0:
print(x)
if x == 0:
print(x)
if x == 0:
print(x)
How can I do this using an automatic process?
The code I want to do this to is:
oglist = ["a","b","c"]
combolist = ["lol"]
comboloop = True
combocounter = 3
recursions = {}
for counterx in range(1, combocounter):
recursions["recursion" + str(counterx)] = False
def loopgen(counter2):
if counter2 == 0:
def loop():
global comboloop
global recursions
if len(lists["list0"]) == 0:
comboloop = False
recursions["recursion1"] = True
else:
lists["list1"] = lists["list0"][1:]
recursions["recursion1"] = False
return
elif counter2 != combocounter - 1:
def loop():
global recursions
if len(lists["list" + str(counter2)]) == 0:
lists["list" + str(counter2 - 1)] = lists["list" + str(counter2 - 1)][1:]
recursions["recursion" + str(counter2)] = True
recursions["recursion" + str(counter2 + 1)] = True
else:
lists["list" + str(counter2 + 1)] = lists["list" + str(counter2)][1:]
recursions["recursion" + str(counter2 + 1)] = False
return
else:
def loop():
global counter3
global recursions
if len(lists["list" + str(counter2)]) == 0:
lists["list" + str(counter2 - 1)] = lists["list" + str(counter2 - 1)][1:]
recursions["recursion" + str(counter2)] = True
else:
combolist[counter3] = lists["list0"][0]
for x in range(1, combocounter):
combolist[counter3] = combolist[counter3] + lists["list" + str(x)][0]
combolist.append("lol")
lists["list" + str(counter2)] = lists["list" + str(counter2)][1:]
counter3 += 1
recursions["recursion" + str(counter2)] = False
return
return loop
lists = {}
for x in range(0, combocounter):
lists["list" + str(x)] = ["lol"]
loops = {}
for counter1 in range(0, combocounter):
loops["loop" + str(counter1)] = loopgen(counter1)
lists["list0"] = oglist
counter3 = 0
while comboloop == True:
loops["loop0"]()
while recursions["recursion1"] == False:
loops["loop1"]()
while recursions["recursion2"] == False:
loops["loop2"]()
combolist.remove("lol")
print(combolist)
There are only 3 while loops on the bottom, because combocounter = 3
In future versions of this, combocounter will not be a static number.
While loop :
while x == 0:
print(x)
Recursion :
def f(x):
if x == 0:
print(x)
f(x)
I defined another function which would replicate the creation of a while loop inside another while loop with...
def otherloop(counter4):
while recursions["recursion" + str(counter4)] == False:
loops["loop" + str(counter4)]()
if counter4 != combocounter - 1:
return otherloop(counter4 + 1)
if counter4 != 1:
return otherloop(counter4 - 1)
return
Then of course I replaced
while recursions["recursion1"] == False:
loops["loop1"]()
while recursions["recursion2"] == False:
loops["loop2"]()
with
otherloop(1)

Python Class Setters Not Changing Variables

The closest thread I could find to my problem was this: Python setter does not change variable
It didn't really help, the volume and the channels are not changing at all. The first fucntion which is to "watch TV" works perfectly fine.
class TV(object):
def __init__(self, channel, volume):
self.__channel = channel
self.__volume = volume
def __str__(self):
out = ""
out += "You're on channel #" + str(self.__channel) + ", " + self.channelNetwork()
out += "\nVolume is currently at: " + str(self.__volume) + "/20"
return out
# a method that determines the name for each channel from 1-10
def channelNetwork(self):
c = self.__channel
if c == 1:
return "CBS"
elif c==2:
return "NBC"
elif c==3:
return "ABC"
elif c==4:
return "Fox"
elif c==5:
return "ESPN"
elif c==6:
return "PBS"
elif c==7:
return "CNN"
elif c==8:
return "Comedy Central"
elif c==9:
return "Cartoon Network"
elif c==10:
return "Nicklodeon"
# a volume slider that has a range from 0-20
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
def channelChanger(self, newChannel):
c = self.__channel
if newChannel == "+":
c += 1
else:
c -= 1
if c < 0:
c = 0
if c > 10:
c = 10
def main():
import random
randomChannel = random.randint(1,10)
randomVolume = random.randrange(21)
televsion = TV(randomChannel, randomVolume)
choice = None
while choice != "0":
print \
("""
TV Simulator
0 - Turn off TV
1 - Watch TV
2 - Change channel
3 - Change volume
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Have a good day! :)")
elif choice == "1":
print("You relax on your couch and watch some TV")
print(televsion)
elif choice == "2":
newChannel = None
while newChannel not in ('+', '-'):
newChannel = input("\nPress '+' to go up a channel and press '-' to go down a channel: ")
televsion.channelChanger(newChannel)
elif choice == "3":
newVolume = None
while newVolume not in ('+', '-'):
newVolume = input("\nPress '+' to increase volume and press '-' to decrease volume: ")
televsion.volumeSlider(newVolume)
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
input("\n\nPress enter to exit.")
The problem is, that when you do:
v = self.__volume
In:
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
Assigning to v won't affect self.__volume. You need to use self.__volume = 20 or whatever.
As an aside, don't use double-underscore name-mangling unless you actually need it. E.g. self.volume is fine.

Categories