2

So for context: I'm trying to create a simple chess program in python with pygame (2.0.0). Since I don't want to create every single of the 64 tiles manually I am looking for a way to create them using a function. Since in chess tiles are named from a1 to h8 (files and ranks) I want the objects to have this kind of names (a1, a2,...). The tile-class is until now very simple:

class tile: 

    def __init__(self):
        self.piece = None

Then I made two lists: one for the files and one for the ranks. Then two for-loops (one in another) so that for every single combination it would create a tile-object:

files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
ranks = ['1', '2', '3', '4', '5', '6', '7', '8']

for f in files:
    for r in ranks:
        f + r = tile()

Now my problem: python doesn't allow this ;( I want to create 64 tile-objects with names from a1 to h8. Is there any way for this?

Einliterflasche
  • 473
  • 6
  • 18

2 Answers2

1

While it is technically possible, I would heavily advise against manipulating variable scopes dynamically. The "intended" way of doing this is using a dictionary:

files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
ranks = ['1', '2', '3', '4', '5', '6', '7', '8']

tiles = {}

for f in files:
    for r in ranks:
        tiles[f + r] = tile()

You can then access e.g. tile E4 through tiles["e4"].

L3viathan
  • 26,748
  • 2
  • 58
  • 81
1

It would make sense to store these tiles in a dict:

files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
ranks = ['1', '2', '3', '4', '5', '6', '7', '8']
tiles = {f'{file}{rank}': tile() for file in files for rank in ranks}

Another way would be to create a Chessboard class:

class Chessboard:
    def __init__(self, files, ranks):
        for file in files:
            for rank in ranks:
                setattr(self, f'{file}{rank}', tile())
                
                
chessboard = Chessboard(files, ranks)
mapf
  • 1,906
  • 1
  • 14
  • 40
  • Can you please explain how the second part works? I don't get how setattr() works with (self, '{file}{rank}', tile()). Also: what does '{file}{rank}' do? – Einliterflasche Dec 22 '20 at 18:55
  • Well it does what its name implies. It sets attributes. In this case the attributes of the `Chessboard` class by the names of `f'{file}{rank}'` to the values of `tile()`. – mapf Dec 22 '20 at 19:23
  • does that mean that f'{file}{rank}' becomes an object of the tile-class? if so how is it possible inside of an object like chessboardß is the new object only accessable in the chessboard class? And what does f'' do? – Einliterflasche Dec 22 '20 at 19:31
  • I would recommnd you just try it out and see what happens. It's the best way to understand stuff. Also if there are general concepts you are not familiar with or don't understand, just look them up. It's easy to do so and you will find much better and more elaborate explanations. – mapf Dec 22 '20 at 19:51