I've been asked for my A Level computing to create a text based hangman game. For some reason, when the "guessword" is displayed, it contains an additional character at the end, which cannot be solved, and therefore makes the game unwinnable. This only happens on a few circumstances, not every word in the list has this additional character.
Here is the python code:
import random
class Hangman():
def Playing(self):
category = raw_input("Please select a category from; EuroCapitals; PremTeams; FruitAndVeg")
again = True
while again:
guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)]
board = "*" * (len(guessword) - 1)
alreadySaid = set()
mistakes = 7
print(" ".join(board))
guessed = False
while not guessed and mistakes > 0:
whatplayersaid = raw_input("Guess a letter: ")
if whatplayersaid in guessword:
alreadySaid.add(whatplayersaid)
board = "".join([char if char in alreadySaid else "*" for char in guessword])
if board == guessword:
guessed = True
else:
mistakes -= 1
print("Nope.", mistakes, "mistakes left.")
print(" ".join(board))
again = (input("Again [y/n]: ").lower() == 'y')
Hangman().Playing()
And the list of words in "EuroCapitals.txt" is as follows:
london
paris
madrid
berlin
moscow
rome
amsterdam
bern
zagreb
stockholm
Any help would be greatly appreciated.
Most likely it's a \n
character (or maybe some extra whitespace?) from the file -- readlines()
will preserve them if they are in the file. So, you want to .rstrip()
your guessword
, e.g.:
guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)].rstrip()
As an aside, creating an anonymous file object like this generally isn't a good idea, because it won't be closed right away. You're better off using a with
statement:
with open(category + ".txt", "r") as f:
guessword = f.readlines()[random.randint(0,9)].rstrip()
and you could further refine it with
with open(category + ".txt", "r") as f:
guessword = random.choice(f.readlines()).rstrip()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다