战舰游戏已选方格跟踪程序开发需求咨询
Battleship Square Tracker Solution
Got it, let's build that battleship tracker you need! This Python program will keep track of every square you've guessed, and give the right feedback each time you input a coordinate.
How it works:
- We'll use a set to store already guessed coordinates—sets are perfect here because checking if an item exists is super fast.
- The program will keep asking for guesses until you enter an empty line.
- For each guess:
- If it's a new square, we add it to our set and print "Hit".
- If you've already guessed it, we print the reminder message.
Full Code:
# Initialize an empty set to track guessed squares guessed_squares = set() while True: # Get user input, strip any leading/trailing whitespace guess = input("Guess: ").strip() # Exit the loop if input is empty if not guess: break # Check if the square has been guessed before if guess in guessed_squares: print("You've chosen that square already") else: guessed_squares.add(guess) print("Hit")
Example Run:
Guess: A3 Hit Guess: B5 Hit Guess: A3 You've chosen that square already Guess: (empty line, program stops)
This is simple but effective—no fancy stuff, just exactly what you asked for. You can tweak the input prompt if you want, but the core logic stays solid.
内容的提问来源于stack exchange,提问作者Student
相关产品推荐
相关产品推荐

