Issue with python skipping code in simple chess program - python

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()

Related

Trying to figure out how to properly save and load a game in a save.p file using Pickle module

Problem
My problem consists of me trying to save the position of the player on the board that I created and then loading it when they enter a specified SENTINEL value. Though the problem that I am getting at this current time is referencing something before the assignment.
This is how I think I should be loading the game.
What I've Tried
I've tried defining the values that are said not to be defined or referenced after the assignment earlier, though it ended up still giving me the same error and in the end didn't make sense to me. I've looked up a lot of different problems relating to this but didn't quite get the grasp on it due to terminology and getting to overwhelmed. Hence why I came here to get a straightforward explanation for my exact problem.
Code
Save Game
def SaveGame(player, board):
playerData = {}
playerData['player'] = player
playerData['board'] = board
saveGame = open("Save.p","wb")
pickle.dump(playerData, saveGame)
saveGame.close()
Load Game (where I'm having trouble)
def LoadGame():
player, board = pickle.load(open("Save.p","rb"))
return player, board
Commanding Player (using the save game function)
def CommandPlayer(player,board):
VALID_INPUTS = ["W","A","S","D","Q"]
row = player["row"]
col = player["col"]
while True: # Input validation loop.
userInput = input("Enter a direction (W)(A)(S)(D) to move in or (Q) to quit.): ").upper()
if userInput in VALID_INPUTS:
break
if userInput == "Q":
SaveGame(player, board)
Main.py (where I'm having trouble with the loading)
def Main():
userinput = input("Welcome to the Character Creator 2000, Enter G to generate your Character and stats or Enter (L) to load a Game (0) to Quit: ").upper() #Requests User Input
if userinput == ("L"):
LoadGame()
player, board = CommandPlayer(player, board)
os.system('cls')
ShowBoard(board)
You're not loading the game data back properly. Your SaveGame) function is saving a dictionary, so that is what pickle.load() will return in LoadGame().
Here's the right way of doing it:
def LoadGame():
with open("Save.p", "rb") as pkl_file:
playerData = pickle.load(pkl_file)
player = playerData['player']
board = playerData['board']
return player, board
LoadGame()
player, board = CommandPlayer(player, board)
You have player, board = ... in the wrong place. It should be one line up:
player, board = LoadGame()
CommandPlayer(player, board)

Zelle-graphics window — Cloning object instead of moving

I'm making a simulation of a traffic light and a car. When the light turns green, the car should move. (I'm aware that actual stoplights don't jump from green to red, or from red to yellow, but...just go with it). The program takes input from the user as to how long the stoplight should loop; it starts by remaining red for 3 seconds and then looping through the other colors.
So my problem is that when I try to move the car (represented by a Rectangle object here) and wheels (two Circle objects), the graphics window appears to be creating an entirely new rectangle, despite the fact that I haven't called the clone() method or anything anywhere in my program. Try running the program for 8+ seconds to see.
Why is the car rectangle making copies of itself instead of just moving the original?
Code below:
import sys
from graphics import *
import time
def drawCar(win):
car = Rectangle(Point(0,510), Point(100,555))
car.setFill(color_rgb(255,0,0))
wheel1 = Circle(Point(15,565),10)
wheel2 = Circle(Point(75,565),10)
wheel1.setFill(color_rgb(0,0,0))
wheel2.setFill(color_rgb(0,0,0))
car.draw(win)
wheel1.draw(win)
wheel2.draw(win)
def drawTrack(win):
rect = Rectangle(Point(0,575),Point(500,600))
rect.setFill(color_rgb(0,0,0))
rect.draw(win)
drawCar(win)
def loop(x):
# opens and titles a graphics window
win = GraphWin("Traffic Light", 500,600)
# creates 3 black circles for the window
red = Circle(Point(250,100),80)
yellow = Circle(Point(250,260),80)
green = Circle(Point(250,420),80)
# draw the car and track
drawTrack(win)
corner1 = Point(0,510)
corner2 = Point(100,555)
car = Rectangle(corner1,corner2)
car.setFill(color_rgb(255,0,0))
wheel1 = Circle(Point(15,565),10)
wheel2 = Circle(Point(75,565),10)
wheel1.setFill(color_rgb(0,0,0))
wheel2.setFill(color_rgb(0,0,0))
car.draw(win)
wheel1.draw(win)
wheel2.draw(win)
# sets default colors of the circles
red.setFill(color_rgb(255,0,0))
yellow.setFill(color_rgb(0,0,0))
green.setFill(color_rgb(0,0,0))
red.draw(win)
yellow.draw(win)
green.draw(win)
redCount = 1 # red light counter is automatically set to 1 because it starts with red by default
yelCount = 0 # yellow and green light counters are set to 0
greenCount = 0
redSet = True
yellowSet = False
greenSet = False
start = time.time()
end = time.time() + x
time.sleep(2) # wait 2 seconds while showing the red light (since the loop waits 1 additional second on the red), then begin the color-changing
while (time.time() - start < end):
if(time.time() + 1 > end): # if the time it will take to rest on the next light will make it go overtime
break # then stop
if redSet:
print("Red, changing to yellow")
red.setFill(color_rgb(0,0,0))
yellow.setFill(color_rgb(255,255,0))
yelCount += 1
redSet = False
yellowSet = True
time.sleep(1) # hold the yellow light for 1 second
elif yellowSet:
yellow.setFill(color_rgb(0,0,0))
green.setFill(color_rgb(0,255,0))
greenCount += 1
yellowSet = False
greenSet = True
time.sleep(1) # hold green light for 1 second
#corner1.move(60,0)
#corner2.move(60,0)
car.move(60,0)
wheel1.move(60,0)
wheel2.move(60,0)
print("Corners moved")
elif greenSet:
green.setFill(color_rgb(0,0,0))
red.setFill(color_rgb(255,0,0))
greenSet = False
redSet = True
time.sleep(1)
redCount += 1
else:
break
print("Red light hit ", redCount)
print("Yellow light hit ", yelCount)
print("Green light hit ", greenCount)
# if the user clicks anywhere in the window
win.getMouse()
# then we close the window
win.close()
def main():
# prompts the user for a time limit
x = float(input("How many seconds do you want the traffic light simulation to last? "))
# prints confirmation
print("Starting the loop for ", x, " seconds:")
# begins the loop
loop(x)
main()
The problem is because you're drawing the car (and wheels) twice.
Fortunately the fix to prevent that is simple:
def drawTrack(win):
rect = Rectangle(Point(0,575),Point(500,600))
rect.setFill(color_rgb(0,0,0))
rect.draw(win)
# drawCar(win) # Don't do this.
Note: After doing this, there will be no calls at all the function drawCar() so you could remove it. Another alternative would be to leave it in and replace the lines of code in the initialization part of the loop() function that do the same thing with a call to it (thereby making the code more modular).

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 turtle crashes with loop

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

python -- Crash when trying to deal with unexpected input

So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)

Categories

Resources