Skip to content

Instantly share code, notes, and snippets.

@lfalanga
Created December 14, 2019 20:37
Show Gist options
  • Save lfalanga/9577b1f020f44bbc2c1579dc086f4e0d to your computer and use it in GitHub Desktop.
Save lfalanga/9577b1f020f44bbc2c1579dc086f4e0d to your computer and use it in GitHub Desktop.
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
# Situating ship randomly
def situating_ship():
ship_row = random_row(board)
ship_col = random_col(board)
return [ship_row, ship_col]
# Performing attack
def performing_attack(shootting_target):
print 'Please define shooting coordinates...'
guess_row = int(raw_input("Guess Row input: "))
guess_col = int(raw_input("Guess Col input: "))
shootting_target = [guess_row, guess_col]
return shootting_target
# Shooting missiles
# return 1: Ship destroyed
# return 2: Out of the ocean
# return 3: Already shootted target
# return 4: Missed target
def shooting_missiles(ship_location_in, shootting_target_in):
if (shootting_target_in[0] == ship_location_in[0]) and (shootting_target_in[1] == ship_location_in[1]):
return 1
else:
if (shootting_target_in[0] not in range(5)) or (shootting_target_in[1] not in range(5)):
return 2
elif (board[shootting_target_in[0]][shootting_target_in[1]] == 'X'):
return 3
else:
# Storing attack attemp into the board
board[shootting_target_in[0]][shootting_target_in[1]] = 'X'
return 4
# Main Program
from random import randint
# Generating board
board = []
for x in range(0, 5):
board.append(["O"] * 5)
# Ship location
ship_location = []
# Shotting target
shootting_target = []
# Defining ship location randomly
ship_location = situating_ship()
# Printing out battleship location
print 'Ship location: (%s, %s)' % (ship_location[0], ship_location[1])
print
# Battleships starts (4 attemps)
for i in range(4):
# Preparing attack
shootting_target = performing_attack(shootting_target)
# Printing out attack target
print 'Attempting attack number %s at coordinates: (%s, %s)' % (i+1, shootting_target[0], shootting_target[1])
print
shooting_missile_result = shooting_missiles(ship_location, shootting_target)
if shooting_missile_result == 1:
print 'Congratulations! You sank my battleship!'
break
elif shooting_missile_result == 2:
print "Oops, that's not even in the ocean."
print
elif shooting_missile_result == 3:
print 'You guessed that one already.'
print
elif shooting_missile_result == 4:
print 'You missed my blattleship!'
# Printing out Battleship board
print 'Battleship attack board:'
print_board(board)
print
else:
print '¡Vada a bordo, cazzo!'
print '¡Ciao!'
break
print 'WAR IS OVER! Give peace a chance.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment