python: Chess moves validation - python

Does anybody know if there is a free python chess moves validation function available somewhere?
What I need. I have a diagram stored as a string, and move candidate. What I need is to see if move candidate is valid for the diagram.
Would be really interested to see examples, if possible.
The string looks this way:
ememememememememememememememememememembbememwpemememememememwpemembkememememememememememememememememwbembrememememwkemememememem
I understand it may seem stupid, but I find it the easiest to encode position this way. Move candidate for me is just another such position (which happened after next move, can change this behavior I think)

You are missing information e.g. whose turn to move, whether each king has ever moved (means castling is not allowed), the "en passant" status of each pawn. That aside, it would be a very instructive exercise for you to write your own, using a not-very-complicated board representation like the 10x12-element array described here (except that you'd linearise it to a 120-element array).

I know this is a rather old question, but my brother and me were looking for the same thing and we came across this awesome little python module called Chessnut.
Here is an example of its use:
#!/usr/bin/python
from Chessnut import Game
chessgame = Game(fen="rnbq1rk1/ppppp1bp/5np1/5p2/2PP4/2NBPN2/PP3PPP/R1BQK2R b KQ - 4 6")
print chessgame
print chessgame.get_moves()
# apply a move
chessgame.apply_move(chessgame.get_moves()[1])
print chessgame
and here the generated output:
rnbq1rk1/ppppp1bp/5np1/5p2/2PP4/2NBPN2/PP3PPP/R1BQK2R b KQ - 4 6
['b8a6', 'b8c6', 'd8e8', 'f8e8', 'f8f7', 'g8h8', 'g8f7', 'a7a6', 'a7a5', 'b7b6', 'b7b5', 'c7c6', 'c7c5', 'd7d6', 'd7d5', 'e7e6', 'e7e5', 'g7h8', 'g7h6', 'h7h6', 'h7h5', 'f6e8', 'f6d5', 'f6e4', 'f6g4', 'f6h5', 'g6g5', 'f5f4']
r1bq1rk1/ppppp1bp/2n2np1/5p2/2PP4/2NBPN2/PP3PPP/R1BQK2R w KQ - 5 7
Awesome! :)
Thanks cgearhart!

Just use the source of one of the Python Chess programs like PyChess or Python Chess
Specifically, the valid moves for pychess: https://code.google.com/p/pychess/source/browse/lib/pychess/Utils/lutils/validator.py

Wouldn't hurt to look at some of the related answers on the side: Chess move validation library and https://stackoverflow.com/questions/1239913/smallest-chess-playing-program stand out to me.
Though personally I'm in favor of building your own.

