gpt4 book ai didi

python - 如何修复 numpy python 文件加载/写入中的逻辑错误

转载 作者:行者123 更新时间:2023-12-01 08:02:15 26 4
gpt4 key购买 nike

我最近开始创建一款基于控制台的角色扮演游戏。

我编写了这段代码:

# MAIN GAME LOOP
while True:
if MMS == 'A': # already definied
print('Loading Story mode...')
print('[LOADING] Importing numpy')
try:
import numpy as np
except ImportError:
print('Error 01 // Cilent side')
print('ImportError')
while True:
A = 1
print('[LOADING] Trying load save...')
try:
SAVE = np.loadtxt('Savedata.dat')
MAXLIFE = SAVE[:, 0] # all of thesse already definied
LIFE = SAVE[:, 1]
MAXEN = SAVE[:, 2]
EN = SAVE[:, 3]
MAXOX = SAVE[:, 4]
OX = SAVE[:, 5]
OPOS = SAVE[:, 6]
POS = SAVE[:, 7]
CHAPTER = SAVE[:, 8]
SAVE.close()
except:
sleep(4)
print('[LOADING] No save file found or incorrect save.')
print('[LOADING] Creating a new save.')
MAXLIFE = 150
LIFE = 110
MAXEN = 150
EN = 150
MAXOX = 150
OX = 85
OPOS = 10
POS = 10
CHAPTER = 1
np.savetxt('Savedata.dat', [MAXLIFE, LIFE, MAXEN, EN, MAXOX, OX, OPOS, POS, CHAPTER])

除了如果没有保存,它会创建一个具有默认值的新保存。如果有保存,游戏就会加载它。但是,它产生了无限的输出:

[LOADING] No save file found or incorrect save.
[LOADING] Creating a new save.
Loading Story mode...
[LOADING] Importing numpy
[LOADING] Trying load save...
[LOADING] No save file found or incorrect save.
[LOADING] Creating a new save.
Loading Story mode...
...

无限循环没问题,但它没有检测到之前的保存。

位于 Savedata.dat 中

1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00

我做错了什么?谢谢!

最佳答案

正如 hpaulj 所说,不要使用裸露的 except。我将其重写为:

except Exception as e:
print(e)

(我知道,仅捕获异常也很糟糕)它会打印出以下内容:

Traceback (most recent call last):
File "wakagame.py", line 21, in <module>
MAXLIFE = SAVE[:, 0] # all of thesse already definied
IndexError: too many indices for array

问题是您正在尝试选择列:

MAXLIFE = 保存[:, 0]

不是来自矩阵,而是来自平均一维数组:

np.savetxt('Savedata.dat', [MAXLIFE, LIFE, MAXEN, EN, MAXOX, OX, OPOS, POS, CHAPTER])

您应该将所有这些行替换为如下行:

MAXLIFE = 保存[0]

(另请注意,SAVE 是一个 numpy 数组,而不是文件,因此 SAVE.close() 将返回错误。您应该删除此行)

关于python - 如何修复 numpy python 文件加载/写入中的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55677884/

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