import random # BEGIN: constants and globals board = [[],[]] HUMAN = 0 COMPUTER = 1 EMPTY = 0 SHIP = 1 HIT = 2 MISS = 3 shipsNumber = 1 ships = [shipsNumber*2, shipsNumber*2] # END: constants and globals def initializeGameboard(): for who in [HUMAN, COMPUTER]: safety = 100 shipsToSet = shipsNumber for r in range(10): row = [] for c in range(10): row.append(EMPTY) board[who].append(row) # Or the same with list comprehension # which is more Pythonic approach but less universal (portable) ''' board[who] = [[EMPTY for _ in range(10)] for _ in range(10)] ''' while True and safety > 0: orientation = random.randint(0, 1) if orientation == 0: # Vertical orientation r = random.randint(0, 9-1) c = random.randint(0, 9) if board[who][r][c] == EMPTY and board[who][r+1][c] == EMPTY: board[who][r][c] = SHIP board[who][r+1][c] = SHIP shipsToSet -= 1 else: # Horizontal orientation r = random.randint(0, 9) c = random.randint(0, 9-1) if board[who][r][c] == EMPTY and board[who][r][c+1] == EMPTY: board[who][r][c] = SHIP board[who][r][c+1] = SHIP shipsToSet -= 1 safety -= 1 if shipsToSet == 0: break if safety == 0: print("PROBLEM Z USTAWIENIEM STATKÓW") def printGameboard(forWhom): who = forWhom whoReadable = "Komputera" if who == COMPUTER else "Gracza" print(f'\n=== stan planszy {whoReadable} ===\n') print(' 0123456789') for r in range(0,10): print(f'{r} ', end = '') for c in range(0,10): if board[who][r][c] == EMPTY: print('.', end = '') elif board[who][r][c] == SHIP: print('#', end = '') elif board[who][r][c] == HIT: print('X', end = '') elif board[who][r][c] == MISS: print('*', end = '') print() def getOpponent(forPlayer): return HUMAN if forPlayer == COMPUTER else COMPUTER def switchPlayer(currentPlayer): return getOpponent(forPlayer = currentPlayer) def getReadableName(who): return "Gracza" if who == HUMAN else "Komputera" def checkIfPlayerIsWinner(who): opponent = getOpponent(forPlayer = who) if ships[opponent] == 0: return True return False def shot(forPlayer): who = forPlayer if who == HUMAN: r = int(input('Podaj wiersz')) c = int(input('Podaj kolumnę')) else: r = random.randint(0, 9) c = random.randint(0, 9) opponent = getOpponent(forPlayer = who) if r>=0 and r<=9 and c>=0 and c<= 9: if board[opponent][r][c] == SHIP: board[opponent][r][c] = HIT ships[opponent] -= 1 elif board[opponent][r][c] == EMPTY: board[opponent][r][c] = MISS else: print("Niepoprawne współrzędne, tracisz swój ruch.") else: print("Współrzędne ze złego zakresu.") def mainGameLoop(): who = HUMAN while True: whoReadable = getReadableName(who = who) print(f"Teraz kolej {whoReadable}") shot(forPlayer = who) opponent = getOpponent(who) printGameboard(forWhom = opponent) if checkIfPlayerIsWinner(who): player = "Wygrałeś!" if who == HUMAN else "Komputer wygrał!" print(f"Brawo! {player}") break who = switchPlayer(currentPlayer = who) initializeGameboard() printGameboard(forWhom = HUMAN) printGameboard(forWhom = COMPUTER) mainGameLoop()