挂字游戏程序

-2 投票
3 回答
565 浏览
提问于 2025-04-18 04:58

好的,我正在为我的计算机科学课程做一个期末项目,我决定做一个猜单词的游戏,因为这个游戏实现起来比较简单。我已经把所有功能都做得差不多了,除了一个问题,就是我的一些打印语句有点问题。代码在下面:

import random
import os

HANGMANPICS = ['''

        +---+
        |   |
            |
            |
            |
            |
            |
      =========== ''','''
        +---+
        |   |
        O   |
            |
            |
            |
            |
      =========== ''','''
        +---+
        |   |
        O   |
        |   |
            |
            |
            |
      =========== ''','''
        +---+
        |   |
        O   |
       /|   |
            |
            |
            |
      =========== ''','''
        +---+
        |   |
        O   |
       /|\  |
            |
            |
            |
      =========== ''','''
        +---+
        |   |
        O   |
       /|\  |
       /    |
            |
            |
      =========== ''','''
        +---+
        |   |
        O   |
       /|\  |
       / \  |
            |
            |
      =========== ''']

ANIMALS = '''cat dog fish whale otter spider snake bird dolphin tiger mouse 
      rabbit bear lion'''
CITIES = '''indianapolis chicago orlando miami denver columbus memphis oakland
     seatlle phoenix dallas detroit baltimore cincinatti'''
COUNTRIES = '''india china america japan egypt greece mexico italy canada 
        australia france brazil germany korea'''

def Countries():
    print 'Guess the name of this country'
    return COUNTRIES

def Cities():
    print 'Guess the name of this city'
    return CITIES

def Animals():
    print 'Guess the name of this animal'
    return ANIMALS

def Random():
    print 'Guess the name of this randomly chosen country, city, or animal'
    return COUNTRIES + CITIES + ANIMALS

def Welcome():
    print ('Select a category:')
    print ('1: Countries')
    print ('2: Cities')
    print ('3: Animals')
    print ('4: Random')

    choice = {"1": Countries, "2": Cities, "3": Animals, "4": Random}
    choose = raw_input()
    return choice.get(choose, Random)().split()


def getRandomword(wordlist):
    wordindex = random.randint(0, len(wordlist)-1)
    return wordlist[wordindex]

def Display(HANGMANPICS,MISSEDLETTERS,CORRECTLETTERS,SECRETWORD):
    os.system('cls')
    print(HANGMANPICS[len(MISSEDLETTERS)])
    print

    print 'Missed letters:',
    for letter in MISSEDLETTERS:
        print letter,
    print

    blanks = '_' * len(SECRETWORD)

    for i in range(len(SECRETWORD)):
        if SECRETWORD[i] in CORRECTLETTERS:
            blanks = blanks[:i] + SECRETWORD[i] + blanks[i+1:]

    for letter in blanks:
        print letter
    print

def getGuess(alreadyguessed):
    while True:
        print 'Guess a letter'
        guess = raw_input()
        guess = guess.lower()
        if len(guess) != 1:
            print 'Please enter single letters'
        elif guess in alreadyguessed:
            print 'This letter has already been guessed, please guess again'
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print 'You did not guess a letter, please guess a letter'
        else:
            return guess

def playAgain():
    print ('Do you wanna play again? (Yes or No)')
    return raw_input().lower().startswith('y')

print ('Welcome to Hangman! By Aaron Taylor')
print (HANGMANPICS[6])
words = Welcome()
MISSEDLETTERS = ''
CORRECTLETTERS = ''
SECRETWORD = getRandomword(words)

done = False

while True:
    Display(HANGMANPICS,MISSEDLETTERS,CORRECTLETTERS,SECRETWORD)
    guess = getGuess(MISSEDLETTERS + CORRECTLETTERS)

    if guess in SECRETWORD:
        CORRECTLETTERS = CORRECTLETTERS + guess
        found = True
        for i in range(len(SECRETWORD)):
            if SECRETWORD[i] not in CORRECTLETTERS:
                found = False
                break

        if found:
             print('You won the game!')
             print('The correct word was ---->' + SECRETWORD.upper())
             done = True

    else:
        MISSEDLETTERS = MISSEDLETTERS + guess
        if len(MISSEDLETTERS) == len(HANGMANPICS)-1:
            Display(HANGMANPICS,MISSEDLETTERS,CORRECTLETTERS,SECRETWORD)
            print('You did not guess the word correctly. The word was : ' + SECRETWORD)
            done = True

    if done:
        if playAgain():
            os.system('cls')
            words = Welcome()
            MISSEDLETTERS = ''
            CORRECTLETTERS = ''
            done = False
            SECRETWORD = getRandomword(words)
        else:
            break

