python中的战舰游戏,用于学校的一个项目

时间:2019-04-19 09:50:08

标签: python

我是编程的初学者,我想用python 3.6为我的学校项目构建一个军舰游戏,我有一些错误,但是我不知道如何解决。如果您尝试运行我的代码,请运行它直到出现错误为止,因为有时没有问题。我曾经在placer_bateau_verticalement函数中弹出超出范围的错误,并且列表索引超出范围的错误。这是我的代码:

编辑4:带有伪代码的python代码

"""//----------------library----------------\\"""
import random



"""//----------------variables----------------\\"""

gridPlayerA = [0] * 100 #IA's grid
gridPlayerB = [0] * 100 #Player's grid


gridGamePlayerA = [0] * 100 # just create a copy of the IA boards and only show the empty board



OnGame = True # turn on the game

PrevPlayerShoots = []
PrevIAShoots = []





"""//----------------functions----------------\\"""

def main():

    BoatTouchedByPlayer = 0
    BoatTouchedByIA = 0


    put_boats(gridPlayerA)#put IA's boats randomly
    put_boats(gridPlayerB)#put Player's boats randomly (temporarily)

    while OnGame == True: #while we're in the game


        print(gridGamePlayerA) # print the IA's grid (with no boats)


        PlayerShoot = input("It's your turn, where do you want to shoot ? (give the coords like this : A,1) ")
        PlayerShoot.split(",") #Split the coords
        Lettre = PlayerShoot[0] # take the lettre
        Number = int(PlayerShoot[2]) # take the number, convert into an integer

        Player_Shoot = int(ord(Lettre)) - 65 + 10*(Number - 1) # transform the lettre and the number into a number coord


        if can_shoot(PrevPlayerShoots, Player_Shoot) == True: #if we can shoot



            if gridPlayerA[Player_Shoot] == 1: # if we touch a boat in the IA's board
                shoot_Touched(gridGamePlayerA, Player_Shoot) # call the shoot function that replace the coord by an F on the empty board
                print("touched")
                BoatTouchedByPlayer = BoatTouchedByPlayer + 1# count until 14 (number of boat "parts")
                End_Game("Player") # check if the player won


            else:
                shoot(gridGamePlayerA, Player_Shoot)# show the shot next time to remind the player where he has shoot
                print("missed, IA's turn : ")
                IA_shot = random.randint(0, 99) # make the IA shot randomly 
                if gridPlayerB[IA_shot] == 1:# if IA touch a boat in the player's board
                    print("IA touched one of your boat")
                    shoot_Touched(gridPlayerB, IA_shot) # call the shoot function that replace the coord by an F
                    print(gridPlayerB) # print the player's board
                    BoatTouchedByIA = BoatTouchedByIA + 1 # count until 14 (number of boat "parts")
                    End_Game("IA") # check if the IA won

                else:
                    shoot(gridPlayerB, IA_shot) # replace the shoot by an X
                    print("Lucky, IA missed !")




def shoot_Touched(grid, shot):
    grid.pop(shot)
    grid.insert(shot, 'F')


def shoot(grid, shot):
    grid.pop(shot)
    grid.insert(shot, 'X')



def End_Game(grid):
    if grid == "IA":
        if grid == 14: # if IA has touched all the player's boat
            OnGame = False #turn off the game
            print("Too bad, IA has won !")

    elif grid == "Player":    
        if grid == 14:
            OnGame = False #turn off the game
            print("Wow, you have won !")



def can_shoot(List, shot):
    for x in range(len(List)):#check if the shoot didn't already done
        if List[x] == shot:
            print("you've already shoot here !")
            return False
    List.append(shot)        
    return True


def put_boats(grid):
    for n in range(2,6):
        x, y, direction = random.randint(0,9), random.randint(0,9), random.randint(0,1)
        while cant_put_boat(n, x, y, direction, grid):
            x, y, direction = random.randint(0,9), random.randint(0,9), random.randint(0,1)
        put_boat(n, x, y, direction, grid)



