mercredi 11 novembre 2015

change de value of a variable when in a function python

I try to make a Battleship game, my code was working so far. My problem happen when I try to place my second ship with this function.

def placing_Battleship_p1(self):
    bo1=str.lower(input('orientation: '))
    bx1=0
    bx1=int(input('x: '))
    by1=0
    by1=int(input('y: '))
    if (((bx1+4)>11 or (bx1)<1) and bo1=='h') or ((((by1+4)>11 or by1<1) and bo1=='v')):
        print('Out of your map, chose another position')
        self.placing_Battleship_p1()
    else:
        if bo1=='h':
            for i in range(4):
                if self[by1,bx1+i]=='A':
                    print('There is already a ship here')
                    self.placing_Battleship_p1()
                else:
                    self[by1,bx1+i]='B'
        elif bo1=='v':
            for i in range(4):
                if self[by1+i,bx1]=='A':
                    print('There is already a ship here')
                    self.placing_Battleship_p1()
                else:
                    self[by1+i,bx1]='B'
        else:
            print('Invalid orientation, chose v for vertical of h for horizontal')
            self.placing_Battleship_p1()

Note that the code itself is working ( since I can place my first boat ) My problem happen in the loop that verify if there is alredy another boat.

 if bo1=='h':
            for i in range(4):
                if self[by1,bx1+i]=='A':
                    print('There is already a ship here')
                    self.placing_Battleship_p1()
                else:
                    self[by1,bx1+i]='B'
        elif bo1=='v':
            for i in range(4):
                if self[by1+i,bx1]=='A':
                    print('There is already a ship here')
                    self.placing_Battleship_p1()
                else:
                    self[by1+i,bx1]='B'

where the string 'A' represent the Aircraft carrier ( the first ship ) and 'B' is the Battleship ( second ship ) If I run the code, and make sure that the second boat touch the first one, it prints 'There is already a ship here' which is what I want.but when it run the code again, it stays in the loop and whatever is the given position, it will print 'There is already a ship here' even if there is no ship.

Aucun commentaire:

Enregistrer un commentaire