所以我想做一個hang子手遊戲。我有一個函數可以將你想猜測的單詞轉換爲下劃線。所以,如果你的話是房子你最終:_ _ _ _ _
如何替換python中的特定字符?
然後,我有另一個功能,將該單詞中的每個字符添加到數組中。我有一個功能,可以讓你猜測,如果猜測是不正確的,它會從你身上帶走生命(我正在使用生命系統,同時找出如何實現hang子手的繪製),並將錯誤的字母添加到一個空陣列。我的程序還會檢查您是否輸入了任何不是字母或字母不重複的字符。
我唯一的問題是,我想不出一種告訴計算機的方式,如果字母在單詞中,它應該切換你的猜測字母的空白空間。所以說,如果你的話是房子,你猜字母h它應該返回:
h _ _ _ _
如果我使用替換功能,它取代了正確的字母每一個下劃線。對我能做什麼有任何建議?
這裏是我的代碼:
import random
category = [('sports', 1), ('video games', 2), ('movies', 3)]
sports = ('football', 'baseball', 'basketball')
video_games = ('counter strike', 'doom', 'wolfenstein')
movies = ('star wars', 'indiana jones', 'lord of the rings')
def pick_category():
print("For sports type 1, for video games type 2, for movies type 3")
choice = int(input("Choose a category: "))
if choice == 1:
word = random.choice(sports)
elif choice == 2:
word = random.choice(video_games)
elif choice == 3:
word = random.choice(movies)
else:
print("Invalid input")
return word
word = pick_category()
def convert_spaces(): #Turns every letter in the word into an empty space
spaces = word
for i in range(0, len(word)):
if ord(word[i]) != 32:
spaces = spaces.replace(word[i], '_ ')
print(spaces)
return spaces
convert_spaces()
def word_list(): # Appends every letter of the word into an array
array = []
for i in range(0, len(word)):
array.append(word[i])
print(array)
return array
def guess():
array = []
lives = 9
while lives != 0:
n = input("Guess a letter ").lower()
if ord(n) in range(96, 123):
if n in array:
print("That letter is already in use.")
elif n not in word and n not in array:
array.append(n)
lives = lives - 1
else:
print("Invalid input, try again")
convert_spaces()
print("Used letters: ", array)
print("Life counter: ", lives)
return array
guess()
請發表您的代碼 –
[Python替換字符串]的可能重複(http://stackoverflow.com/questions/32978542/python-replacing-string) –
另請參閱:http://stackoverflow.com/search?tab =相關性&q = python%20hangman –