python turtle crashes with loop - python

I have a class and functions inside the class. They all work fine but when I input the loop so that it can keep asking the user to put in another circle it crashes. What's going on? Everything works fine without the loop...
from turtle import*
snowman = 1
owl = Owlet()
s_answer = input("radius of first snowman circle?")
answer = int(s_answer)
s_xPos = input("What is your x position?")
xPos = int(s_xPos)
s_yPos = input("What is your y position?")
yPos = int(s_yPos)
#owl.__init__(xPos,yPos,answer,"black")
owl.centered_circle(xPos,yPos,answer,"black")
while snowman == True:
answer = int(s_answer)
s_xPos = input("What is your x position?")
xPos = int(s_xPos)
s_yPos = input("What is your y position?")
yPos = int(s_yPos)
#owl.__init__(xPos,yPos,answer,"black")
owl.centered_circle(xPos,yPos,answer,"black")

You'll never break out of that loop unless somewhere in the loop you either insert a break or a snowman=False

Related

Issue with python skipping code in simple chess program

I am creating a simple program for chess, and I ran to an issue of supposedly python skipping code.
Program entry is: find_side()
Console output:
Enter your team(1-black 2-white):1
<PlayResult at 0x3ec1dc0 (move=e2e4, ponder=d7d5, info={}, draw_offered=False, resigned=False)>
Enter your enemies move:
According to the console output, engine randomly generated move for the White player and made a counter-response in ponder. But I have input for that, looks like, that python is executing result_engine sooner than user input.
Also, there's one more problem. Engine completely ignores the chess.engine.turn = turn line.
I am using stockfish 11 as an engine and import chess as an link between python code and engine with universal chess engine
Code:
import chess
import chess.engine
import time
import os
def logic_white():
engine = chess.engine.SimpleEngine.popen_uci("C:\\Users\\Admin\\Desktop\\sf.exe")
board = chess.Board()
turn = True # True - white False - black
while True:
chess.engine.turn = turn # This isn't working
result_engine = engine.play(board,chess.engine.Limit(time=0.1))
print(result_engine)
res = input("Enter your enemie's move: ")
move = chess.Move.from_uci(res)
board.push(move)
turn = not turn
time.sleep(0.5)
def logic_black():
engine = chess.engine.SimpleEngine.popen_uci("C:\\Users\\Admin\\Desktop\\sf.exe")
board = chess.Board()
turn = True # True - white False - black
while True:
chess.engine.turn = turn # This isn't working
res = input("Enter your enemie's move: ")
move = chess.Move.from_uci(res) #Inputting the enemy move and putting in on the virtual board
board.push(move)
result_engine = engine.play(board,chess.engine.Limit(time=0.1)) #Calculating best move to respond
print(result_engine)
board.push(result_engine) #Push the engine's move to the virtual board
turn = not turn # Inverting turn, so turns can change from black to white, etc.
time.sleep(0.5)
def find_side():
if(input("Enter your team(1-black 2-white):")) == 1:
logic_black()
else:
logic_white()
Python's input function returns a string, so it will never be equal to the integer 1. As such, the code will always go into the else block. To fix this, either convert the input to an integer or compare it to '1'.
def find_side():
if int(input("Enter your team(1-black 2-white):")) == 1:
logic_black()
else:
logic_white()

TicTacToe project in Python 2: I am trying to avoid using global variables and return variables instead

I am working on a project, and I have no idea how to avoid using global variables. I have a list of functions that perform bits and pieces but I am not able to pass variables between them!
Here is my current code:
===================
def player_names_input():
global player_A_name,player_B_name
player_A_name = raw_input("Please enter name for Player A : ")
player_B_name = raw_input("Please enter name for Player B : ")
def coin_flip():
global player_A_name,player_B_name,start_player,end_player,game_state
game_state = "running"
import random
print "\nFlipping a coin to see who starts first..."
random_int = random.randint(0, 1)
if random_int == 0:
coin = 'Heads'
start_player = player_A_name
end_player = player_B_name
else:
coin = 'Tails'
start_player = player_B_name
end_player = player_A_name
print '\nCoin flip --> ',coin
print '\nStarting player --> ',start_player
print '\nStarting player gets "X"'
player_names_input()
coin_flip()
Here is my failed attempt to use return instead of global:
=========================================================
def player_names_input():
player_A_name = raw_input("Please enter name for Player A : ")
player_B_name = raw_input("Please enter name for Player B : ")
return player_A_name,player_B_name
def coin_flip(player_A_name,player_B_name):
game_state = "running"
import random
print "\nFlipping a coin to see who starts first..."
random_int = random.randint(0, 1)
if random_int == 0:
coin = 'Heads'
start_player = player_A_name
end_player = player_B_name
else:
coin = 'Tails'
start_player = player_B_name
end_player = player_A_name
print '\nCoin flip --> ',coin
print '\nStarting player --> ',start_player
print '\nStarting player gets "X"'
player_names_input()
coin_flip(player_A_name,player_B_name)
1- Please help make my second code run, I really wanna avoid global variables as everyone recommends.
2- Please critique my code, I am in the beginning and I am trying to learn writing good code (not just code). How bad is my attempt?
Since you have defined player_names_input() to return a 2-tuple (the two values, player_A_name and player_B_name), you could just assign them like so in the scope you are using that function,
player_A_name, player_B_name = player_names_input()
Now, when this is called:
coin_flip(player_A_name, player_B_name)
The two variables will be available for use.
You may want to consider wrapping the actual main program in a main method like
def main():
player_A_name, player_B_name = player_names_input()
coin_flip(player_A_name, player_B_name)
And call that if that file was directly executed - this is done by checking the magic __name__ variable to equal to the string '__main__', so add this too to the end of your program file.
if __name__ == '__main__':
main()

