转弯随机选择变成一个木塔

2024-09-30 01:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python很陌生,我正在尝试制作一个刽子手游戏。我现在有一行代码是word = (random.choice(open("Level1py.txt").readline()))。你知道吗

我得到了错误'str' object does not support item assignment。你知道吗

这是我剩下的代码(抱歉搞砸了):

import random
def checkLetter(letter, word, guess_word):   
    for c in word:
        if c == letter:
            guess_word[word.index(c)] = c
            word[word.index(c)] = '*'
            print(guess_word) 
word = (random.choice(open("Level1py.txt").readline().split()))
guess_word = ['_' for x in word]
print(guess_word)
while '_' in guess_word:
    guess = input('Letter: ')
    print(checkLetter(guess, word, guess_word))

Tags: 代码intxtforreadlineindexrandomopen
2条回答

字符串在python中是不可变的。一个简单的解决方法是使用列表,列表是可变的:

st = "hello"
ls = list(st)
ls[3] = 'r'
st = ''.join(ls)
print(st)

输出

helro

编辑:下面是如何在自己的代码中实现它

import random
def checkLetter(letter, word, guess_word):
    for c in word:
        if c == letter:
            guess_word[word.index(c)] = c
            word_list = list(word)
            word_list[word.index(c)] = "*"
            word = ''.join(word_list)
            print(guess_word)
word = 'test'
guess_word = ['_' for x in word]
print(guess_word)
while '_' in guess_word:
    guess = input('Letter: ')
    print(checkLetter(guess, word, guess_word))

请注意,还有其他问题与此无关,如打印None和重复打印

您还可以使用字典解决问题:

word = "my string" #replace this with your random word
guess_word = {i: '_' for i in set(word)} # initially assign _ to all unique letters
guess_word[' '] = ' ' # exclude white space from the game
wrong_attempts = 0

while '_' in guess_word.values():
    guess = input('Letter: ')
    if guess in guess_word.keys():
        guess_word[guess] = guess
    else:
        wrong_attempts += 1
        if wrong_attempts > 11:
            break
    printable = [guess_word[i] for i in word]
    print(' '.join(printable))

if '_' in guess_word.values():
    print('you lost')
else:
    print('congratulation, you won')

相关问题 更多 >

    热门问题