当我运行python文字游戏时,出现属性错误,我不知道如何解决

时间:2018-06-27 19:25:49

标签: python

对于我的第一个python项目,我决定进行一次文字游戏冒险,但是偶然发现了一个我真的不知道如何解决错误的错误:

错误:

Traceback (most recent call last):
File "C:\Users\Sekou\Documents\school simulator game\aloysiusgame.py", line 248, in <module>
myPlayer.gender = player_gender
AttributeError: 'str' object has no attribute 'gender'         

代码:

question2 = "ben je een meisje of jongen?\n"
for character in question2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
player_gender = input("> ")
valid_anwsers = ["meisje", "jongen"]
myPlayer.gender = player_gender
    print("Je bent een " + player_gender + "!\n")
    while player_gender.lower() not in valid_anwsers:
player_gender = input("> ")
if player_gender.lower() in valid_anwsers:
    myPlayer.gender = player_gender
    print("Je bent een " + player_gender + "!\n")
pass

编辑我定义播放器的部分:

import cmd
import textwrap
import sys
import os
import time
import random

screen_width = 100

##### player setup #####
class player:
def __init__(self):
        self.name = ''
        self.gender = ''
        self.classyear4 = ''
        self.sociaal = 0
        self.educatie = 0
        self.emoties = 0
        self.location = 'c16'
        self.game_over = False
        myPlayer = player()

1 个答案:

答案 0 :(得分:0)

我想这是你想做的事,希望对你有帮助

myPlayer = {}
questions ={'name':None, 'age':None, 'gender':['man', 'woman']}


for question, valid_answers  in questions.items():
    correct = False
    error_msg =""

    if valid_answers == None:
        answer = input(question + '\n>')
        myPlayer[question] = answer
    else:
        while correct == False:
            answer = input(error_msg+question+'\n>')
            if answer.strip().lower() in valid_answers:
                myPlayer[question] = answer
                correct = True
            else:
                error_msg = ("Your answer is invalid \n")

for key, value in myPlayer.items():
    print("{}:{}".format(key, value))