0

So I am trying to write a board typeish "game" in python. So I have a function place_piece that places a piece at a row and column and then I have another function that checks if a row and column is free or not. It works but if I try to place 2 pieces the second piece overrides the first piece so I can only place one piece at a time. I want to be able to place an unlimited amount of pieces without them overriding each other.

Here's my code: I say that board = new_board() in the beginning before running the functions

def new_board():
    board = {}
    return board


def is_free(board, x, y):
    x = x
    y = y
    if board["x"] == x and board["y"] == y:
        return False
    else:
        return True


def place_piece(board, x, y, player):
    board["x"] = x
    board["y"] = y
    board["player"] = player
    return True

So basically I want to to be able to say place_piece(board,100,200,"player1") and place_piece(board,300,400,"player1") and then I want to check if these places are free with is_free(board,100,200) and is_free(board,100,200) and I want both of them to return False as they aren't free.

Can I somehow save each dictionary in a list or something?

glibdud
  • 7,550
  • 4
  • 27
  • 37
Lss
  • 65
  • 1
  • 7
  • 1
    If you're second guessing your data structure, you're not using the right one. Ditch the dict. – cs95 Sep 11 '17 at 12:42
  • The dupe addresses your question, but you're probably doing this wrong. You should use a set for lookup, or have your dictionary store tuples as the key. – cs95 Sep 11 '17 at 12:45
  • you can save anything in a list, list.append(dict) – almost a beginner Sep 11 '17 at 12:47
  • if you use x,y for each position on the board, you can use a list of lists, instead of dictionaries – Tushar Aggarwal Sep 11 '17 at 12:47
  • @cᴏʟᴅsᴘᴇᴇᴅ I don't quite understand how to save the keys as tuples. I tried making board["x"] to board[("x")] but it made no difference. – Lss Sep 11 '17 at 16:36
  • Yeah, that's not going to do it, and that's not how the duplicate does it either. – cs95 Sep 11 '17 at 18:09

0 Answers0