def put_boat(length, x, y, direction, grid):
    if direction == 0: # HORIZ direction
        for i in range(length):
            position = x + 10*y
            grid.pop(position)
            grid.insert(position, 1)
            position = position + 1

    if direction == 1: # VERT direction
        for i in range(length):
            position = x + 10*y
            grid.pop(position)
            grid.insert(position, 1)
            position = position + 10

def cant_put_boat(length, x, y, direction, grid):
    return direction == 0 and x + length >= 10 or direction == 1 and y + length >= 10





"""//----------------main code----------------\\"""


main()#simply run the main function

编辑3:伪代码有效吗?

def main():
    grid = []
    put_boats(grid)
    for _ in range(100):
        play(grid)
    print(grid)

def put_boats(grid):
    for b in range(2,6):
        x, y, direction = 4, 5, 0
        while cant_put_boat(b, x, y, direction, grid):
            x, y, direction = 0, 0, 0
        put_boat(b, x, y, direction, grid)

def cant_put_boat(b, x, y, direction, grid):
    # you don't need to test every position
    return direction == 0 and x + b >= 10 or direction == 1 and y + b >= 10

def put_boat(b, x, y, direction, grid):
    if direction == 0:
        for i in range(b):
            position = x + 10*y
            grid.append(position)
            position = position + 1

    if direction == 1:
        for k in range(b):
            position = x + 10*y
            grid.append(position)
            position = position + 10 

def play(grid):
    x, y = 5, 5
    while can_shoot(x, y) == False: #
        x, y = 1, 5
    shoot(grid, x + y)

def can_shoot(grid, shot):
    prev_shoots = []
    for j in range(len(prev_shoots)):
        if shot == prev_shoots[j]:
            return False
    return True

def shoot(grid, shot):
    grid.pop(shot)
    grid.insert(shot, 'X')



main()

编辑2:伪代码:

def main():
    grid = init_grid()
    put_boats(grid)
    for _ in range(100):
        play(grid)

def put_boats(grid):
    for b in range(2,6):
        x, y, dir = random
        while cant_put_boat(b, x, y, dir):
            x, y, dir = random
        put_boat(b, x, y, dir, grid)

def cant_put_boat(b, x, y, dir, grid):
    # you don't need to test every position
    return dir == HORIZ and x + b >= 10
        or dir == VERT and y + b >= 10

def put_boat(b, x, y, dir, grid):
    if dir == HORIZ:
        for i in range(b):
            position = x + 10*y
            grid.append[position]
            position = position + 1

    if dir == VERT:
        for k in range(b):
            position = x + 10*y
            grid.append[position]
            position = position + 10 

def play(grid):
    x, y = random
    while cant_shoot(grid, x, y)
        x, y = random
    shoot(x, y)

def can_shoot(grid, shot):
    prev_shoots = []
    for j in range(len(prev_shoots)):
        if shot == prev_shoots[j]:
            return False
    return True

def shoot(grid, shot):
    grid.pop(shot)
    grid.insert(shot, 'X')

编辑1:我的代码的英文版:

"""//----------------bibliothèques----------------\\"""
import random



"""//----------------initialisation des variables----------------\\"""
grid_playerA_init = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,       #IA's grid (player A)
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,]

grid_playerB_init = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,       #Player's grid (player B)
                        0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
                        0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
                        0, 1, 0, 1, 0, 0, 0, 0, 0, 0,
                        0, 1, 0, 1, 0, 0, 0, 0, 0, 0,
                        0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 
                        0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
                        0, 0, 0, 1, 1, 1, 1, 0, 0, 1,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,]


previous_shots = []#empty matrix which will contain all the shots
touch = False #False because we don t already touch a boat
NbBoatTouchPlayer = 0 #count the amount of time the player touches a boat, it will help to know the end of the game
NbBoatTouchIA = 0 #count the amount of time the IA touches a boat, it will help to know the end of the game



"""//----------------fonctions----------------\\"""




def replaceBoat():#replace the '0' by '1' to symbolise a boat  
    grid_playerA_init.pop(position)
    grid_playerA_init.insert(position, 1)


