PythonGirl
PythonGirl

Reputation: 15

Merging two similar code pieces together in Python

I am quite new to python, and have a problem with a code I am currently working on. As you can see in the bit of my code below, it is basically identical to each other, the only thing that separates the two is the player/opponentTile, I would like to merge these two together but I don't exactly know how. Any advice is appreciated! ( I cannot only put if self.legalMove(playerTile, opponentTile, x, y) == False:).

And I would also not like having both self, playerTile, opponentTile in the def ....Move considering I want to call onto the definition in the code only using for example: playerMove(playerTile) (And if I do that a ValueError pop up)

def playerMove(self,playerTile):
    if self.legalMove(playerTile, x, y) == False:
        continue
    else:
        break

def opponentMove(self,opponentTile):
    if self.legalMove(opponentTile, x, y) == False:
        continue
    else:
        break

Upvotes: 0

Views: 94

Answers (2)

martin
martin

Reputation: 736

If it is the same you only have to pass the entity you want to move

def entity_move(self,entity_tile): 
    possibilities = '0 1 2 3 4 5 6 7 8 9'.split()
    while True:
        move = input().lower()
        if len(move) == 2 and move[0] in possibilities and move[1] in possibilities:
            x = int(move[0])
            y = int(move[1])
            if self.legalMove(entity_tile, x, y) == False:
                continue
            else:
                break
        else:
            print('Not a valid input!')

Upvotes: 2

MrPromethee
MrPromethee

Reputation: 719

These methods seem to be exactly the same. You only need one.

Rename it to:

def move(self, tile)

and you can use it in both cases.

Upvotes: 3

Related Questions