-2
import time

ocean_table = ("  A B C D E F\n" +
               "1 # # # # # #\n" +
               "2 # # # # # #\n" +
               "3 # # # # # #\n" +
               "4 # # # # # #\n" +
               "5 # # # # # #\n" +
               "6 # # # # # #\n")
print(ocean_table)

battleship_placement = ["A3" or 88, "A4" or 116, "A5" or 144, "C2" or 68, "D3" or 100, "E4" or 132, "F5" or 164]

player_guess = input("Enter your coordinates: ")
player_guess = player_guess.upper()

if player_guess in battleship_placement:
    battleship_placement.remove(player_guess)
    ocean_table = list(ocean_table)
    ocean_table[player_guess in battleship_placement] = "X"
    print("You got a hit!")
    

else:
    print("\nYou missed the target")

    
time.sleep(1.4)

ocean_table ="".join(ocean_table)
print(ocean_table)
    
#print(battleship_placement)

I'm trying to make a really simple battleship game where the board (ocean_table) is a string that looks like a table of A-F columns and 1-6 rows of hash-marks. Then if you guess a location correctly that hash-mark flips to an X. I'm storing the battleship placements as a string or int and the int represents the list place value of that specific hash in the ocean_table. So far when I run it I only get an X placed before all of the other characters in ocean_table. Can this not be achieved using dual list place values like I'm trying to do in battleship_placement? Any help for this noob would be greatly appreciated.

  • 2
    this kind of comparison: `"A3" or 88` will always return `"A3"` (and that is a feature) because it is the first truthy value: [How do "and" and "or" act with non-boolean values?](https://stackoverflow.com/questions/47007680/how-do-and-and-or-act-with-non-boolean-values) – Matiiss Oct 15 '21 at 11:36
  • 1
    This is just not really how any of this works… You should simply have nested lists/dicts: `grid = {'A': [True, False, False, ...], ...}`. Then you can trivially access any point on the grid like `grid['A'][4]` and read or change its value. – deceze Oct 15 '21 at 11:38

1 Answers1

0

No, but your data structures don't have to mirror their displayed value exactly.

Store the ocean table as a list of lists:

ocean_table = [["#" for _ in range(6)] for _ in range(6)]

Store the ships as pairs of integers:

battleship_placement = [(0, 2), (0, 3), (0,4), (2, 1), (3,2) , (4, 3), (5, 4)]

And convert user input to the corresponding pair:

def convert(s):
    return (ord(s[0]) - ord("A"), int(s[1]) - 1)

I'll leaving using convert to update an entry in ocean_table as an exercise.

chepner
  • 497,756
  • 71
  • 530
  • 681