def can_place_boat_here(x,y, direc, length):# check if there is no collision between boats 
    if direc == 0: # verticle direction
        for i in range(length):
            if (x + y*10+10*i) < 100:#if the boat doesn t exceed
                if grid_playerA_init [x +10*y + 10*i] == 1:#if there is already an other boat
                    return False 
            elif (x + y*10 +10*i) >= 100:#if we exceed the grid 
                for j in range(length - i):
                    #print((x + 10 * y) - (10 * i))
                    #print (i)
                    #print("can_place_boat_here")
                    #print(x,y,i)
                    if grid_playerA_init[(x + 10 * y) - (10* i)] == 1: #if there is already a boat
                        return False 
        return True

    if direc == 1: # horizontal direction
        for i in range(length):
            if ((x + 10*y + i)-9) % 10 != 0: 
                if grid_playerA_init [x + 10*y + i] == 1:
                    return False
            elif ((x+10*y)-9) % 10 == 0:
                for j in range(length - i):
                    if x+10*y-i == 1:
                        return False
                    return True
        return True



def place_boat_vertically(x,y,direc,lenght):#place a boat vertically with the coordinates
    if can_place_boat_here(x,y, direc,lenght):
        for i in range(lenght):
            global position
            position = x + y*10
            if position >= 100:
                position = position- 10 * i
                for j in range(lenght-i):
                    position = position - 10
            #print("place_boat_vertically")
            #print(x,y)
            replaceBoat()
            y = y + 1
    else:
        #####
        while can_place_boat_here(x,y, direc,lenght) == False:
            print("FALSE VERTC")
            print(lenght)
            """ -------------------------------------TEST-------------------------------------"""
            x = random.randint(0, 9)
            y = random.randint(0, 9)
            print("x")
            print(x)
            print("y")
            print(y)


            for i in range(lenght):
                position = x + y*10
                if position >= 100:
                    position = position- 10 * i
                    for j in range(lenght-i):
                        position = position - 10
                #print("place_boat_vertically")
                #print(x,y)
                replaceBoat()
                y = y + 1





def place_boat_horizontally(x,y,direc,lenght):#place a boat horizontally with the coordinates
    if can_place_boat_here(x,y, direc,lenght):
        for i in range(lenght):
            global position
            position = x + y * 10

            #print("place_boat_horizontally")
            #print(x,y)

            if (position - 9) % 10 == 0:
                replaceBoat()
                position = position -1 * i
                for j in range(lenght - i):
                    position = position - 1
                    replaceBoat()
            else:
                replaceBoat()
                x = x + 1
    else:
       #####
        while can_place_boat_here(x,y, direc,lenght) == False:
            print("FALSE HORIZ")
            print(lenght)
            """ -------------------------------------TEST-------------------------------------"""
            x = random.randint(0, 9)
            y = random.randint(0, 9)
            print("x")
            print(x)
            print("y")
            print(y)



            for i in range(lenght):
                position = x + y * 10

                #print("place_boat_horizontally")
                #print(x,y)

                if (position - 9) % 10 == 0:
                    replaceBoat()
                    position = position -1 * i
                    for j in range(lenght - i):
                        position = position - 1
                        replaceBoat()
                else:
                    replaceBoat()
                    x = x + 1


            """ -------------------------------------END OF THE TEST-------------------------------------"""            

def check_shot(shot):#check if the shot has not already been fired
    for i in range(len(previous_shots)):
        if previous_shots[i] == shot:
            return False
    return True




def replaceshot(shot):#replace the boat touched by an X
    del grid_playerB_init[shot] #delete the touched element
    grid_playerB_init.insert(shot, 'X') #by an X





def IA ():
    shot = random.randint(0, 99)
    if check_shot(shot):
        previous_shots.append(shot)

        if grid_playerB_init[shot] == 1:
            replaceshot(shot)
            touch = True

            i = 1
            nextshot = shot + i
            if grid_playerB_init[nextshot] == 1: # + 1 (right)
                replaceshot(nextshot)
                i = i + 1
                nextshot = shot + i


            elif grid_playerB_init[nextshot] == 0: # - 1(left)
                i = 1 # variable reset
                nextshot = shot - 1
                if grid_playerB_init[nextshot] == 1:
                    replaceshot(nextshot)
                    i = i + 1
                    nextshot = shot - i

            elif grid_playerB_init[nextshot] == 0: # + 10 (upstair)
                i = 1 # variable reset
                nextshot = shot - 10
                if grid_playerB_init[nextshot] == 1:
                    replaceshot(nextshot)
                    i = i + 10
                    nextshot = shot - i

            elif grid_playerB_init[nextshot] == 0: # - 10 (downstair)
                i = 1 # variable reset
                nextshot = shot + 10
                if grid_playerB_init[nextshot] == 1:
                    replaceshot(nextshot)
                    i = i + 10
                    nextshot = shot + i