我希望在玩家选择后,能在游戏屏幕上显示国家、城市、动物和随机选项的打印内容,但我一直没能做到。如果我把os.system('cls')这行代码去掉,打印内容就能正常显示,但这样会让程序看起来不那么美观,我希望能找到一个解决办法,让这些打印语句正常工作。谢谢大家的建议!

3 个回答

0

有两种可能性:

1) 类似于libcurses的光标放置。你可以把光标放在屏幕上的任何位置,然后打印出文本字符。我对这个的了解不多,你可能需要自己查一下,希望能找到适合Python的libcurses库。("urwid"可能会在这里派上用场)

2) 作弊的方法,如果你只需要改变你打印的最后一行,可以使用\r(回车符)。这样光标会回到行的开头,覆盖掉原来的内容。

0

试着在打印语句后面加上 sys.stdout.flush() 这个命令。

1

问题在于你在调用 os.system('cls') 之前,已经执行了 Cities()、Countries() 等函数里的打印语句。我们来看看你的代码结构:

print ('Welcome to Hangman! By Aaron Taylor')
print (HANGMANPICS[6])
words = Welcome()
MISSEDLETTERS = ''
CORRECTLETTERS = ''
SECRETWORD = getRandomword(words)

done = False

while True:
    Display(HANGMANPICS,MISSEDLETTERS,CORRECTLETTERS,SECRETWORD)

Welcome() 执行完后,它会调用相应的函数,比如 Cities()

def Cities():
    print 'Guess the name of this city'
    return CITIES

这个打印语句会被调用并显示出来,但几乎立刻,程序就会进入你的 while True 循环,这个循环会调用 Display(),而 Display() 又会立刻调用 os.system('cls'),这样就会把 Cities() 里打印的内容清除掉。这样说你明白了吗?

我觉得最好的办法是把用户的选择存储在一个变量里,然后在清屏后由 Display() 打印正确的信息。不过,这样做需要稍微调整一下你的代码。有一种比较简单的方法是根据 Welcome 函数的当前返回值来推断用户的选择。下面是我对你代码的一个小修改,我觉得这样可以达到你想要的效果:

def Display(HANGMANPICS,MISSEDLETTERS,CORRECTLETTERS,SECRETWORD, CHOICE):
    os.system('cls')
    CHOICE()
    print(HANGMANPICS[len(MISSEDLETTERS)])
    print

    print 'Missed letters:',
    for letter in MISSEDLETTERS:
        print letter,
    print

    blanks = '_' * len(SECRETWORD)

    for i in range(len(SECRETWORD)):
        if SECRETWORD[i] in CORRECTLETTERS:
            blanks = blanks[:i] + SECRETWORD[i] + blanks[i+1:]

    for letter in blanks:
        print letter
    print

def getGuess(alreadyguessed):
    while True:
        print 'Guess a letter'
        guess = raw_input()
        guess = guess.lower()
        if len(guess) != 1:
            print 'Please enter single letters'
        elif guess in alreadyguessed:
            print 'This letter has already been guessed, please guess again'
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print 'You did not guess a letter, please guess a letter'
        else:
            return guess

def playAgain():
    print ('Do you wanna play again? (Yes or No)')
    return raw_input().lower().startswith('y')

print ('Welcome to Hangman! By Aaron Taylor')
print (HANGMANPICS[6])
words = Welcome()
if words == ANIMALS:
    CHOICE = Animals
elif words == CITIES:
    CHOICE = Cities
elif words == COUNTRIES:
    CHOICE = Countries
else:
    CHOICE = Random

MISSEDLETTERS = ''
CORRECTLETTERS = ''
SECRETWORD = getRandomword(words)

done = False

while True:
    Display(HANGMANPICS,MISSEDLETTERS,CORRECTLETTERS,SECRETWORD,CHOICE)
    guess = getGuess(MISSEDLETTERS + CORRECTLETTERS)

撰写回答