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.
Related
I am making this kind of a game but it isn't really a game so basically I want this to run every time I hit space but it doesn't work no matter what I try so I would be really thankful if somebody could have helped me out on this.
import random
import keyboard
food = 5
x = 0
y = 0
if keyboard.is_pressed('space'):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)
Your code runs once and immediately skips over keyboard.is_pressed("space"), and then exits.
What you want to do instead is to loop forever, and use the keyboard module's read_key functionality to make it wait for a keypress.
An example of this is this - I also added support for exiting the loop/game with esc.
import random
import keyboard
food = 5
x = 0
y = 0
while True:
keyboard.read_key()
if keyboard.is_pressed("esc"):
print("Stopping play...")
break
elif keyboard.is_pressed("space"):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)
You need to put the if statement in a while loop. But ALSO be sure to have some kind of exit code. Below, I used the keypress esc to stop the while loop:
import random
import keyboard
food = 5
x = 0
y = 0
while True:
keyboard.read_key() # an important inclusion thanks to #wkl
if keyboard.is_pressed('esc'):
break
elif keyboard.is_pressed('space'):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)
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
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
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.
So I have to create a game of craps that takes into account bets for an assignment. So far, my code works in that the dice rolls are correct and other little tidbits the assignment called for. But now I don't know how to record each game as a win / lose for the player or computer so that the pot can be added to the winner's money. I realize that my code is half doe, isn't finished, and doesn't run as is, but I just seriously need some help from someone. Please and thank you. Here are more specific directions on my assignment:
http://www.ics.uci.edu/~kay/courses/i42/hw/labA.html
import random
def craps():
print("Welcome to Sky Masterson's Craps Game")
handle_commands()
def handle_commands(): # Collection -> Collection (plus interaction)
""" Display menu to user, accept and process commands
"""
playerInitial = 500
compInitial = 500
MENU = "How much would you like to bet?: "
while True:
bet = float(input(MENU))
if bet <= playerInitial:
human_game()
elif bet > playerInitial:
print("Sorry, you can't bet more than you have")
def handle_commands2():
MENU2 = "Would you like to play again? (y or n): "
while True:
response = input (MENU2)
if response=="y":
counter = counter + multipleGames()
elif response=="n":
while ( counter < 2000):
roll = random.randint(1, 6) + random.randint(1,6)
updateCount(roll)
counter += 1
print ("Thank you for playing." + "\n" + "\n" + "Distribution of dice rolls: " + "\n")
return
else:
invalid_command(response)
def invalid_command(reponse):
"""print message for invalid menu command.
"""
print("Sorry; '" + response + "' isn't a valid command. Please try again.")
def play_game():
"""prints shooters roll results
"""
diceRoll = 0
roll = random.randint(1, 6) + random.randint(1, 6)
updateCount(roll)
diceRoll = diceRoll + 1
point = 0
print("The roll is " + str(roll))
response = (roll)
if response== 7 or response== 11:
print("Natural; shooter wins" + "\n" + "Thank you for playing")
handle_commands2()
elif response== 2 or response== 3 or response== 12:
print("Crapped out; shooter loses" + "\n" + "Thank you for playing")
handle_commands2()
else:
print("The point is " + str(roll))
point = roll
secondRoll = 0
handle_commands()
while (secondRoll !=point) and (secondRoll != 7):
secondRoll = random.randint(1, 6) + random.randint(1, 6)
updateCount(secondRoll)
diceRoll += 1
print("The roll is " + str(secondRoll))
handle_commands()
if secondRoll== point:
print ("Made the point; shooter wins." + "\n" + "Thank you for playing")
handle_commands2()
elif (secondRoll == 7):
print ("Crapped out; shooter loses." + "\n" + "Thank you for playing")
handle_commands2()
return diceRoll
def multipleGames():
gameCounter = 0
while (gameCounter <= 2000):
print("Your game: ")
gameCounter += play_game()
print("\n")
print("Computer's game: ")
gameCounter += play_game()
print( "\n")
return gameCounter
def updateCount(point):
count =List[point] + 1
List[point] = count
List = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
def human_game():
playerInitial = 500
compInitial = 500
while True:
play_game()
if
playerInitial += bet
compInitial += bet
counter = 0
counter = counter + multipleGames()
playerInitial -= bet
craps()
for point in List:
print("%2d" %(point) + ": " + "%3d" %(List[point]) + " " + "(" + ("%2d" % (int((List[point])/2000*100)))+ "%" + ")" + " " + ("*" *(int((List[point])/2000*100))))
Use classes:
import random
class Human:
def __init__(self):
self.name = 'Human'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Computer:
def __init__(self):
self.name = 'Computer'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Game:
def __init__(self):
self.rolls = []
self.currentPlayer = None
def roll(self):
self.rolls.append(random.randint(1, 6))
if __name__ == '__main__':
human = Human()
computer = Computer()
game = Game()
game.roll()
print games.rolls
I won't code all of it for you, but using classes will make things much simpler.