field_width
field_height
ship_count
cheats
from IPython.display import clear_output
import random
def gen_field(width: int, height: int):
return [*map(lambda a: [a]*width,[0]*height)]
def gen_position(width: int, height: int):
return [random.randint(0,width-1),random.randint(0,height-1)]
def populate_field(field: list, ship_count: int):
height = len(field)
width = len(field[0])
if ship_count >= (len(field)*len(field[0]))/2:
print('This won\'t be a good game')
return
ship_positions = []
for _ in range(ship_count):
new_pos = gen_position(width, height)
while new_pos in ship_positions:
new_pos = gen_position(width, height)
ship_positions.append(new_pos)
for pos in ship_positions:
field[pos[1]][pos[0]] = 1 # pos[1] is height and pos[0] is width
return field
def print_field(field: list):
"""
Prints the field in user_readable form
-1 = missed
0 = unknown
1 = ship
"""
for row in field:
print(' '.join([str(x) for x in row]).replace('-1','ā¹').replace('0','š³').replace('1','š¢'))
def prompt_input():
user_in = input('Your guess>>>').replace(' ','').split(',')
while True:
try:
if len(user_in) != 2:
pass
else:
int_input = [int(x) for x in user_in]
return int_input
except:
user_in = input('Your guess in format `width, height` with index starting from 1 >>>').replace(' ','').split(',')
field_width = int(field_width)
field_height = int(field_height)
ship_count = int(ship_count)
def play():
user_field = gen_field(field_width,field_height)
game_field = populate_field(gen_field(field_width,field_height), ship_count)
if cheats != 'No':
print_field(game_field)
print('*'*20)
retries = ship_count*3
moves_made = 0
score = 0
while moves_made <= retries:
print_field(user_field)
h,w = prompt_input()
w -= 1
h -= 1
if retries != moves_made:
clear_output(wait=True)
already_shot = user_field[h][w] != 0
if already_shot:
moves_made -=1
print('You can\'t fire on one cell multiple times')
elif game_field[h][w] == 1:
user_field[h][w] = 1
score += 1
if score != ship_count:
print(f'Yay! Nice shot š«')
else:
user_field[h][w] = -1
moves_made += 1
if moves_made <= retries:
print(f'Moves remaining: {retries-moves_made}')
if score == ship_count:
clear_output(wait=True)
print_field(game_field)
print('*'*20)
print_field(user_field)
print(f'š Congrats! You managed to shoot {score} boat{"s" if score > 1 else ""} in {moves_made} move{"s" if moves_made > 1 else ""}')
return
print('*'*20)
print_field(game_field)
print(f'š¾ Game over! Score {score} out of {ship_count} in {moves_made} moves')
play()