猜猜python中的单词游戏-如何屏蔽单词(例如-----)
我正在用python写一个猜字游戏。这是为了我的学校项目。我差不多做完了,我只是有一件事有点问题。我想不出如何掩饰一个词。例如,如果单词是monkey,程序应该显示-,当用户猜测一个字母时,比如说k,程序应该显示-,k- 不幸的是,我必须以某种方式编写代码。我应该有一个主函数,它将调用其他函数,这些函数将完成所有的工作,比如要求用户输入一个字母或检查猜测的单词是否正确。我已经完成了所有的功能,除了这个掩蔽功能 该函数称为maskWordstate、word、guess。我必须保留这些变量,但它们将被传递给函数。state是隐藏的单词,例如--,word是要猜测的单词,例如monkey和guess是用户猜测的字母。函数更新屏蔽字后,应返回状态。另一条规则是我不能创建全局变量。传递的变量是必须使用的变量 以下是我所拥有的:猜猜python中的单词游戏-如何屏蔽单词(例如-----),python,Python,我正在用python写一个猜字游戏。这是为了我的学校项目。我差不多做完了,我只是有一件事有点问题。我想不出如何掩饰一个词。例如,如果单词是monkey,程序应该显示-,当用户猜测一个字母时,比如说k,程序应该显示-,k- 不幸的是,我必须以某种方式编写代码。我应该有一个主函数,它将调用其他函数,这些函数将完成所有的工作,比如要求用户输入一个字母或检查猜测的单词是否正确。我已经完成了所有的功能,除了这个掩蔽功能 该函数称为maskWordstate、word、guess。我必须保留这些变量,但它们
def maskWord(state, word, guess)
guessed = []
guessed.append(guess)
for guess in word:
if guess in guessed:
state += guess
else: state += "-"
return state
这真的不管用。因为调用此函数的主函数是while循环,所以每次猜测都会变成一个空字符串
如果有人能帮我,我会非常感激的。我知道必须能够只使用变量编写此函数,因为我的老师只允许使用这些变量。修复了我的答案以反映注释,它比kjtl的答案要短一些。但它基于相同的概念,通过使用状态作为。。。那么现在的状态,
def maskWord(state, word, guess):
state = list(state)
for i in range(len(word)):
if word[i] == guess:
state[i] = guess
return "".join(state)
# Lets test if it works..:
word = "electricity"
state = "-" * len(word)
tries = 0
play = True
while play:
if tries == len(word)*2:
print "Fail...";
play = False
guess = raw_input("Guess: ")
tries +=1
state = maskWord(state, word, guess)
print state
if maskWord(state, word, guess) == word:
print "WIN, WIN!!";
play = False
修正了我的答案以反映评论,它比kjtl的答案要短一些。但它基于相同的概念,通过使用状态作为。。。那么现在的状态,
def maskWord(state, word, guess):
state = list(state)
for i in range(len(word)):
if word[i] == guess:
state[i] = guess
return "".join(state)
# Lets test if it works..:
word = "electricity"
state = "-" * len(word)
tries = 0
play = True
while play:
if tries == len(word)*2:
print "Fail...";
play = False
guess = raw_input("Guess: ")
tries +=1
state = maskWord(state, word, guess)
print state
if maskWord(state, word, guess) == word:
print "WIN, WIN!!";
play = False
通过使用状态作为有效猜测的容器,扩展了SLACKY的答案
def maskWord(state, word, guess):
result = ''
guessed = []
character = ''
for character in state:
if not character == '-':
if not character in guessed:
guessed.append(character)
if not guess in guessed:
guessed.append(guess)
for guess in word:
if guess in guessed:
result += guess
else:
result += "-"
# for debugging change to if True:
if False:
print 'state %s' % state
print 'word %s' % word
print 'guess %s' % guess
print guessed
return result
# Lets test if it works..:
import sys
word = "electricity"
state = ""
tries = 0
loop = True
while loop:
if tries == len(word)*3:
print "Fail..."
loop = False
else:
guess = raw_input("Guess: ")
tries +=1
state = maskWord(state, word, guess)
print state
if maskWord(state, word, guess) == word:
print "WIN, WIN!!"
loop = False
通过使用状态作为有效猜测的容器,扩展了SLACKY的答案
def maskWord(state, word, guess):
result = ''
guessed = []
character = ''
for character in state:
if not character == '-':
if not character in guessed:
guessed.append(character)
if not guess in guessed:
guessed.append(guess)
for guess in word:
if guess in guessed:
result += guess
else:
result += "-"
# for debugging change to if True:
if False:
print 'state %s' % state
print 'word %s' % word
print 'guess %s' % guess
print guessed
return result
# Lets test if it works..:
import sys
word = "electricity"
state = ""
tries = 0
loop = True
while loop:
if tries == len(word)*3:
print "Fail..."
loop = False
else:
guess = raw_input("Guess: ")
tries +=1
state = maskWord(state, word, guess)
print state
if maskWord(state, word, guess) == word:
print "WIN, WIN!!"
loop = False
也许这可以帮助你:
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,
'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10,
'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 }
def load_words():
print "Loading word list from file..."
# making the file
words_file= open("N:\Problem Set 1\words.txt", 'r', 0)
# makeing the wordlist
words = []
for line in words_file:
words.append(line.strip().lower())
print " ", len(words), "words loaded."
return words
def get_frequency_dict(sequence):
# freqs: dictionary (element_type -> int)
frequencies = {}
for x in sequence:
frequencies[x] = frequencies.get(x,0) + 1
return frequencies
# -----------------------------------
def get_word_score(word, n):
output = 0
# Checking wether the later is in the list
for letter in word:
output = output + SCRABBLE_LETTER_VALUES.get(letter)
output = output * len(word)
if len(word) == n:
output = output + 50
if output < 0:
print "Thats is a negative value!"
return output
def display_hand(hand):
# Displaying the hand
for letter, frequency in hand.items():
for i in range(frequency):
print letter,
print '\n'
def deal_hand(n):
hand={}
number_vowels = n / 3
for i in range(number_vowels):
z = VOWELS[random.randrange(0,len(VOWELS))]
hand[z] = hand.get(z, 0) + 1
for i in range(number_vowels, n):
z = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[z] = hand.get(z, 0) + 1
return hand
# Updating the hand
def update_hand(hand, word):
for letter in word:
if hand[letter] != 0:
hand[letter] = hand.get(letter, 0) - 1
return hand
#If letter chosen is in hand then append
def is_valid_word(word, hand, words_file):
handchosen = dict.copy(hand)
first_hand =[]
second_hand = []
for letter in handchosen.keys():
for f in range(handchosen[letter]):
first_hand.append(letter)
for letter in word:
for s in handchosen:
if s == letter and handchosen[letter] != 0:
handchosen[letter] = handchosen.get(letter, 0) - 1
for letter in handchosen.keys():
for f in range(handchosen[letter]):
second_hand.append(letter)
if words_file.count(word) > 0 and len(word) + len(second_hand) == len(first_hand):
return True
else:
return False
# Play the hand
def play_hand(hand, words_file):
print
print
print 'Hey welcome to the Wordgame!'
print
print "Press '.' when you want to end the game."
print
n = HAND_SIZE
old_hand = hand.copy()
print 'Initial hand:',
display_hand(hand)
print
loop = 1
while loop == 1:
yourscore = 0
numLetters = 1
while numLetters > 0:
quit = '.'
word = raw_input('Please enter a valid word: ')
if word != quit:
if is_valid_word(word, hand, words_file) == False:
print 'Invalid word. Please enter a valid word:'
else:
numLetters = 1
print 'You got points for:',word,'=',get_word_score(word, n)
yourscore = yourscore + get_word_score(word, n)
print 'The total score:', yourscore
updated_hand = update_hand(hand, word)
print 'Current Hand:',
display_hand(updated_hand)
print
hand = updated_hand
for num in dict.values(hand):
numLetters = num + numLetters
numLetters = numLetters - 1
print numLetters,'letters are still remaining.'
if numLetters == 0:
loop = 0
print
else:
numLetters,loop = 0,0
print 'Lets see what the final score is: ', yourscore
#Play the game
def play_game(words_file):
hand = deal_hand(HAND_SIZE) # random init
while True:
# Let the user make a choice
A = raw_input('Enter n to deal a new hand, r to play the same hand or e to end game: ')
if A == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), words_file)
old_hand = hand.copy()
print
# User can take the same hand
elif A == 'r':
play_hand(old_hand, words_file)
# Break
elif A == 'e':
break
else:
print "That is a invalid command."
if __name__ == '__main__':
words_file = load_words()
play_game(words_file)
也许这可以帮助你:
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,
'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10,
'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 }
def load_words():
print "Loading word list from file..."
# making the file
words_file= open("N:\Problem Set 1\words.txt", 'r', 0)
# makeing the wordlist
words = []
for line in words_file:
words.append(line.strip().lower())
print " ", len(words), "words loaded."
return words
def get_frequency_dict(sequence):
# freqs: dictionary (element_type -> int)
frequencies = {}
for x in sequence:
frequencies[x] = frequencies.get(x,0) + 1
return frequencies
# -----------------------------------
def get_word_score(word, n):
output = 0
# Checking wether the later is in the list
for letter in word:
output = output + SCRABBLE_LETTER_VALUES.get(letter)
output = output * len(word)
if len(word) == n:
output = output + 50
if output < 0:
print "Thats is a negative value!"
return output
def display_hand(hand):
# Displaying the hand
for letter, frequency in hand.items():
for i in range(frequency):
print letter,
print '\n'
def deal_hand(n):
hand={}
number_vowels = n / 3
for i in range(number_vowels):
z = VOWELS[random.randrange(0,len(VOWELS))]
hand[z] = hand.get(z, 0) + 1
for i in range(number_vowels, n):
z = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[z] = hand.get(z, 0) + 1
return hand
# Updating the hand
def update_hand(hand, word):
for letter in word:
if hand[letter] != 0:
hand[letter] = hand.get(letter, 0) - 1
return hand
#If letter chosen is in hand then append
def is_valid_word(word, hand, words_file):
handchosen = dict.copy(hand)
first_hand =[]
second_hand = []
for letter in handchosen.keys():
for f in range(handchosen[letter]):
first_hand.append(letter)
for letter in word:
for s in handchosen:
if s == letter and handchosen[letter] != 0:
handchosen[letter] = handchosen.get(letter, 0) - 1
for letter in handchosen.keys():
for f in range(handchosen[letter]):
second_hand.append(letter)
if words_file.count(word) > 0 and len(word) + len(second_hand) == len(first_hand):
return True
else:
return False
# Play the hand
def play_hand(hand, words_file):
print
print
print 'Hey welcome to the Wordgame!'
print
print "Press '.' when you want to end the game."
print
n = HAND_SIZE
old_hand = hand.copy()
print 'Initial hand:',
display_hand(hand)
print
loop = 1
while loop == 1:
yourscore = 0
numLetters = 1
while numLetters > 0:
quit = '.'
word = raw_input('Please enter a valid word: ')
if word != quit:
if is_valid_word(word, hand, words_file) == False:
print 'Invalid word. Please enter a valid word:'
else:
numLetters = 1
print 'You got points for:',word,'=',get_word_score(word, n)
yourscore = yourscore + get_word_score(word, n)
print 'The total score:', yourscore
updated_hand = update_hand(hand, word)
print 'Current Hand:',
display_hand(updated_hand)
print
hand = updated_hand
for num in dict.values(hand):
numLetters = num + numLetters
numLetters = numLetters - 1
print numLetters,'letters are still remaining.'
if numLetters == 0:
loop = 0
print
else:
numLetters,loop = 0,0
print 'Lets see what the final score is: ', yourscore
#Play the game
def play_game(words_file):
hand = deal_hand(HAND_SIZE) # random init
while True:
# Let the user make a choice
A = raw_input('Enter n to deal a new hand, r to play the same hand or e to end game: ')
if A == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), words_file)
old_hand = hand.copy()
print
# User can take the same hand
elif A == 'r':
play_hand(old_hand, words_file)
# Break
elif A == 'e':
break
else:
print "That is a invalid command."
if __name__ == '__main__':
words_file = load_words()
play_game(words_file)
匹配时需要一个退出条件。另一个规则是我不能创建全局变量。不需要全局变量,只需创建一个主函数或其他函数。不应该state=.join[-for x in rangelenword]be state=-*lenword?谢谢。这两个答案都很好,但我更喜欢你的答案,因为它又好又短:我只是不明白state=liststate的作用,你能给我解释一下吗,谢谢。匹配时需要一个退出条件。另一个规则是我不能创建全局变量。没有任何东西需要全局,只需创建一个主函数或其他函数。state=.join[-for x in rangelenword]不应该是state=-*lenword吗?谢谢。两个答案都很好,但我更喜欢你的答案,因为它又好又短:我只是不明白state=liststate是做什么的,你能给我解释一下吗,谢谢。啊,你赢了我!:啊,你赢了我!: