My Python Chess board data-structure needs some pointers, help

Hi
I'm whipping up this quick chessBoard data structure in Python, but I think my C/Java habits are tripping me somehow.
The objects aren't linking up correctly,and are giving a roll of errors : I have a chessGame class to contain the chessBoard.
I'll do the chessPiece class once this works.
It should be simple

Here is the big chessGame class: That now, just creates the chessboard, and has the main code
import chessBoard

class chessGame:
    def __init__(self):
        print("\n\n.........")
        c=chessBoard()


print('chess main')

chessGame()

Open in new window


Here is the chessBoard:
class chessBoard:

    def __init__(self):

        self.pieces=[]

        #white pawns
        for i in range(0,9):
            print(i)

Open in new window


There are missing lines, but once this simple structure works, I'll be set

Where am I going wrong?

Thanks
LVL 1
beavoidAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gelonidaCommented:
Yes if coming from Java, C#, C++ it's very easy to forget, that python is more explicit.

So don't forget 'self'

Here a very basic example:


class chessGame:
    def __init__(self):
        print("\n\n.........")
        self.board = chessBoard()
        
class chessBoard:
    def __init__(self):
        # create an 8 x 8 array
        self.fields = [ ([ None ] * 8) for cnt in range(8) ]
        for x in range(8):
            self.field[x][1] = 'whitepawn'
            self.field[x][6] = 'blackpawn'

Open in new window

0
beavoidAuthor Commented:
Thanks, but I still get the same error:

   self.board = chessBoard()
TypeError: 'module' object is not callable

Open in new window


with the following 2 files:

chessGame.py
import chessBoard

class chessGame:
    def __init__(self):
        print("\n\n.........")
        self.board = chessBoard()


print('chess main')

chessGame()

Open in new window


chessBoard.py . . .
class chessBoard:
    def __init__(self):
        # create an 8 x 8 array
        self.squares = [ ([ None ] * 8) for cnt in range(8) ]
        for x in range(8):
            self.squares[x][1] = 'whitepawn'
            self.squares[x][6] = 'blackpawn'

Open in new window


What am I missing?
Thanks
0
Florian LenschowCommented:
I'm not sure about this, but if you change "import chessBoard" to "from chessBoard import chessBoard" that could fix the 'module' not callable error, because your module and class have the same name.
1
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

ambienceCommented:
Neither Java nor C++ encourages camel case class-names, chessBoard for example. Also, module names are generally c-style all lowercase.

self.board = chessBoard.chessBoard()

Open in new window


should work. The reason is that you are importing the module chessboard and not the class from that module. Another way is the "from ... import ..." which brings it into the current modules scope (not recommended though - leads to namespace pollution).
0
gelonidaCommented:
In your initial example you did not show that the chessboard class was in a different file.

As others pointed out: The recommendation for coding style (upper/lower case handling) is very different in Python than in other languages.

Your file should be called chess_board.py (or chessboard.py)  which means lower case only and word separation with underscores.

Your class should be called

ChessBoard. (Every word beginning uppercase, the rest lowercase) If you stick with this coding style it is much more obvious where you make  a mistake, as you would have posted, that

self.board = chess_board()

Open in new window

does not work, as you try to instantiate a module or a variable instead of a class.

so either do

import chess_board

. . . 
        self.board = chess_board.ChessBoard()

Open in new window


or

from chess_board import ChessBoard
. . . 
        self.board = ChessBoard()

Open in new window


Coding style is not compulsory, it is simply a recommendation.

But the more you work with other developers the more you see why it is helpful to have a common coding style.
You can read others' and your own code much faster.

You might have a look at PEP-8 https://www.python.org/dev/peps/pep-0008/
0
beavoidAuthor Commented:
Thanks
It is compiling now, didn't think of the identical data member names, silly me. Is confirmation of the class to which a constructor belongs generally always crucial?

Based on the data structure I have, I can't write a printBoard() function to keep printing rows on one line
It can print characters per line only. Must I do a loop inside the print()  to do 8 ?
Can I modify print not to do an end-line after each print?

what might a complete printBoard loop look like to print characters in an 8x8 array across from board files 0->7 down with ranks 0->7
I'll change the appropriate squares to 'R' 'N' 'B' 'Q' 'K' 'B' 'N' 'R'
White will be uppercase and black lower
Is there an initialize array ability like this?
self.board[0]='R' 'N' 'B' 'Q' 'K' 'B' 'N' 'R'
self.board[7]='r' 'n' 'b' 'q' 'k' 'b' 'n' 'r'

Or I could make the board be 8 strings of 8 characters?
?  thx
0
ambienceCommented:
self.board[0]='R' 'N' 'B' 'Q' 'K' 'B' 'N' 'R'

can be

self.board[0]=['R','N', 'B', 'Q', 'K' ,'B' ,'N' ,'R']

Ultimately, you'd want to parse this from an FEN string. Here a list has been assigned to board[0]. List is mutable, which means you can change its contents later (as moves are made).

Given this, printing a row can be

print( " ".join(self.board[0]) )
0
beavoidAuthor Commented:
Awesome, I just have to finalize my ABC
0
beavoidAuthor Commented:
Hi,

This is what I have now, attached. It was working fine, until I suddenly got the old
error:

from Object import ChessPlayer
ModuleNotFoundError: No module named 'Object'

Open in new window

What makes this happen? Do I have too many modules?
Big Thanks

chess_board.py
chess_game.py
chess_piece.py
ChessMove.py
0
gelonidaCommented:
Things like that happen often if you do refactoring.
(Try to restructure your code / rename a file, move a class from one file to another)
Refactoring is a very good idea to keep the code clean and understandable. but occasionally one might forget to rename in one place.

You don't have any file named Object.py.

and this is what python is looking for if you write.

from Object import ChessPlayer

Open in new window


It looks for the file Object.py which should declare an object (in your case probably a class) named "ChessPlayer"
1
beavoidAuthor Commented:
Hi

I've noticed, with all this talk about an object keyword, none of my classes are defined Class_name(object)

This must be causing serious grief, I imagine. I have never heard of object.py
What does it look like?

Looking at them all, they all could be (object):

?
Thanks
0
gelonidaCommented:
class MyClass(object) 

Open in new window

was required in Python2 in order to enforce the new style classes, which had minor differences to the old style classes.

In Pytho 3 the old style classes have been abolished and
class MyClass(object)

Open in new window

and
class MyClass 

Open in new window

or now identical

So for Python3 there is no more need to subclass from object.
If your code should run on Python2 it's better to still subclass from object.
1
beavoidAuthor Commented:
Hi
I have been so put out by all the mistakes I have made above,
that I restarted! using a list array for the board DS, lists are mutable.
I hope this looks good...
class ChessBoard:
    def __init__(self):

        self.board = [[' ',' ',' ',' ',' ',' ',' ',' '] for i in range(8)]


        self.board[0] = ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
        self.board[1] = ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P']
        self.board[7] = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']
        self.board[6] = ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p']


    def print(self):

        for i in range(7,-1,-1):
            print(i, '>', self.board[i])


print('main')

c=ChessBoard()

c.print()

Open in new window

Thanks
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gelonidaCommented:
Looks good to me.

You might use something like
print(i, '>', ' '.join(self.board[i]))

Open in new window

for a more compact print out with out the commas and the single quotes
1
beavoidAuthor Commented:
Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Game Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.