def IA_pourrie(): # just a simple IA which fires randomly with no logic
    shot = random.randint(0, 99)
    if check_shot(shot):
        previous_shots.append(shot)



def Endgame(): #function which makes end of the game when all the boats are touched by one of the players
    if NbBoatTouchPlayer == 14 or NbBoatTouchIA == 14: #5+4+3+2 = 14
        print("END OF THE GAME")
        print("your grid :")
        print(grid_playerB_init)
        print("IA's grid :")
        print(grid_playerA_init)



"""//----------------corps du programme----------------\\"""


for boat in range(2, 6): # we place the boats of 2;3;4 and 5 cases 
    direction = random.randint(0, 1) # choose a random integer between 0 and 1. 0 stands for vertically and 1 stands for horizontally
    positionX = random.randint(0, 9)
    positionY = random.randint(0, 9)
    if direction == 0:
        place_boat_vertically(positionX, positionY, 0, boat)
    if direction == 1:
        place_boat_horizontally(positionX, positionY, 1, boat)
print (grid_playerA_init)



for loop in range(200):         #IA's launch
    IA()
print("")    
print(grid_playerB_init)
print("")
print(previous_shots)

法语版本:

"""//----------------bibliothèques----------------\\"""
import random



"""//----------------initialisation des variables----------------\\"""
tableau_joueurA_init = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,       #IA EN JOUEUR A
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,]

tableau_joueurB_init = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,       #JOUEUR EN JOUEUR B
                        0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
                        0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
                        0, 1, 0, 1, 0, 0, 0, 0, 0, 0,
                        0, 1, 0, 1, 0, 0, 0, 0, 0, 0,
                        0, 1, 0, 0, 0, 0, 1, 1, 0, 0, #exemple : postition x = 3 (compter le 0) et position y = 1 ---> position = 13
                        0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
                        0, 0, 0, 1, 1, 1, 1, 0, 0, 1,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,]


previous_shots = []#matrice vide qui contiendra la liste de tous les tirs effectués
touché = False #on initialise la variable touché à False car on a pas deja touché de bateau
NbBateauxTouchésJoueur = 0 #sert à compter le nombre de bateaux touchés par le joueur, et donc de prévoir la fin du jeu
NbBateauxTouchésIA = 0 #sert à compter le nombre de bateaux touchés par l'IA, et donc de prévoir la fin du jeu



"""//----------------fonctions----------------\\"""




def replaceBateau():#remplace les '0' par des '1' pour symboliser un bateau   
    tableau_joueurA_init.pop(position)
    tableau_joueurA_init.insert(position, 1)


def peut_placer_un_bateau_ici(x,y, direc, longueur):# verifie qu'il n'y ai pas de collision au moment de placer un bateau
    if direc == 0: # verticale
        for i in range(longueur):
            if (x + y*10+10*i) < 100:#si le bateau ne dépasse pas
                if tableau_joueurA_init [x +10*y + 10*i] == 1:#si il y a deja un bateau
                    return False
            elif (x + y*10 +10*i) >= 100:#si on depasse du tableau
                for j in range(longueur - i):
                    #print((x + 10 * y) - (10 * i))
                    #print (i)
                    #print("peut_placer_un_bateau_ici")
                    #print(x,y,i)
                    if tableau_joueurA_init[(x + 10 * y) - (10* i)] == 1:
                        return False # il y a deja un bateau !
        return True

    if direc == 1: # horizontale
        for i in range(longueur):
            if ((x + 10*y + i)-9) % 10 != 0: 
                if tableau_joueurA_init [x + 10*y + i] == 1:
                    return False
            elif ((x+10*y)-9) % 10 == 0:
                for j in range(longueur - i):
                    if x+10*y-i == 1:
                        return False
                    return True
        return True



def placer_bateau_verticalement(x,y,direc,lenght):#place un bateau verticalement avec les coordonnés
    if peut_placer_un_bateau_ici(x,y, direc,lenght):
        for i in range(lenght):
            global position
            position = x + y*10
            if position > 100:
                position = position- 10 * i
                for j in range(lenght-i):
                    position = position - 10
            #print("placer_bateau_verticalement")
            #print(x,y)
            replaceBateau()
            x = x + 10
    else:
        #####
        while peut_placer_un_bateau_ici(x,y, direc,lenght) == False:
            print("FALSE VERTC")
            print(lenght)
            """ -------------------------------------TEST-------------------------------------"""
            x = random.randint(0, 9)
            y = random.randint(0, 9)
            print("x")
            print(x)
            print("y")
            print(y)


            for i in range(lenght):
                position = x + y*10
                if position > 100:
                    position = position- 10 * i
                    for j in range(lenght-i):
                        position = position - 10
                #print("placer_bateau_verticalement")
                #print(x,y)
                replaceBateau()
                x = x + 10





def placer_bateau_horizontalement(x,y,direc,lenght):#place un bateau horizontalement avec les coordonnés
    if peut_placer_un_bateau_ici(x,y, direc,lenght):
        for i in range(lenght):
            global position
            position = x + y * 10

            #print("placer_bateau_horizontalement")
            #print(x,y)

            if (position - 9) % 10 == 0:
                replaceBateau()
                position = position -1 * i
                for j in range(lenght - i):
                    position = position - 1
                    replaceBateau()
            else:
                replaceBateau()
                x = x + 1
    else:
       #####
        while peut_placer_un_bateau_ici(x,y, direc,lenght) == False:
            print("FALSE HORIZ")
            print(lenght)
            """ -------------------------------------TEST-------------------------------------"""
            x = random.randint(0, 9)
            y = random.randint(0, 9)
            print("x")
            print(x)
            print("y")
            print(y)



            for i in range(lenght):
                position = x + y * 10

                #print("placer_bateau_horizontalement")
                #print(x,y)

                if (position - 9) % 10 == 0:
                    replaceBateau()
                    position = position -1 * i
                    for j in range(lenght - i):
                        position = position - 1
                        replaceBateau()
                else:
                    replaceBateau()
                    x = x + 1




def check_tir(tir):#verifie que le tir n'a pas deja été fait
    for i in range(len(previous_shots)):
        if previous_shots[i] == tir:
            return False
    return True




def replaceTir(tir):#remplace le bateau touché par une croix
    del tableau_joueurB_init[tir] #supprime l'element touché
    tableau_joueurB_init.insert(tir, 'X') #par un X





def IA ():
    tir = random.randint(0, 99)
    if check_tir(tir):
        previous_shots.append(tir)

        if tableau_joueurB_init[tir] == 1:
            replaceTir(tir)
            touché = True

            i = 1
            nextshot = tir + i
            if tableau_joueurB_init[nextshot] == 1: # + 1 (à droite)
                replaceTir(nextshot)
                i = i + 1
                nextshot = tir + i


            elif tableau_joueurB_init[nextshot] == 0: # - 1(à gauche)
                i = 1 # on reset la variable
                nextshot = tir - 1
                if tableau_joueurB_init[nextshot] == 1:
                    replaceTir(nextshot)
                    i = i + 1
                    nextshot = tir - i

            elif tableau_joueurB_init[nextshot] == 0: # + 10 (en haut)
                i = 1 # on reset la variable
                nextshot = tir - 10
                if tableau_joueurB_init[nextshot] == 1:
                    replaceTir(nextshot)
                    i = i + 10
                    nextshot = tir - i

            elif tableau_joueurB_init[nextshot] == 0: # - 10 (en bas)
                i = 1 # on reset la variable
                nextshot = tir + 10
                if tableau_joueurB_init[nextshot] == 1:
                    replaceTir(nextshot)
                    i = i + 10
                    nextshot = tir + i



def IA_pourrie():
    tir = random.randint(0, 99)
    if check_tir(tir):
        previous_shots.append(tir)



