私はサイコロゲームをプログラミングしています。このコード セグメントは、正しい入力 (たとえば、5+4*3/2-1) を取得し、後でプログラムがクラッシュしないようにするための入力用です。
GUIにはeasyguiを使用しています。最初は次のようなコードでした。
#possible_inputs = a list of operators (+-*/) and the values from the dices (1-6) as well as "OK, "Del" and "Reroll"
#raw_user_input = empty list
#br_value - the target value
#dice_value_list - the values from the dices
var = 0
while(var != possible_inputs.index("OK")):
var = eg.indexbox(raw_user_input, "Targetvalue: " + br_value_str, possible_inputs)
if(var != possible_inputs.index("OK")):
raw_user_input.append(possible_inputs[var])
if(var == possible_inputs.index("Del")):
raw_user_input[:] = []
if(var == possible_inputs.index("Reroll")):
#reroll dices
if(len(raw_user_input) == 0):
eg.msgbox("No input given", "ERROR")
return gui_input(dice_value_list, br_value)
for r in range(len(raw_user_input)):
if(r%2 == 0):
if(raw_user_input[r] not in dice_value_list):
eg.msgbox("Incorrect expression", "ERROR")
return gui_input(dice_value_list, br_value)
else:
if(raw_user_input[r] not in allowed_operators):
eg.msgbox("Incorrect expression", "ERROR")
return gui_input(dice_value_list, br_value)
それは問題なく機能し、入力が間違っていないため、プログラムがクラッシュすることはありませんでした。
ただし、入力を計算する関数を while ループ内に配置して、計算された式をメッセージボックスにリアルタイムでユーザーに提供できるようにする必要があります。そこで、プログラムを次のように変更しました。
input_value_calc = 0
while(var != possible_inputs.index("OK")):
var = eg.indexbox(raw_user_input, "Target value: " + br_value_str + ", current target value " + str(input_value_calc), possible_inputs)
if(var != possible_inputs.index("OK")):
raw_user_input.append(possible_inputs[var])
if(var == possible_inputs.index("Del")):
raw_user_input[:] = []
if(var == possible_inputs.index("Reroll")):
#reroll dices
br_check, values_input, input_value_calc = user_input_value_check(raw_user_input,br_value):
def user_input_value_check(raw_user_input,br_value):
if(len(raw_user_input) == 0):
eg.msgbox("No input given", "ERROR")
gui_input(dice_value_list, br_value)
for r in range(len(raw_user_input)):
if(r%2 == 0):
if(raw_user_input[r] not in dice_value_list):
eg.msgbox("Incorrect expression", "ERROR")
gui_input(dice_value_list, br_value)
else:
if(raw_user_input[r] not in allowed_operators):
eg.msgbox("Incorrect expression", "ERROR")
gui_input(dice_value_list, br_value)
#rest of the program calculates the score, which works fine
#the function returns True/False (if the input evaluates to the correct br_value), values_input (again for other functions in the program), input_value_calc (the evaluated input value)
最初に正しい入力をした場合はすべて問題ありませんが、今の問題は、間違った入力 (2 つの演算子または 2 つの値が隣り合っている、演算子で始まるなど) を与えるたびに、間違っていると表示され、与えさせてくれることです。別の入力。ただし、今回はボタンが正しく機能していません (たとえば、del を押すと、入力に「del」が追加されます)。
誰かが私にこれを手伝ってくれて本当に感謝しています! ありがとう!