python - 简单的重复水平系统
问题描述
尝试构建一个简单的升级系统原型,您可以在其中添加或减去 xp,每次用户升级需要再次升级的 xp 应该增加 100,并且用户 xp 应该返回并保持任何超过所需数量的 xp。到目前为止,所有这些事情都提到了某种工作,但似乎如果我通过几个级别的程序中断,我没有收到任何错误,这可能是一个简单的修复,但我被卡住了。
level = 0
next_level = 100
current_xp = 0
xp_to_next_level = 100
runtest = True
levelup = True
while runtest:
xp_added = int(input('Add xp: '))
current_xp = current_xp + xp_added
if current_xp < next_level:
xp_to_next_level = next_level - current_xp
print('Your level is '+str(level))
print('Your current xp is '+str(current_xp))
print('Xp to next level is '+str(xp_to_next_level))
print()
continue
while levelup:
if current_xp >= next_level:
print('Level Up!')
print()
level = level + 1
current_xp = current_xp - next_level
next_level = 100 * (level + 1 )
xp_to_next_level = next_level - current_xp
print('Your level is '+str(level))
print('Your current xp is '+str(current_xp))
print('Xp to next level is '+str(xp_to_next_level))
print()
continue
else:
levelup = False
解决方案
如果您正在寻找其他方法来改进您的代码,模块化通常是一个大问题
# a function which returns the amount of xp needed to pass a level
def xp_per_level(level):
return (level + 1) * 100
# a function which wraps around the xp and changes the level
def update_level(xp, level):
while xp >= xp_per_level(level):
xp -= xp_per_level(level)
level += 1
while xp < 0:
level -= 1
xp += xp_per_level(level)
return xp, level
level = 0
xp = 0
while True:
xp += int(input('enter change in xp: '))
# since update_level returns two values, we need to "unpack" both here
xp, level = update_level(xp, level)
这使您可以将逻辑分成清晰的函数,并更好地控制通过一个级别所需的 xp 量。在上面的示例中,玩家在达到 100xp 后从级别 0 移动到 1,并在 200xp 时从 1 移动到 2,依此类推。
希望它有助于提供一种替代结构,即使逻辑几乎相同:)
编辑:添加xp_to_next_level
功能
def xp_to_next_level(xp, level):
# this works by subtracting the current xp from max xp for that level
return xp_per_level(level) - xp
推荐阅读
- android - 在android中通过网络发送消息
- php - 如何使用 PHP 从表单在同一项目中发送 PUT 请求
- javascript - this.value 和 $(this).val() 有什么区别?
- mysql - 如何创建存储过程并在预定时间运行它(在 MYSQL 中)
- javascript - 为什么 Edge 中的 sessionStorage 与 Firefox/Chrome 不同,我该如何更改?
- python - 字典中字符串值的总和
- c - redis中run_with_period c宏背后的确切语法或规范是什么
- javascript - 比较日期时间与当前日期时间
- javascript - 将字符串转换为标准矩格式
- android - 用户不选择图像时出现错误如何解决