gpt4 book ai didi

Python csv file not printing properly, for Text Based Game(对于基于文本的游戏,无法正确打印Python CSV文件)

转载 作者:bug小助手 更新时间:2023-10-28 21:33:06 26 4
gpt4 key购买 nike



So creating this text based game, currently just sorting out some fundamentals, when printing out the classes stats the knight class prints out totally fine but the mage class for some reason prints out two physical damage stats. This is my code.

所以创建这个基于文本的游戏,目前只是整理了一些基础知识,当打印出职业属性时,骑士职业打印得很好,但由于某种原因,法师职业打印出了两个物理伤害统计数据。这是我的密码。


import csv


class Character:

health = 0
physicalDamage = 0
rangedDamage = 0
magicDamage = 0
defense = 0

inventoryMax = 25
inventoryList = []

def __init__(self, name, role):
self.name = name
self.role = role

def ClassPicker():
print('Select Your Class')
with open('./tables/classes.csv', 'r') as classes:
classes = list(csv.reader(classes))
classStats = classes[0]
classes.pop(0)
while True:
for row in classes:
print(f'[{classes.index(row)+1}]{row[0]}')
inspect = int(input('')) - 1
for x in classes[inspect]:
if classes[inspect].index(x) >= 2:
print(f'{classStats[classes[inspect].index(x)]}: {x}')
else:
print(x)
print('Are You Sure You Want To Select This Class')
print('[yes] [no]')
confirm = input('').lower()
if confirm == 'no':
print('Select Your Class')
elif confirm == 'yes':
print(classes[0])
chosenClass = classes[0]
break
else:
print('Enter A Valid Option')

# One Time Class Stat Setting
Character.role = chosenClass[0]
Character.health = chosenClass[2]
Character.physicalDamage = chosenClass[3]
Character.rangedDamage = chosenClass[4]
Character.magicDamage = chosenClass[5]
Character.defense = chosenClass[6]


if __name__ == '__main__':
Character.name = input('what is your name? ')
print(f'Your Name Is {Character.name}?')
while True:
print('[yes] [no]')
confirm = input().lower()
if confirm == 'no':
Character.name = input('what is your name? ')
print(f'Your Name Is {Character.name}?')
elif confirm == 'yes':
break
else:
print('Enter A Valid Option')
ClassPicker()

the csv file used

使用的CSV文件


any help is massively appreciated and any ideas or suggestions go a long way <3

我们非常感谢任何帮助,任何想法或建议都大有裨益<3


it should print
Mage
Highly intelligent, with an affinity towards magic. The Mage prefers to sit at range casting spells.
Health: 80
Physical Damage: 5
Ranged Damage: 5
Magic Damage: 20
Defense: 2

它应该打印出高度智能的法师,对魔法有一种亲和力。法师更喜欢坐在远程施法的位置上。生命值:80点物理伤害:5点远程伤害:5点魔法伤害:20点防御:2点


But instead it prints like this
Mage
Highly intelligent, with an affinity towards magic. The Mage prefers to sit at range casting spells.
Health: 80
Physical Damage: 5
Physical Damage: 5
Magic Damage: 20
Defense: 2

相反,它印出了像这位法师一样的高度智能,与魔法有一种亲和力。法师更喜欢坐在远程施法的位置上。生命值:80点物理伤害:5点物理伤害:5点魔法伤害:20点防御:2点


The knight class prints correctly and uses the exact same code so I genuinely dont understand

Knight类打印正确,并且使用完全相同的代码,所以我真的不明白


更多回答

Maybe you should redesign your code first. You have a class Character and according to the existence of the __init__ method you want to create instances of it. But you never do that. You just use the class as a namespace. And while you're working on that you might want to read the Style Guide for Python Code and change the names of your variables. At the moment your code is hard to read for an experienced Python developer.

也许你应该先重新设计你的代码。您有一个类字符,并且根据__init__方法的存在,您想要创建它的实例。但你从来没这么做过。您只需将类用作命名空间。在此过程中,您可能需要阅读《Python代码样式指南》,并更改变量的名称。目前,对于经验丰富的Python开发人员来说,您的代码很难阅读。

Please give a downloadable CSV, not a screenshot. StackOverflow is helpful, but it's a lot to ask people to retype your data files...

请提供一个可下载的CSV,而不是截图。StackOverflow是有帮助的,但要求人们重新输入您的数据文件太多了……

优秀答案推荐

            elif confirm == 'yes':
print(classes[0])
chosenClass = classes[0]
break

this always selects the same index (Knight) as the chosen class.

also, use csv.DictReader can you can clean up all the confusing index notation.

这始终选择与所选类别相同的索引(骑士)。此外,使用csv.DictReader可以清理所有令人困惑的索引表示法。


def ClassPicker():
print('Select Your Class')
with open('data.csv', 'r') as classes:
classes = list(csv.DictReader(classes))
while True:
for i, row in enumerate(classes, 1):
class_name = row['Class']
print(f'[{i}]{class_name}')
inspect = int(input('')) - 1
for key, val in classes[inspect].items():
print(f'{key}: {val}')
print('Are You Sure You Want To Select This Class')
print('[yes] [no]')
confirm = input('').lower()
if confirm == 'no':
print('Select Your Class')
elif confirm == 'yes':
print(classes[inspect])
chosenClass = classes[inspect]
break
else:
print('Enter A Valid Option')

# One Time Class Stat Setting
Character.role = chosenClass['Class']
Character.health = chosenClass['Health']
Character.physicalDamage = chosenClass['Physical Damage']
Character.rangedDamage = chosenClass['Ranged Damage']
Character.magicDamage = chosenClass['Magic Damage']
Character.defense = chosenClass['Defense']


The problem is at the line:

问题出在前线:


print(f'{classStats[classes[inspect].index(x)]}: {x}')

Notice in your data, the class Mage has the same Physical Damage with Ranged Damage (both are 5). So the program run classes[inspect].index(5) twice, which prints Physical Damage twice.

请注意,在你的数据中,法师职业拥有与远程伤害相同的物理伤害(两者都是5)。因此,该程序运行了两次CLASS[Inspect].index(5),这将打印两次物理损坏。


My opinion for fix is replacing this block of code:

我对FIX的看法是替换这段代码:


for x in classes[inspect]:
if classes[inspect].index(x) >= 2:
print(f'{classStats[classes[inspect].index(x)]}: {x}')
else:
print(x)

with a simple dict created from the zip function:

使用从ZIP函数创建的简单DICT:


for k, v in dict(zip(classStats, classes[inspect])).items():
if k in ("Class", "Description"):
print(v)
else:
print(f"{k}: {v}")


And it should print the thing you want.

而且它应该打印出你想要的东西。



This sounds like a fun project! There's a few things you were doing that are a little bit unconventional in Python. For example, modifying class variables on the Character class instead of creating an instance of that class.. I took a stab at refactoring your code to be more Pythonic.

这听起来像是一个有趣的项目!在Python中,您正在做的一些事情有点不符合常规。例如,修改Character类的类变量,而不是创建该类的实例。我试着重构您的代码,使其更具毕达式风格。


I've separated the logic out into smaller functions, we're now using csv.DictReader and we're instantiating a new Character() instead of modifying the class itself.

我已经将逻辑分离成更小的函数,我们现在使用csv.DictReader,并且我们实例化一个新的字符(),而不是修改类本身。


As a further enhancement, you might check whether a dataclass would be a good fit for your Character.

作为进一步的增强,您可以检查数据类是否适合您的角色。


import csv

class Character:

def __init__(
self,
name,
character_class,
health,
physical_damage,
ranged_damage,
magic_damage,
defense,
inventory_max=25,
**_kwargs,
):
self.name = name
self.character_class = character_class
self.health = health
self.physical_damage = physical_damage
self.ranged_damage = ranged_damage
self.magic_damage = (defense,)
self.inventory_max = inventory_max
self.inventory_list = []

def __str__(self):
return f'<Character: {self.name} ({self.character_class})>'

def load_classes(filename='./classes.csv'):
# Close the file after we're done with it. We don't need to keep it
# open while waiting for the user the make their choice.
with open(filename, 'r') as class_file:
return list(csv.DictReader(class_file))

def get_user_input(message, valid_choices):
while True:
print(message)
user_response = input()
if user_response in valid_choices:
return user_response
else:
print(f'Invalid choice, please enter one of {valid_choices}')


def confirm(player_resp):
if player_resp in ('y', 'yes'):
return True
elif player_resp in ('n', 'no'):
return False
else:
raise ValueError('Invalid input')


def pick_class(list_of_class_dicts):
while True:
for index, class_dict in enumerate(list_of_class_dicts, start=1):
print(f"{index}) {class_dict['character_class']}: {class_dict['description']}")

player_resp = get_user_input(
'Select Your Class?',
valid_choices=[str(i) for i in range(1, len(list_of_class_dicts) + 1)],
)
selected = list_of_class_dicts[int(player_resp) - 1]
for key, value in selected.items():
print(f'{key}: {value}')
player_confirms = confirm(
get_user_input(
'Are You Sure You Want To Select This Class?\n[yes] [no]',
valid_choices=('yes', 'y', 'no', 'n'),
)
)
if player_confirms:
return selected


def build_character(available_classes):
while True:
player_name = input('what is your name? ')
print(f'Your Name Is {player_name}?')
selected_class = pick_class(available_classes)
character = Character(player_name, **selected_class)
print('Your character is...')
print(character)
player_accepts = confirm(
get_user_input(
'Are you happy with this choice?\n[yes] [no]',
valid_choices=('yes', 'y', 'no', 'n'),
)
)
if player_accepts:
return character

if __name__ == '__main__':
available_classes = load_classes()
character = build_character(available_classes)

With this CSV file:

使用此CSV文件:


character_class,description,health,physical_damage,ranged_damage,magic_damage,defense
Mage,a wizard is never late,100,4,0,8,5
Knight,good night,150,10,2,0,10

更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com