Oct-17-2022, 12:39 AM
I have a little problem with this code, it works sometimes, and something it doesn't. I don't know what is causing the problem. beneath, I will provide the output when it works and when it doesn't.
import random board = [] for i in range(3): board.append([]) for j in range(10): board[i].append([]) for k in range(10): board[i][j].append('-') ships = [] ships.append(['S', 2]) ships.append(['S', 3]) ships.append(['S', 3]) ships.append(['S', 4]) ships.append(['S', 5]) for ship in ships: level = random.randint(0, 2) start_space = random.randint(0, 9) for i in range(ship[1]): board[level][start_space + i][random.randint(0, 9)] = ship[0] for level in board: print('------------------------------') for row in level: print(row)
Output:['-', '-', '-', '-', '-', '-', '-', 'S', '-', '-']
['-', 'S', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', 'S']
['-', '-', 'S', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
------------------------------
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', 'S', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', 'S', 'S', '-']
['-', 'S', '-', '-', '-', '-', '-', '-', '-', 'S']
['-', '-', '-', '-', '-', '-', '-', 'S', '-', 'S']
['-', 'S', 'S', 'S', '-', '-', '-', '-', '-', '-']
['-', 'S', '-', '-', '-', 'S', '-', '-', '-', '-']
['S', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
------------------------------
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
Output:Traceback (most recent call last):
File "C:/Users/Alex/Desktop/batt.py", line 22, in <module>
board[level][start_space + i][random.randint(0, 9)] = ship[0]
IndexError: list index out of range