def finDuGame():        #fonction qui met fin au jeu, quand tous les bateaux sont touchés pour n'importe quel joueur
    if NbBateauxTouchésJoueur == 14 or NbBateauxTouchésIA == 14: #5+4+3+2 = 14
        print("FIN DU JEU")
        print("votre jeu :")
        print(tableau_joueurB_init)
        print("jeu de l'IA :")
        print(tableau_joueurA_init)



"""//----------------corps du programme----------------\\"""


for bateau in range(2, 6): # on place les bateaux de 2;3;4 et 5 cases 
    direction = random.randint(0, 1) # choisi un nombre entre 0 et 1. 0 correspond à la verticale et 1 à l'horizontale
    positionX = random.randint(0, 9)
    positionY = random.randint(0, 9)
    if direction == 0:
        placer_bateau_verticalement(positionX, positionY, 0, bateau)
    if direction == 1:
        placer_bateau_horizontalement(positionX, positionY, 1, bateau)
print (tableau_joueurA_init)



for loop in range(200):         #lancement de l'IA
    IA()
print("")    
print(tableau_joueurB_init)
print("")
print(previous_shots)

2 个答案:

答案 0 :(得分:1)

  • 如评论中所述,除非您有充分的理由(例如技术或行政术语),否则请始终用英语编写代码
  • 使用snake_case(PEP8)。
  • 避免使用全局变量:它们使代码很多难以阅读。
  • 也许使用二维列表。

现在,基础知识:

