I am trying to make a function where user can autosolve the game at the current state. I got this error. Anyone who helps me is gladly appreciated.
#main method
def main(self):
for i in range(self.iniNumTower):
tempStack = MyStack("Tower" + str(i + 1))
self.TowerList.append(tempStack)
#User to choose their diffculty
self.options = raw_input("Select your Difficulty: ")
if self.options == "Beginner":
self.numDisk = 3
elif self.options == "Advance":
self.numDisk = 6
else:
self.numDisk = 10
for i in range(self.numDisk, 0, -1):
self.endGameList.append(i)
self.TowerList[0].push(i)
print("[1] - Continue Steps")
print("[2] - Auto Solve")
print("[0=9] - Quit")
choice = int(raw_input("Enter choice: "))
while choice != 9:
if choice == 0:
break
elif choice == 1:
# while checkEndGame(endGameList,targetTower._data,helperTower._data) != 1:
moveFrom = 0
moveTo = 0
a.printAllTowers()
a.printTowerOptions()
moveFrom = int(raw_input("Move from: "))
# if(moveFrom!=9):
moveTo = int(raw_input("Move to : "))
if a.checkDiskMove(a.TowerList[moveFrom - 1], a.TowerList[moveTo - 1]) == 1:
a.moveDisk(a.TowerList[moveFrom - 1], a.TowerList[moveTo - 1])
else:
print "Unable to move from " + a.TowerList[moveFrom - 1].name + " to " + a.TowerList[
moveTo - 1].name
if a.checkEndGame() == 1:
a.printAllTowers()
print "You've Win!"
print "Game End"
break
elif choice == 2:
a.autoSolve(a.numDisk, a.TowerList[0], a.TowerList[2], a.TowerList[1])
if a.checkEndGame() == 1:
a.printAllTowers()
print "You've Win!"
print "Game End"
break
def autoSolve(self,n, from_rod, to_rod, aux_rod):
if n == 1:
print "Move disk 1 from rod", from_rod.name, "to rod", to_rod.name
cap = CurrentCapture()
to_rod.push(from_rod.pop())
cap.capture(self.TowerList[0], self.TowerList[2], self.TowerList[1])
self.answerKey.append(cap)
return
TowerOfHanoi().autoSolve(n - 1, from_rod, aux_rod, to_rod)
print "Move disk", n, "from rod", from_rod.name, "to rod", to_rod.name
to_rod.push(from_rod.pop())
TowerOfHanoi().autoSolve(n - 1, aux_rod, to_rod, from_rod)
This is the error I got, "IndexError: list index out of range".
Edit main method in this. I hope this helps. I am not sure why the list is out of range when i did a print out, it shows 3.
Edit2 with traceback
traceback (most recent call last):
TowerOfHanoi().autoSolve(n - 1, from_rod, aux_rod, to_rod)
cap.capture(self.TowerList[0], self.TowerList[2], self.TowerList[1])
IndexError: list index out of range
Judging from the fact that you only access a list on line 6, the error must lie there. Without more information about the code and functions in it, I can't help more than that, unfortunately!
Hope this helps.
Related
im new in Python and i'm self learner. Actually im trying to create easy word game.
Currently im in stage when im adding monster/player damage and I have three problems which i can't figure out.
I want every room to have a chance for a random monster to appear from "Monster" dictionary. However, after meeting a monster for the first time, the value of his life after the fight is overwritten in the dictionary. This causes the monster to have a negative life when you meet it again. How to fix it?
When i'll find monster in any room, I have set two options "run" and "fight". When someone will type any other command, the loop returns to the draw whether a monster or a chest will appear in the room. I want the return to occur until after the event is randomly selected
I have problem with placing command
if playerLife <= 0:
print("You died, your body will lay in chambers forever")
break
I want to end game immidiatly after players dead.
import random
from enum import Enum
playerDamage = 4
playerLife = 100
def find_aprox_value(value):
lowestValue = 0.9 * value
highestValue = 1.1 * value
return random.randint(lowestValue, highestValue)
def weapon_hit(chance):
if_hit = random.uniform(1, 100)
if if_hit < chance:
monsterLife[drawnMonster] = monsterLife[drawnMonster] - playerDamage
print("You hit a monster and you dealt 4 damage. It has", monsterLife[drawnMonster], " life")
else:
print("You missed")
def monster_hit():
global playerLife
monsterHit = monsterDamage[drawnMonster]
print("Monster did", monsterDamage[drawnMonster], "damage")
playerLife = playerLife - monsterHit
print("You have ", playerLife, "life")
Event = Enum('Event', ['Chest', 'Monster'])
Chest = Enum('Chest', {'greenChest': 'zieloną skrzynię',
'blueChest': 'niebieską skrzynię',
'violetChest': 'fioletową skrzynię',
'orangeChest': 'pomarańczową skrzynię'
})
Monster = Enum('Monster', {'Rat': 'Szczura',
'Bat': 'Nietoperza',
'GiantSpider': 'Ogromnego Pająka',
'Wolf': 'Wilka',
})
Color = Enum('Color', ['greenChest', 'blueChest', 'violetChest', 'orangeChest'])
MonsterKind = Enum('MonsterKind', ['Rat', 'Bat', 'GiantSpider', 'Wolf'])
eventDictionary = {
Event.Chest: 0.4,
Event.Monster: 0.6
}
eventList = list(eventDictionary.keys())
eventProbability = list(eventDictionary.values())
chestDictionary = {
Chest.greenChest: 0.5,
Chest.blueChest: 0.3,
Chest.violetChest: 0.15,
Chest.orangeChest: 0.05
}
PremiumChestDictionary = {
Chest.blueChest: 0.5,
Chest.violetChest: 0.35,
Chest.orangeChest: 0.15
}
MonsterDictionary = {
Monster.Rat: 0.5,
Monster.Bat: 0.3,
Monster.GiantSpider: 0.15,
Monster.Wolf: 0.05
}
chestList = list(chestDictionary.keys())
chestProbability = list(chestDictionary.values())
MonsterList = list(MonsterDictionary.keys())
MonsterProbability = list(MonsterDictionary.values())
PremiumChestList = list(PremiumChestDictionary.keys())
PremiumChestProbability = list(PremiumChestDictionary.values())
colorValue = {
Chest.greenChest: 1000,
Chest.blueChest: 4000,
Chest.violetChest: 9000,
Chest.orangeChest: 16000
}
monsterLife = {
Monster.Rat: 5,
Monster.Bat: 10,
Monster.GiantSpider: 15,
Monster.Wolf: 30
}
monsterDamage = {
Monster.Rat: 3,
Monster.Bat: 5,
Monster.GiantSpider: 8,
Monster.Wolf: 12
}
gameLength = 10
Gold = 0
while gameLength > 0:
gameAnswer = input("Do you want to move forward? \n")
if gameAnswer == "yes":
print("Great, lets see what is inside")
drawnEvent = random.choices(eventList, eventProbability)[0]
if drawnEvent == Event.Chest:
drawnChest = random.choices(chestList, chestProbability)[0]
goldAcquire = find_aprox_value(colorValue[drawnChest])
print("You have find ", drawnChest.value, "inside was", goldAcquire, "gold")
Gold = Gold + goldAcquire
gameLength = gameLength - 1
elif drawnEvent == Event.Monster:
drawnMonster = random.choices(MonsterList, MonsterProbability)[0]
print("Oh no, you have find", drawnMonster.value, "which has", monsterLife[drawnMonster],
"life .If you will defeat him, you will find great treasure.")
eventAnswer = input(" What is your choice?(fight, run)")
if eventAnswer == "fight":
while monsterLife[drawnMonster] > 0:
weapon_hit(70)
if monsterLife[drawnMonster] > 0:
monster_hit()
if playerLife <= 0:
print("You died, your body will lay in chambers forever")
break
drawnPremiumChest = random.choices(PremiumChestList, PremiumChestProbability)[0]
goldAcquire = find_aprox_value(colorValue[drawnPremiumChest])
print("Congratulations, you have defeat a monster, and you found", drawnPremiumChest.value,
", inside was", goldAcquire, " gold")
Gold = Gold + goldAcquire
gameLength = gameLength - 1
elif eventAnswer == "run":
gameLength = gameLength - 1
print("you have successfully run")
else:
print("Only options is run or fight")
continue
else:
print("Your only options is move forward")
continue
print("Congratulations you have acquired", Gold, "gold")
As I mentioned at the beginning, I am just starting to learn python and this is my first post on this forum, so please be understanding and thank you for your help in advance.
There are many solutions to your problem (at least five). Here are the simplest:
The simplest: Instead of break, you can end the program with sys.exit (0) (with code 0 because it's not an error).
More elegant:
# Outer loop:
while gameLength > 0 and playerLife > 0:
# Inner loop:
while monsterLife[drawnMonster] > 0 and playerLife > 0:
# Statement 'if playerLife <= 0' becomes redundant
# Outside the loop:
if playerLife > 0:
print("Congratulations ...")
else:
print("You died, ...")
or:
# Outer loop:
while gameLength > 0 and playerLife > 0:
# Inner loop:
while monsterLife[drawnMonster] > 0:
if playerLife <= 0:
break
# Outside the loop:
if playerLife > 0:
print("Congratulations ...")
else:
print("You died, ...")
More advanced: instead of using break statement, an exception can be thrown. The exception must be handled by the try ... catch statement.
BTW: both continue statements are completely unnecessary - these are the last statements of the loop, so they don't change anything about the execution of the loop.
Have fun with Python.
so my code is designed to basically create a bingo card, then when you press enter draws a number and changes the bingo card value to 0 if the drawn number matches. My issue is that my code isn't properly producing a bingo or not a bingo which you can see towards the end of the code. How should I change this so that my code will return bingo when I have bingo.
import random #Condernsed solo version with call and player together
import numpy as np
def bingo_card(): #Code to generate BINGO card using numpy array
test1=np.array(random.sample(range(1,16),5))
test2=np.array(random.sample(range(16,31),5))
test3=np.array(random.sample(range(31,46),5))
test4=np.array(random.sample(range(46,61),5))
test5=np.array(random.sample(range(61,76),5))
test= np.concatenate((test1,test2,test3,test4,test5))
test= test.reshape(5,5)
test[2,2]=0
bingo_card.test = test
BINGO= print("Your Card")
print("B", test[0]),
print("I", test[1]),
print("N", test[2]),
print("G", test[3]),
print("O", test[4])
card = BINGO
return card
def called_value(): #should be close to the code we use to check if called value is in generated matrix, may need some formatting and fixing
checked_card = bingo_card.test
while True:
called_num = input ("Type called number to mark card or press 's' to quit if you think you have bingo").lower()
if called_num != "s":
number_check = int(called_num)
checked_card = np.where(checked_card==number_check,0,checked_card)
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
elif called_num == "s":
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
row_zeros = np.count_nonzero(checked_card == 0, axis=1)
col_zeros = np.count_nonzero(checked_card == 0, axis=0)
diagonal_zeros = np.count_nonzero(np.diag(checked_card) == 0)
diagonal1_zeros = np.count_nonzero(np.diag(np.fliplr(checked_card)) == 0)
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
def solo():
bingo_card()
called_value()
solo()
You've committed one of the classic blunders.
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
row_zeros[i] or col_zeros[i] is going to be True or False (usually True), which is never equal to 5. And you don't need to loop to check the diagonals. You need:
if diagonal_zeros == 5 or diagonal1_zeros == 5:
return ("Bingo!")
for i in range (5):
if row_zeros[i] == 5 or col_zeros[i] == 5:
return ("Bingo!")
return ("Not Bingo")
I am making a game in python and I get this error:
UnboundLocalError: local variable 'playerY' referenced before assignment
The code is:
import voyager200librarys
playerY = 1
playerX = 0
amountOfRows = 3
command = voyager200librarys.menu ("P Y C R A F T", ["Play", "Quit"])
if (command == "Play"):
world = [0,0,0,0,-1,0,1,1,1]
def printWorld ():
index = 0
indexCheck = 0
for x in range(len (world)):
voyager200librarys.printWithoutNewLine (" ")
if (world [index] == 0):
voyager200librarys.printWithoutNewLine (" ")
if (world [index] == 1):
voyager200librarys.printWithoutNewLine ("D")
if (world [index] == -1):
voyager200librarys.printWithoutNewLine ("&")
indexCheck += 1
if (indexCheck == 3):
print ("")
indexCheck = 0
index += 1
def mainMenu ():
print ("")
whatToDo = voyager200librarys.menu ("What To Do?", ["Move"])
if (whatToDo == "Move"):
movementControls ()
def movementControls ():
print ("")
print ("Movement Controls:")
print ("< > Ʌ")
print ("")
print ("| | |")
print ("V V V")
print ("")
print ("1 2 3")
print ("")
command = input ("Plase Pick An Option: ")
command = int (command)
if (command != 1):
if (command != 2):
if (command != 3):
print ("Plase Pick A Valid Option Next Time.")
if (command == 1):
world [playerY * amountOfRows + playerX] = 0 #(The problem occurs here)
playerX -= 1
if (command == 2):
world [playerY * amountOfRows + playerX] = 0
playerX += 1
if (command == 3):
world [playerY * amountOfRows + playerX] = 0
playerY -= 0
while (True):
printWorld()
mainMenu()
world [playerY * amountOfRows + playerX] = -1
and I've tried swapping "playerX" and "playerY" but it doesn't fix it! Btw the game itself is a ripoff of minecraft, and if your missing any information ask me.
If anyone has answers please help!
P.S. A quick answer would be great.
P.S. It's python.
For a class project, my groupmates and I are to code a tic tac toe program. So far, this is what we have. All of us have 0 experience in python and this is our first time actually coding in python.
import random
import colorama
from colorama import Fore, Style
print(Fore.LIGHTWHITE_EX + "Tic Tac Toe - Below is the key to the board.")
Style.RESET_ALL
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
print(Fore.LIGHTBLUE_EX + "0|1|2\n3|4|5\n6|7|8\n")
def print_board():
for i in range(0, 3):
for j in range(0, 3):
if (board[i*3 + j] == 'X'):
print(Fore.RED + board[i*3 + j], end = '')
elif (board[i*3 + j] == 'O'):
print(Fore.BLUE + board[i*3 + j], end = '')
else:
print(board[i*3 + j], end = '')
print(Style.RESET_ALL, end = '')
if j != 2:
print('|', end = '')
print()
print_board()
while True:
x = input('Player 1, pick a number from 0-8: ') #
x = int(x)
board[x] = 'X'
print_board()
o = input('Player 2, pick a number from 0-8:')
o = int(o)
board[o] = 'O'
print_board()
answer = raw_input("Would you like to play it again?")
if answer == 'yes':
restart_game()
else:
close_game()
WAYS_T0_WIN = ((0,1,2)(3,4,5)(6,7,8)(0,3,6)(1,4,7)(2,5,8)(0,4,8)(2,4,6))
We're stuck on how to have the program detect when someone has won the game and then have it print "You won!" and also having the program detect when it's a tie and print "It's a tie!". We've looked all over the internet for a solution but none of them work and we can't understand the instructions. No use asking the teacher because they don't know python or how to code.
I have changed your code in such a way that first of all "save players choices" and in second "check if a player won and break the loop":
import random
import colorama
from colorama import Fore, Style
print(Fore.LIGHTWHITE_EX + "Tic Tac Toe - Below is the key to the board.")
Style.RESET_ALL
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
print(Fore.LIGHTBLUE_EX + "0|1|2\n3|4|5\n6|7|8\n")
def print_board():
for i in range(0, 3):
for j in range(0, 3):
if (board[i*3 + j] == 'X'):
print(Fore.RED + board[i*3 + j], end = '')
elif (board[i*3 + j] == 'O'):
print(Fore.BLUE + board[i*3 + j], end = '')
else:
print(board[i*3 + j], end = '')
print(Style.RESET_ALL, end = '')
if j != 2:
print('|', end = '')
print()
def won(choices):
WAYS_T0_WIN = [(0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)]
for tpl in WAYS_T0_WIN:
if all(e in choices for e in tpl):
return True
return False
print_board()
turn = True
first_player_choices = []
second_player_choices = []
while True:
if turn:
x = input('Player 1, pick a number from 0-8: ') #
x = int(x)
if board[x] == '_':
board[x] = 'X'
first_player_choices.append(x)
turn = not turn
print_board()
if won(first_player_choices):
print('Player 1 won!')
break
else:
print('Already taken! Again:')
continue
else:
o = input('Player 2, pick a number from 0-8: ') #
o = int(o)
if board[o] == '_':
board[o] = 'O'
second_player_choices.append(o)
turn = not turn
print_board()
if won(second_player_choices):
print('Player 2 won!')
break
else:
print('Already taken! Again:')
continue
# answer = input("Would you like to play it again?")
# if answer == 'yes':
# restart_game()
# else:
# close_game()
I also added a condition to check if players choice is already taken! By the way, you can do it way much better. :)
EDIT: there was a little problem with spaces in my answer here and I solve it in edit. Now you can directly copy it in a py file and run it!
Firstly, you need a condition which doesn't allow the same space to be allocated twice, when test running I could type space 3 as much as I wanted for example without it stopping me. You need some sort of check for this.
Secondly, for the actual win system, you made it easy because you already have the co-ordinates for all of the winning games, I recommend something along the lines of:
def checkwin(team):
for i in WAYS_TO_WIN:
checked = False
while not checked:
k = 0
for j in i:
if board[j] == team:
k+=1
if k == 3:
return True
checked = True
This way is checks if any of the co-ordinates have all 3 of any set. You might have to adjust this code, but this looks like a solution.
Note: I'm still a beginner at coding and I stumbled upon your thread, this is an idea not necessarily a working solution
I am converting an array into a string to print, but the compiler still says not iterable.
Traceback (most recent call last):
File "python", line 157, in <module>
File "python", line 56, in total
TypeError: 'int' object is not iterable
The function total() is located on line 56, if you think it is the problem, but if you run the script, you should find that the function works properly every other instance.
import random
import time
def makeDeck():
cards = []
num = 1
for card in range(52):
cards.append(num)
num += 1
if num == 13:
num = 1
return cards
#def shuffle(cards):
#for card in cards:
#num = random.randint(0,51)
#cards.insert(0, cards[num])
#return cards
def shuffle(deck):
for card in deck:
hold = deck.pop(0)
deck.insert(random.randint(1,51),hold)
return deck
def cardToString(hand):
cardString = []
for card in hand:
if card == 1:
cardString.append('Ace')
elif card == 11:
cardString.append('Jack')
elif card == 12:
cardString.append('Queen')
elif card == 13:
cardString.append('King')
else:
cardString.append(str(card))
for card in cardString:
return card
def deal(user,deck):
hand = []
for x in range(2):
hand.append(deck.pop(0))
return hand
def deal1(user,deck):
hand = []
for card in deck:
hand.append(deck.pop(0))
return hand
def total(hand):
score = 0
for card in hand:
if(card>10):
score += 10
elif(card != 1):
score += card
else:
if(score>=11):
score+=1
else:
score+=11
return score
#def playGame():
#to do
name1 = input('Player 1, please enter your name:\n')
p2q = input('Will there be two plaers? (y/n)')
if(p2q == 'y' or p2q == 'Y' ):
p2yn = 1
name2 = input('Player 2, please enter your name:\n')
elif(p2q == 'n' or p2q == 'N'):
p2yn = 0
deck = makeDeck()
shuffle(deck)
p1hand = deal(name1,deck)
if(p2yn == 1):
p2hand = deal(name2,deck)
else:
print(end = ' ')
hs=0
print(str(name1)+', your hand is:', end = ' ' )
cardToString(p1hand)
print(str(p1hand[0])+',',p1hand[1], end = ' ')
print('and your total is', total(p1hand))
time.sleep(2)
tot1 = total(p1hand)
while(tot1 < 21):
p1cvar = input('Would you like another card? (y/n)\n')
if(p1cvar =='n' or p1cvar == 'N'):
break
else:
p1hand.append(deck.pop(0))
newCard = str(p1hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p1hand))
time.sleep(1)
if(total(p1hand) <= 21):
hs = total(p1hand)
else:
print('You went over 21!')
p1hand=0
time.sleep(1)
break
if(p1hand != 0):
print('The high score is', total(p1hand), 'held by', str(name1)+'.')
time.sleep(1)
shuffle(deck)
if(p2yn == 1):
print(str(name2)+', your hand is:', end = ' ' )
cardToString(p2hand)
print(str(p2hand[0])+',',p2hand[1], end = ' ')
print('and your total is', total(p2hand))
time.sleep(2)
tot1 = total(p2hand)
while(tot1 < 21):
p2cvar = input('Would you like another card? (y/n)\n')
if(p2cvar =='n' or p2cvar == 'N'):
break
else:
p2hand.append(deck.pop(0))
newCard = str(p2hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p2hand))
time.sleep(1)
if(total(p2hand)>21):
print('You went over 21!')
p2hand=0
time.sleep(1)
break
if(p2hand != 0 and total(p2hand)>hs):
print('The high score is', total(p2hand), 'held by', str(name2)+'.')
hs = total(p2hand)
time.sleep(1)
dealerHand = deal('Dealer',deck)
print("The dealer's hand is:", end = ' ' )
cardToString(dealerHand)
print(str(dealerHand[0])+',',dealerHand[1], end = ' ')
print('and their total is', total(dealerHand))
time.sleep(2)
totD = total(dealerHand)
while(totD < 21):
tdh = total(dealerHand)
if(tdh<hs and tdh<22):
dealerHand.append(deck.pop(0))
newCard = str(dealerHand[-1])
cardToString(newCard)
print('Dealer got a', newCard)
time.sleep(.5)
print("Dealer's total is now", total(dealerHand))
time.sleep(1)
if(total(dealerHand) <= 21 and total(dealerHand)>hs):
hs = total(dealerHand)
else:
print('Dealer went over 21!')
dealerHand=0
else:
break
if(dealerHand != 0):
print('The high score is', total(dealerHand), 'held by', str("Dealer")+'.')
while(total(p1hand)>21 or total(dealerHand)>21):
if(total(dealerHand)>21):
print('Dealer has been eliminated from play!')
elif(total(p1hand)>21):
print(name1,'has been eliminated from play!')
About 11 lines up from the bottom of your code block, you are setting the dealers hand to 0:
....
else:
print('Dealer went over 21!')
dealerHand=0
This is concerning since their hand should be a list. Thus when you try to iterate over it to count the total, you get that an int isn't iteratable.
Should probably be something like
dealerHand = []
Also, a few lines after that, you are asking if dealerHand!=0, when I think you mean total(dealerHand)
You should also be careful with your other assignments that change a variable from a list to an int such as
#Around line 111
print('You went over 21!')
p1hand=0
time.sleep(1)
break
.....
#Around line 140
print('You went over 21!')
p2hand=0
time.sleep(1)
break
Because Python is not strongly type, changing the type of a given variable name can lead to a lot of these kinds of problems
#Stephen gave you the direct answer. I suggest using pylint3 (or some other linter) on your code. It would have told you the problem
R:170, 6: Redefinition of dealerHand type from list to int
(redefined-variable-type)
This will help you in the future.