Save File Function

So for my intro programming class we have to create a game with a save/load function and I'm trying to test out some code to make sure it works.
For some reason I cannot get the following function to work properly. I've tried going through it line by line in the Idle and it works just fine there but once I try to use the same system in a function it just will not work. Help please?
def save(name,inventory,mapGrid,x,y,enemy):`
choice = 0
file = shelve.open("save_files")
save = {'save1':file['save1'],'save2':file['save2'],'save3':file['save3']}
print("Where would you like to save?")
print("Save 1 -", save['save1']['name'])
print("Save 2 -", save['save2']['name'])
print("Save 3 -", save['save3']['name'])
choice = input("Enter Number:\t")
if choice == 1:
save['save1']['name'] = name
save['save1']['inventory'] = inventory
save['save1']['mapGrid'] = mapGrid
save['save1']['x'] = x
save['save1']['y'] = y
save['save1']['enemy'] = enemy
file['save1'] = save['save1']
file.sync()
if choice == 2:
save['save2']['name'] = name
save['save2']['inventory'] = inventory
save['save2']['mapGrid'] = mapGrid
save['save2']['x'] = x
save['save2']['y'] = y
save['save2']['enemy'] = enemy
file['save2'] = save['save2']
file.sync()
if choice == 3:
save['save3']['name'] = name
save['save3']['inventory'] = inventory
save['save3']['mapGrid'] = mapGrid
save['save3']['x'] = x
save['save3']['y'] = y
save['save3']['enemy'] = enemy
file['save3'] = save['save3']
file.sync()
file.close()
print("Game Saved")
EDIT: After running the function it should save the dictionary to file['save#'] and allow me to access the data later on, but the data doesn't save to the shelve file and when I try to access it again there's nothing there. ((Sorry should have put this in right off the bat))
For example if I run the save() function again it should display the name associated with the save file, but it just shows 'EMPTY'.
The basic thing I have the save_files set to is
file['save#'] = {'name':'EMPTY'}
Since your if statements are comparing int, make sure that choice is also an integer. It's possible that choice is actually a string, in which case none of the comparisons will be True. Basically:
choice = int(input("Enter Number:\t"))
Alternatively you could change all comparisons to strings, but the important thing is to assure type consistency in the comparisons

Python 2 game coordinates class

I wanted to create a x-y coordinate system even though this is supposed to be a text RPG as to keep track of where everything is. So, I was experimenting on making a function and test for that function that would let the character move on a x-y grid, however, no matter what I try, I cannot make it work. Here is the code:
class Player:
def movement(charactor_movement):
proceed = 0
if charactor_movement == "left":
character.position_x = character.position_x - 1
proceed = 1
elif charactor_movement == "right":
character.position_x = character.position_x + 1
proceed = 1
elif charactor_movement == "forward":
character.position_y = character.position_y + 1
proceed = 1
elif charactor_movement == "backward" or charactor_movement == "back":
character.position_y = character.position_y - 1
proceed = 1
charactor = Player()
charactor.position_x = 0
charactor.position_y = 0
proceed = 0
while proceed == 0:
print "You are at",
print charactor.position_x,
print"x and",
print charactor.position_y,
print"y."
global charactor_movement
charactor_movement = raw_input("Where are you going?")
charactor.movement()
At this point, it does what it is supposed to do up to changing the coordinates, as it prints "You are at 0 x and 0 y" and "Where are you going?" no matter what I type. I have tried adding an else to the function which it defaulted to no matter what I typed and gave me "Sorry, I cannot understand you." Any comments on fixing or generally improving the code would be appreciated.(Note: For the testing I purposely did not add a way to exit. The class is what i need fixed.)
You are getting the same coordinates with each iteration because your values within your while loop are not changing. Incrementing character.position_x within movement will never change the value of character.position_x within your while loop, as it is outside your function's scope. You have to use the global keyword within your movement function for each variable you are changing should you want your current logic to remain the same. Additionally, why not just pass charactor_movement as a parameter to your movement function, as opposed to using global as you currently are doing.
A minimal example:
Consider the following:
def somefunct(x):
mycode = x
mycode = 'no codez'
while True:
print mycode
codez = raw_input('gimme teh codez: ')
somefunct(codez)
which outputs
>>>[evaluate untitled-1.py]
no codez
gimme teh codez: codez!
no codez
Declaring mycode as global in the function places it in the scope of the while loop when assigned, thus
def somefunct(x):
global mycode #make variable global here
mycode = x
mycode = 'no codez'
while True:
print mycode
codez = raw_input('gimme teh codez: ')
somefunct(codez)
results in the output
>>>[evaluate untitled-1.py]
no codez
gimme teh codez: codez!
codez!

Python: NameError: global name 'lol' is not defined

I know there are a lot of these but i've been searching for an hour and nothing is working.
ship2X=eg.passwordbox("Player " + str(playerNumber) + " input the x co-ordinate for your SECOND ship ")
ship2Y=eg.passwordbox("Player " + str(playerNumber) + " input the y co-ordinate for your SECOND ship ")
return[ship2X, ship2Y]
The above code is in a function.
def haveShot(playerNumber, ship, ship2, board):
global ship2
eg.msgbox("Player " + str(playerNumber) + " your shot")
hit=False
shotX=eg.enterbox("Enter the x-coordinate for your shot: ")
shotY=eg.enterbox("Enter the y-coordinate for your shot: ")
.... error checking here....
if int(shotX) == int(ship[0]) and int(shotY) == int(ship[1]):
board[5 - int(shotY)][int(shotX) - 1] = "X"
eg.msgbox("Nice shot! You hit ship 1")
hit = True
elif int(shotX) == int(ship2[0]) and int(shotY) == int(ship2[1]):
board[5 - int(shotY)][int(shotX) - 1] = "X"
eg.msgbox("Nice shot! You hit ship 2")
hit = True
elif board[5 - int(shotY)][int(shotX) - 1] == "o":
eg.msgbox("You already tried that shot! D'oh!")
else:
board[5 - int(shotY)][int(shotX) - 1] = "o"
eg.msgbox("Unlucky - you missed!")
Ye, I have an if before that.
Then I have this near the end:
hit = False
winner = "0"
p1 = 0
p2 = 0
while hit == False:
hit = haveShot("1", player2Ship, player2Ship, player1Board)
if hit:
p1 = p1+1
hit = haveShot("2", player1Ship, player1Ship, player2Board)
if hit:
p2 = p2+2
I copied it from the first enter ship thing so I'm super confused as to why that's happening...
Any ideas?
If you want to see the full code you can see it at: http://pastebin.com/TAyHtnTs
The error I have is if I do enter the correct co-ordinate for the second ship it says I missed it, however if I enter the correct co-ordinates for the first ship it says I hit it like it shoul.
Thanks for the help you can provide :)
Couple of things:
Line 81
You can't have two subsequent return statements. The first one will exit the function. If you want to return two sets of coordinates return a nested list:
return [[x1, y1], [x2, y2]]
Line 161
Then use unpacking to get these:
p1ship1, p1ship2 = inputCoords("1")
p2ship1, p2ship2 = inputCoords("2")
Line 171/176
Make sure the two ships you're passing in are different (currently they're the same):
hit = haveShot("1", player2Ship, player2Ship, player1Board)
to
hit = haveShot("1", p2ship1, p2ship2, player1Board)
Line 170
The while hit == False condition means that the game will exit as soon as player 1's ship is hit. Use another variable to check if the game is over, such as:
while player1ShipCount > 0 and player2ShipCount > 0:
#play game
And keep track of each players' available ships.
I don't have enough reputation to comment, or I would, but...
You haven't defined "lol", you have defined "lolX" and "lolY", which are separate variables.
If you want to define a list or a dictionary with values inside, you cannot just write lolX or lolY, you would have to do (I use a dictionary here since it seems to be what you want):
lol = {}
lol[X]=eg.passwordbox("Player " + str(playerNumber) + " input the x co-ordinate for your SECOND ship ")
Then you can access the value in lol by lol[X].
You have defined separate variables, rather than define a specific value of that variable.

Categories

Resources