>>> L = [2]
>>> L.pop(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> L[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

在您的代码中:

def peut_placer_un_bateau_ici(x,y, direc, longueur):# verifie qu'il n'y ai pas de collision au moment de placer un bateau
    ...
            elif (x + y*10 +10*i) >= 100:#si on depasse du tableau
                ...
                    if tableau_joueurA_init[(x + 10 * y) - (10* i)] == 1:

如果x + y*10 >= 100 and i == 0会发生什么?您有(x + 10 * y) - (10* i) = (x + y*10 +10*i) >= 100list index out of range

然后:

def placer_bateau_verticalement(x,y,direc,lenght):#place un bateau verticalement avec les coordonnés
    ...
            if position > 100:
                # fix position
           replaceBateau()

还有

def replaceBateau():#remplace les '0' par des '1' pour symboliser un bateau   
    tableau_joueurA_init.pop(position)
    tableau_joueurA_init.insert(position, 1)

(BTW, a list is mutable: `tableau_joueurA_init[position] = 1` would do the trick)

如果position == 100会发生什么? pop index out of range

您必须注意边缘情况。建议:清理代码,修复错误,然后将其发布到https://codereview.stackexchange.com

编辑。有点帮助,因为您似乎迷路了。

首先,您需要了解Top-down approach

  

使用自上而下的方法编写程序的技术是编写一个主要过程,该过程将列出所需的所有主要功能。稍后,编程团队将研究每个功能的需求,然后重复该过程。

让我们尝试将其应用于伪代码:

def main():
    grid = init_grid()
    put_boats(grid)
    for _ in range(100):
        play(grid)

def put_boats(grid):
    for b in range(2,6):
        x, y, dir = random
        while cant_put_boat(b, x, y, dir):
            x, y, dir = random
        put_boat(b, x, y, dir, grid)

def cant_put_boat(b, x, y, dir, grid):
    # you don't need to test every position
    return dir == HORIZ and x + b >= 10
        or dir == VERT and y + b >= 10

def put_boat(b, x, y, dir, grid):
    # you can write it yourself

def play(grid):
    x, y = random
    while cant_shoot(grid, x, y)
        x, y = random
    shoot(x, y)

def can_shoot(grid, shot)
    # you can write it yourself

def shoot(grid, shot)
    # you can write it yourself

这是非常示意性的,但是应该可以帮助您。尝试使其简单和干净。创建小型函数(4-6行代码,仅此而已)。在熟悉过程代码之前,请不要切换到类。

使用assert,并在可能的情况下使用doctest测试您的代码。

最后一招:

tableau_joueurA_init = [0, 0, ..., 0]

与:

tableau_joueurA_init = [0]*100 # 100 times the element 0

答案 1 :(得分:0)

在发布我的整个代码之前,我想对@jferard表示感谢,他会指导我并帮助我很多

这是代码:

"""//----------------library----------------\\"""
import random



"""//----------------variables----------------\\"""

gridPlayerA = [0] * 100 #IA's grid
gridPlayerB = [0] * 100 #Player's grid


gridGamePlayerA = [0] * 100 # just create a copy of the IA boards and only show the empty board



OnGame = True # turn on the game

PrevPlayerShoots = []
PrevIAShoots = []





"""//----------------functions----------------\\"""

def main():

    BoatTouchedByPlayer = 0
    BoatTouchedByIA = 0
    print(gridPlayerB)

    put_boats(gridPlayerA)#put IA's boats randomly
    put_boats(gridPlayerB)#put Player's boats randomly (temporarily)
    while OnGame == True: #while we're in the game


        print(gridGamePlayerA) # print the IA's grid (with no boats)


        PlayerShoot = input("It's your turn, where do you want to shoot ? (give the coords like this : A,1) ")
        PlayerShoot.split(",") #Split the coords
        Lettre = PlayerShoot[0] # take the lettre
        Number = int(PlayerShoot[2]) # take the number, convert into an integer

        Player_Shoot = int(ord(Lettre)) - 65 + 10*(Number - 1) # transform the lettre and the number into a number coord


        if can_shoot(PrevPlayerShoots, Player_Shoot) == True: #if we can shoot



            if gridPlayerA[Player_Shoot] == 1: # if we touch a boat in the IA's board
                shoot_Touched(gridGamePlayerA, Player_Shoot) # call the shoot function that replace the coord by an F on the empty board
                print("touched")
                BoatTouchedByPlayer = BoatTouchedByPlayer + 1# count until 14 (number of boat "parts")
                End_Game("Player") # check if the player won


            else:
                shoot(gridGamePlayerA, Player_Shoot)# show the shot next time to remind the player where he has shoot
                print("missed, IA's turn : ")
                IA_shot = random.randint(0, 99) # make the IA shot randomly 
                if gridPlayerB[IA_shot] == 1:# if IA touch a boat in the player's board
                    print("IA touched one of your boat")
                    shoot_Touched(gridPlayerB, IA_shot) # call the shoot function that replace the coord by an F
                    print(gridPlayerB) # print the player's board
                    BoatTouchedByIA = BoatTouchedByIA + 1 # count until 14 (number of boat "parts")
                    End_Game("IA") # check if the IA won

                else:
                    shoot(gridPlayerB, IA_shot) # replace the shoot by an X
                    print("Lucky, IA missed !")




def shoot_Touched(grid, shot):
    grid.pop(shot)
    grid.insert(shot, 'F')


def shoot(grid, shot):
    grid.pop(shot)
    grid.insert(shot, 'X')



def End_Game(grid):
    if grid == "IA":
        if grid == 14: # if IA has touched all the player's boat
            OnGame = False #turn off the game
            print("Too bad, IA has won !")

    elif grid == "Player":    
        if grid == 14:
            OnGame = False #turn off the game
            print("Wow, you have won !")



def can_shoot(List, shot):
    for x in range(len(List)):#check if the shoot didn't already done
        if List[x] == shot:
            print("you've already shoot here !")
            return False
    List.append(shot)        
    return True


def put_boats(grid):
    for n in range(2,6):
        x, y, direction = random.randint(0,9), random.randint(0,9), random.randint(0,1)
        while cant_put_boat(n, x, y, direction, grid):
            x, y, direction = random.randint(0,9), random.randint(0,9), random.randint(0,1)
        put_boat(n, x, y, direction, grid)



def put_boat(length, x, y, direction, grid):
    if direction == 0: # HORIZ direction
        for i in range(length):
            position = x+i + 10*y
            grid[position] = 1


    if direction == 1: # VERT direction
        for i in range(length):
            position = x + 10*(y+i)
            grid[position] = 1


def cant_put_boat(length, x, y, direction, grid):
    return direction == 0 and x + length >= 10 or direction == 1 and y + length >= 10





"""//----------------main code----------------\\"""


main()#simply run the main function