Beispiel #1
0
def main():
    grid = g.read_grid('grid.txt')
    # grid = g.make_grid(20, 20)
    g.print_grid(grid)
    print()

    start = get_user_coords(grid, 'start')
    end = get_user_coords(grid, 'goal')
    print('-' * 15)

    # Randomly toggles search and heuristic methods
    path, num_states = informed_search(grid,
                                       start,
                                       end,
                                       greedy=choice([True, False]),
                                       manhattan=choice([True, False]))
    print('Number of nodes expanded:', num_states)
    print('-' * 15)

    fname = 'path.txt'

    if path is None:
        print('No path found.')
    else:
        print('Path length: {} nodes'.format(len(path)))
        print('Total cost:', path[0][1])
        print()
        g.output_grid(fname, grid, start, end, [x[0] for x in path])
        print()
        print('Path: coordinate - cost')
        print('\n'.join('\t{} - {:02d}'.format(coord, cost)
                        for coord, cost in path[::-1]))
Beispiel #2
0
def ship_phase():
    """The function for the ship deployment phase. prompts the player
    to deploy all his ships and after confirming deployment, deploys the
    AI's ships"""
    grid.print_grid(participants.player.ship_grid)
    for ship in participants.player.ship_locations:
        while True:
            try:
                cords = cfg.coordregex.search(input("Where do you want to put "
                                                    + ship + "? [Size of this ship=" + str(cfg.ships[ship]['size']) +
                                                    " cells] "))
                ans = input("I understood " + str(cords.groups()) + " is this correct?(y/n) ")
                if ans.strip().lower()[0] == 'y':
                    Ycoord = int(cords.group(2)) - 1
                    Xcoord = ord(cords.group(1).lower()) - 97
                    direction = input("In which direction? (up/down/left/right) ")
                    if direction.lower() not in cfg.directions_list:
                        print("That's not a valid direction")
                        continue
                    else:
                        valid, Ystep, Xstep = grid.check_location_validity(participants.player,
                                                                           participants.player.ship_grid,
                                                                           ship,
                                                                           Xcoord,
                                                                           Ycoord,
                                                                           direction.lower())
                        if valid == 0:
                            continue
                        else:
                            grid.lay_ship(participants.player,
                                          ship,
                                          Xcoord,
                                          Ycoord,
                                          Ystep,
                                          Xstep)
                            grid.print_grid(participants.player.ship_grid)
                            break
                else:
                    continue
            except AttributeError:
                print("I didn't detect coordinates. ", end='')
                print("write a coordinate in the form 'LetterNumber' (ie A10 or B9)")
                continue
    while True:
        answer = input("This is your final layout, proceed?"
                       "(y = proceed - n = restart the process) ")
        if answer.strip().lower()[0] == 'y':
            grid.lay_ai_ships()
            battle_phase()
            return
        elif answer.strip().lower()[0] == 'n':
            participants.player.ship_grid = [['-' for x in range(cfg.h)] for y in range(cfg.w)]
            ship_phase()
        else:
            print("Not a valid answer")
            continue
Beispiel #3
0
def print_current_board(board, mask):
    grid.print_grid(board)
    for j, row in enumerate(mask):
        result = ""
        for i, col in enumerate(row):
            tmp_char = ""
            if not mask[j][i]:
                tmp_char = "X"
            else:
                tmp_cell = board[j][i]
                tmp_char = tmp_cell if tmp_cell != None else " "

            result += str(tmp_char)
        print(result)
Beispiel #4
0
def get_location(vessel_index) :
    global column
    global row
    global direction
    
    name = grid.VESSEL_NAMES[vessel_index]
    size = grid.VESSEL_SIZES[vessel_index]

    print('Enter placement of your', name, '(', size,  'spaces)')
    column = input('\tLeft Column (A-J): ')
    row = int(input('\tTop Row (1-10): '))
    direction = input('\tDirection (h)orizontal or (v)ertical: ')
    
    column = ord(column) - ord('A')
    row = row - 1
    
    if(column >= grid.GRID_WIDTH or column < 0) :
        print('The column entered is invalid, it must be a value between A and J.')
        get_location(vessel_index)
    elif(row >= grid.GRID_HEIGHT or row < 0) :
        print('The row entered is invalid, it must be between 1 and 10.')
        get_location(vessel_index)
    else :
        if (direction == 'h' and column + size > grid.GRID_WIDTH) :
            print('Invalid column. The vessel is directed horizontally to the right')
            print('and does not fit on the grid with this starting column.')
            get_location(vessel_index)
        elif (direction == 'v' and row + size > grid.GRID_HEIGHT) :
            print('Invalid row. The vessel is directed vertically downwards')
            print('and does not fit on the grid with this starting now.')
            get_location(vessel_index)
        else :
            if (direction != 'h' and direction != 'v') :
                print('The direction entered is invalid, it must be either (h)orizontal or (v)ertical.')
                get_location(vessel_index)
            else :
                overlap = grid.has_overlap(vessel_index, row, column, direction, defend_grid)
                if(overlap == True) :
                    print('The vessel entered overlaps another one! Please place your new vessel elsewhere.')
                    get_location(vessel_index)
                else :
                    grid.add_vessel(vessel_index, row, column, direction, defend_grid)           
                    grid.print_grid(defend_grid)     