Check out ChessBoard.
Unfortunately it has some drawbacks:
it seems to be abandoned, because the bugs reported more than one year ago in the comments don't seem to be fixed
the code is not really PEP-8 compliant
some methods are very ugly and big, not all methods have docstrings
there are no unit tests, so digging into that code might be a challenge (I've already tried it at least twice and failed)
The good thing is that the code is GPL so you can play with it as long as you stick to that license.

I've made a simple chess implementation with move validation here: https://github.com/akulakov/pychess
Validation logic is in each piece's "moves()" method, and you can validate your own move by generating full list of moves and checking if your move is there.

Related

What does 'arg1 must be a string, bytes or code object' mean? exec()

an image of the error message for anyone interested
trying to make a simple version of a language translator to a language I made that is similar to one from Outer wilds. but when I try to execute one of the letters for turtle to draw it says as the image above or
arg1 must be a string, bytes or code object
As I am not an amazing coder, I have no clue what that means.
This is the code that I have written and I want to exec()
There is another image containing the code I want to exec()
if anyone can tell me how to solve this thanks! and if you are able to use more simple python and dumb the answer down an little bit so I can understand then that would also be massively helpful!
if you can't dumb it down for me, no problem!
a = T.fd(20)
b = T.fd(20); T.rt(60); T.fd(20)
Neither of those statements does what you think they do. The first statement calls the fd function immediately (presumably moving the turtle forward by 20), and returns None, so None will be stored in a.
The second line also does a forward 20 and stores that return value in b. It then does a right 60 and a forward 20, but nothing about those will be stored in b. Those are completely separate statements.
The bottom line is, if you want to store up a macro to be executed later with exec, then those lines MUST BE STRINGS. You don't have any strings. So, change your code to:
a = "T.fd(20)"
b = "T.fd(20); T.rt(60); T.fd(20)"
...etc...
Then it will do what you want. This is not the BEST way to do this, because exec is a bad habit, but it will do what you want. The better way would be to do something like:
a = "F20"
b = "F20,R60,F20"
and then write a little interpreter to convert those to turtle movements.

grounding predicates with python scripts in asp/clingo

I am using clingo version 4 and wish to be able to ground relations via python script (please don't ask why, it's not a crime, since you can at least ground 1-ary relations). I am hoping this is possible, and need some help.
#script (python)
import gringo;
def main(prg):
prg.ground([('base', [])]);
# ... compute somethings ...
prg.ground([('myrel', [[10,20],[30,40],[70,40]])]);
prg.solve();
#end.
#program myrel(x,y).
r(x,y).
#show r/2.
this doesn't work. Does anyone know how to do this? I tried [(10,20),(30,40),(70,40)] instead, but that also did not work.
It is possible, but one has to input each entry one by one (which for my application is actually good). Instead of
prg.ground([('myrel', [[10,20],[30,40],[70,40]])]);
one has to write
prg.ground([('myrel', [10,20])]);
prg.ground([('myrel', [30,40])]);
prg.ground([('myrel', [70,40])]);
and then it is accepted and yields the right output.

"Re-declared Defined Without Usage" One Script but Not The Other?

This sounds like it should be blindingly obvious but there's something quirky going on.
So I have two scripts. Largely the same but a few variances here and there. They both run big loops and they both use global variables. Yes, I know this is bad. Tidying it up is on my to do list but I'm on a time constraint at the moment.
One script works fine. As expected.
The other works fine... for the most part. Then it bugs out once it iterates through the loop again. It's very strange because the code has very little differences but I did pick up on something which I can't explain.
The variable I use to track my position in the loop is set like this in script 1 (which works flawlessly):
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
The second script has:
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
However in the second script PyCharm highlights the = -1 part as
Redclared'CurrentMatchScan' defined above without usage
So the obvious assumption is something further up in the code is using it. I do call a function later on which is placed up there...
def LoadMatch():
nextbox1 = LinkList[CurrentMatchScan + 1]
nextbox2 = LinkList[CurrentMatchScan + 2]
But this is only called once CurrentMatchScan is set... and the first script has the exact same code.
Is my IDE just not noticing it on the other script or something? There's a pretty big issue with the looping on the second one and this is the only difference I can see between the two.
I know this doesn't look like a lot to go on but there's not much else to it that I can see. It's barely actually referenced.
I'd really appreciate anyone who can point out how much of an idiot I'm being and missing something really simple.
/edit:
Based on the fact that it does use CurrentMatchScan and calls LoadMatch() for the first iterations properly I'm starting to doubt this is anything but PyCharm trying to warn me I'm potentially doing something silly.
I think if this was the issue it wouldn't work at all so the warning might be a bit of a red herring when it comes to the issue I'm actually facing.

Why can't I get the output in Python?

def travel():
travel.s=0
travel.frate=[]
travel.tr=[]
def accomodation():
print"""specialises
1.place 1
a.hotel 1
b.hotel 2
Hotel1:ac/non ac rooms
Ac.for ac...
Noac.for non ac...."""
hd=[5000,6000]
hg=[4000,7000]
TAc=[1000]
Nac=[400]
ch5=input("Enter your choice")
fav=raw_input("ENter hotel choice")
mode=raw_input("Enter ac/no ac")
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
else:
frate=hd[i]+Nac
if(ch5==2):
for i in range(0,2,1):
frate=hg[i]+TAc
else:
frate=hg[i]+Nac
accomodation()
travel()
When i run the program , i get the error as List Index out of range.but in hd and hg list,there are only two elements, so index number will be from 0 right?? Is there anything i should import?? I even gave statements like this:
travel.frate=travel.hg[i]+TAc
but it still doesn't come.Thank you for your effort.
the indentation is proper now,but the output is still not coming.
The specific issue you are encountering is caused by these lines here:
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
hd[i] looks at hd[5000] and hd[6000] which will throw an IndexError.
But if you fix that, you're going to run into another error, because
frate=hd[i]+TAc
tries to add a list TAc to an integer hd[i], which is an unsupported operation. You probably need frate=hd[i]+TAc[0], or even better, make TAc a number rather than a list. This issue occurs elsewhere in your code as well.
Finally, while not causing explicit issues in your code right now, there are two other problems:
ch5=input("Enter your choice") is dangerous since input tells Python to run whatever code snippet the user enters. In this case, much safer to do ch5=int(raw_input("Enter your choice"))
for i in range(0,2,1): is really for i in range(2): - only use the starting index and jump parameters if you need to change them from their default, namely 0 and 1.
There are other issues like variable scope (you're expecting travel.frate to be modified from within accommodation, but that's not happening) and defining variables in functions like travel.frate (not invalid syntax, but definitely strange) but those are probably better addressed outside of this question.

terrain gen python constraints

in my free time I'm making a text-based/ascii(for now) rogue-like game as a study(relevant because context for question)
At the moment, I'm trying to generate the terrain/the rooms that will be used in the world.
The world should be 'endless'.
Generating random terrain isn't the big issue.
I'm struggling with finding a way to maintainably add constraints like:
'plains can not be next to mountain'
I could build a big decisiontree, however, this would mean an if currentTile == plain: if not next to mountain and an if currentTile == mountain: if not text to plains.
this not maintainable, since every rule has to be implemented on 2 places.
I'm wondering what standard solutions for this type of issues exist?
Greetings
I'm not entirely sure I follow your example excerpt but you could have a list of 2 element sets, each containing disallowed combinations. Then you could look up
disallowed = [set(plain, mountains)]
if set(currentTile, newTile) not in disallowed:
#rest of code

Categories

Resources