I am making a simple battleship game with a computer for singleplayer mode. I don't want the bot to guess in the same place as it has already guessed. I have been trying to use .txt files as "logs" for old guesses, convert them to a list and then run through them with a "for" statement. The problem I am having is detecting when the entire file had NOT got the coordinates it has guessed. Is there a better way of doing this?
Here is the code WITHOUT detection for un-guessed guesses
import random
f = open("guesses.txt", "w")
guessing = True
while guessing == True:
guess = random.sample(range(0, 4)2)
f = open("guesses.txt", "r")
f = f.readlines()
for i in f:
if guess == i:
break
Thank-You so very much in advance Files look like this:
[2, 3]
[3, 2]
[3, 0]
[1, 4]
[4, 3]
CodePudding user response:
From what I’m getting, you could simply do something like this:
with open("yourfile.txt", "r") as file:
contents = file.read()
if str(my_guess) in contents:
print("The guess is not unique")
else:
print("The guess is unique")
CodePudding user response:
Is there a better way of doing this?
If I were writing a battleship game, I would either keep a list of guesses or a 2D array with guesses marked. I wouldn't bother with a file at all.
Files are intended for more permanent storage. For example, if you want to save a game and continue it later. They don't make sense for keeping track of the state of the game as you play it.