Beispiel #5
0
def get_location(vessel_index) :
    global column
    global row
    global direction
    
    import random
    
    name = grid.VESSEL_NAMES[vessel_index]
    size = grid.VESSEL_SIZES[vessel_index]

    column = random.choice('ABCDEFGHIJ')
    row = random.randint(1,10)
    direction = random.choice('hv')
    
    column = ord(column) - ord('A')
    row = row - 1
    
    if(column >= grid.GRID_WIDTH or column < 0) :
        get_location(vessel_index)
    elif(row >= grid.GRID_HEIGHT or row < 0) :
        get_location(vessel_index)
    else :
        if (direction == 'h' and column + size > grid.GRID_WIDTH) :
            get_location(vessel_index)
        elif (direction == 'v' and row + size > grid.GRID_HEIGHT) :
            get_location(vessel_index)
        else :
            if (direction != 'h' and direction != 'v') :
                get_location(vessel_index)
            else :
                overlap = grid.has_overlap(vessel_index, row, column, direction, defend_grid)
                if(overlap == True) :
                    get_location(vessel_index)
                else :
                    grid.add_vessel(vessel_index, row, column, direction, defend_grid)
                    grid.print_grid(defend_grid)               
Beispiel #6
0
def main():

    # prints VESSEL_NAME[index], location, and orientation of a vessel
    print_titlescreen()
    grid.print_grid()
    # Ask user to place all 5 ships
    i = 0
    for i in range(5):  # for loop
        human.get_location(i)
        grid.print_grid()
        ai.get_location(i)
        grid.print_grid()

    enter_choice()
    return
def main():
        
    # prints VESSEL_NAME[index], location, and orientation of a vessel
	print_titlescreen()
	grid.print_grid()
    # Ask user to place all 5 ships
	i = 0
	for i in range(5): # for loop
		human.get_location(i)
		grid.print_grid()
		ai.get_location(i)
		grid.print_grid()
		
	enter_choice()
	return
Beispiel #8
0
 def optionC(self):
     grid.print_grid(participants.player.guess_grid)
Beispiel #9
0
 def optionB(self):
     grid.print_grid(participants.player.ship_grid)
def main():
	
	for i in range(grid.NUM_OF_VESSELS):
		
		#human.get_location(i)
		grid.add_vessel(human.grid_defend, i, i, 0, 'h') 
		ai.get_location(i)
		print("AI Grid:")
		grid.print_grid(ai.grid_defend)
		print("Human Grid:")
		grid.print_grid(human.grid_defend)  

	while not (grid.all_vessels_sunk(ai.grid_defend) and grid.all_vessels_sunk(human.grid_defend)):
		
		human.enter_choice()
		
		row, col = human.get_choice()
		grid.drop_bomb(ai.grid_defend, human.grid_attack, row, col)
		
		row, col = ai.get_choice()
		grid.drop_bomb(human.grid_defend, ai.grid_attack, row, col)
		
		print("AI Grid:")
		grid.print_grid(ai.grid_defend)
		print("Human Grid:")
		grid.print_grid(human.grid_defend)  
		print("AI Grid A:")
		grid.print_grid(ai.grid_attack)
		print("Human Grid A:")
		grid.print_grid(human.grid_attack)  
Beispiel #11
0
def main():

    for i in range(grid.NUM_OF_VESSELS):

        #human.get_location(i)
        grid.add_vessel(human.grid_defend, i, i, 0, 'h')
        ai.get_location(i)
        print("AI Grid:")
        grid.print_grid(ai.grid_defend)
        print("Human Grid:")
        grid.print_grid(human.grid_defend)

    while not (grid.all_vessels_sunk(ai.grid_defend)
               and grid.all_vessels_sunk(human.grid_defend)):

        human.enter_choice()

        row, col = human.get_choice()
        grid.drop_bomb(ai.grid_defend, human.grid_attack, row, col)

        row, col = ai.get_choice()
        grid.drop_bomb(human.grid_defend, ai.grid_attack, row, col)

        print("AI Grid:")
        grid.print_grid(ai.grid_defend)
        print("Human Grid:")
        grid.print_grid(human.grid_defend)
        print("AI Grid A:")
        grid.print_grid(ai.grid_attack)
        print("Human Grid A:")
        grid.print_grid(human.grid_attack)