Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- gameboard = []
- threeShip = []
- twoshipcoords = []
- oneshipcoord = []
- for x in range(5):
- gameboard.append(["O"] * 5)
- battleships = gameboard
- def print_board(board):
- for row in board:
- print(" ".join(row))
- def random_row(board):
- return random.randint(0, len(board) - 1)
- def random_col(board):
- return random.randint(0, len(board[0]) - 1)
- def place_oneship(board): #place a one "peg" ship
- x = random_row(board)
- y = random_col(board)
- battleships[y][x] = "B"
- oneshipcoord.append([x, y])
- def place_twoship(board):
- twoship = 0 #how many "pegs" the ship has.
- while twoship == 0:
- #x = random_row(board)
- #y = random_col(board)
- x = 2
- y = 4
- if board[y][x] != "B": #check if the spot is empty for a ship
- board[y][x] = "B"
- twoship = 1
- twoshipcoords.append([x, y])
- while twoship == 1: #Start checking if surrounding areas are clear for the ship to expand one space
- #Checks for direction, then make sure index isn't out of bound.
- direction = "N"#random.choice("NSEW") #Code by Kevin below from Stackoverflow, thank you
- print(direction)
- if direction == "N" and x + 1 < 5 and y - 1 >=0:
- if board[y-1][x] != "B":
- board[y-1][x] = "B"
- twoship = 2
- twoshipcoords.append([x, y - 1])
- elif direction == "S"and x - 1 >= 0 and y + 1 <5:
- if board[y+1][x] != "B":
- board[y+1][x] = "B"
- twoship = 2
- twoshipcoords.append([x , y + 1])
- elif direction == "E"and y <5 and x + 1 <5:
- if board[y][x+1] != "B":
- board[y][x+1] = "B"
- twoship = 2
- twoshipcoords.append([x + 1 , y])
- elif direction == "W" and y - 1 >=0:
- if board[y][x-1] != "B":
- board[y][x-1] = "B"
- twoship = 2
- twoshipcoords.append([x - 1 , y])
- place_oneship(battleships)
- place_twoship(battleships)
- print(twoshipcoords)
- print_board(battleships)
- print ("Let's play Battleship!")
- print_board(gameboard)
- for turn in range(4):
- guess_row = int(input("Guess Row: "))
- guess_col = int(input("Guess Col:"))
- guess_point =[guess_row, guess_col]
- if guess_point == "H" or guess_point == "X":
- print("That spot has already been chosen")
- for coords in zip(twoshipcoords[:], oneshipcoord[:]):
- if guess_point == coords:
- gameboard[guess_col][guess_row] = "H"
- twoshipcoords.remove(coords)
- break
- else:
- print("You missed my battleship!")
- gameboard[guess_col][guess_row] = "X"
- print_board(gameboard)
- print(twoshipcoords)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement