2014-09-25 2 views
-1

Я в базовом классе программирования, и я немного застрял в этой игре. Идея заключалась в том, чтобы создать простую игру с угадыванием слов, где компьютер выбрал бы случайное слово, и вы попытаетесь угадать сначала какую-нибудь букву в слове, а затем само слово после 5 попыток. Я прошел несколько раз, и я все еще получаю сообщение об ошибке «Недопустимый синтаксис» при попытке запустить модуль. Я немного дислексичен, когда дело доходит до языков программирования, так что, возможно, есть что-то, что я пропускаю? Буду признателен, если кто-то там может предложить немного помощи!Word Guessing Game в Python?

#Word Guessing Game 
#Computer picks a random word 
#Player tries to guess it 
#computer only responds with yes or no 

import random 

tries = 0 

print "Welcome to the word game!" 
print "\nI'm going to think of a word and you have to guess it!" 
print "\nGuess which letters are in the word, then you have to guess the whole thing!" 
print "\nGood luck!" 

WORDS = ("follow", "waking", "insane", "chilly", "massive", 
     "ancient", "zebra", "logical", "never", "nice") 

word = random.choice(WORDS) 

correct = word 
length = len(word) 
length = str(length) 

guess = raw_input("The word is " + length + " letters long. Guess a letter!: ") 

while tries < 5: 
    for guess in word: 
     if guess not in word: 
      print "Sorry, try again." 
     else: 
      print "Good job! Guess another!" 

    tries = tries + 1 #* 

    if tries = 5: 
     final = raw_input ("Try to guess the word!: ") 

     if final = correct: 
      print "Amazing! My word was ", word, "!" 

     else: 
      print "Sorry. My word was ", word, ". Better luck next time!" 

raw_input("\n\nPress enter to exit") 

Следует также отметить, что проблемы, возникшие после окончания «в то время как попытки» блок, когда я попытался указать пределы «пытается» переменной. Я работал с ним раньше в случайной игре чисел, но по какой-то причине здесь это не сработало. Я был бы очень признателен за помощь! Следует также отметить, что я запускаю довольно устаревшую версию Python, некоторые версии 2.0, я считаю.

+0

что вы ожидаете 'для угадывания в слове:' делать? – njzk2

+0

@ Hodge-PodgeCrush, я очистил пробелы в OP. Убедитесь, что строка с '# *' имеет тот же отступ в вопросе, что и в вашем коде. Все остальное казалось прекрасным. – jedwards

ответ

1
tries = tries + 1 

    if tries == 5: 
     final = raw_input ("Try to guess the word!: ") 

     if final == correct: 

== Вам нужно для сравнения не =, = для задания.

Вы можете также заменить tries = tries + 1 с tries += 1

Вы также хотите переместить raw_input внутри цикла и просто попросить пользователя угадать слово вне время, когда догадки все израсходованы:

while tries < 5: 
    guess = raw_input("The word is " + length + " letters long. Guess a letter!: ") 
    if guess not in word: # use `in` to check if the guess/letter is in the word 
     print "Sorry, try again." 
    else: 
     print "Good job! Guess another!" 

    tries += 1 

# guesses are all used up when we get here 
final = raw_input ("Try to guess the word!: ") 

if final == correct: 
    print "Amazing! My word was ", word, "!" 

else: 
    print "Sorry. My word was ", word, ". Better luck next time!" 
0

попробуйте этот.

import random 

index = -1 
infi = ("python","jumble","hide","mama") 

word = random.choice(infi) 
word_len = len(word) 
guess = "" 
attempt = 0 
enter = "" 
print(word) 
temp = "_" * word_len 

print("\t\t The word chosen by computer contain", word_len,"letters.") 
print("\t Tap any letter to check if this letter is in computer word.\n") 
print("\t You got 5 attempts to check if tapped letter is in computer word.\n") 
print("\t\t\t\t GOOD LUCK!!!\n\n\n\n") 

for i in range(0, 5): 
    attempt +=1 
    guess = input("Attempt no. "+str(attempt)+":") 
    if guess in word and guess != enter: 
     for i in range(0, word_len): 
      if guess == word[i]: 
       temp = temp[:i] + guess +temp[i+1:] 
     print("yes\n" + temp) 
    if guess not in word: 
     print("no") 
    if "_" not in temp: 
     print("\t\t*********** Congratulation!! You guess the word *************") 
     break 
    elif attempt == 5: 
     guess = input("And the word is:") 
     if guess == word: 

      print("\t\t*********** Congratulation!! You guess the word *************") 
     else: 
      print("\t\t*********** WRONG!! Shame on you *************")