I made a baseball game, but I can't find the error.

Asked 2 years ago, Updated 2 years ago, 112 views

I made it like below, and it works well to the first function that prevents duplicate numbers.

For example, if you enter 123 and you have at least one strike, If you repeatedly enter 123 several times, the strike will increase by yourself and the game will end... Similarly, when 456 is entered, if 0 strike 1 ball is entered repeatedly, the ball continues to increase, and

I don't know where the error came from Do you know?

import random

answer = random.sample(range(1,10),3)

tr_num = 0
st_num = 0
bl_num = 0


def same_num():
    if (num[0] == num[1] == num[2]) or (num[0] == num[1]) or (num[0] == num[2]) or (num[1] == num[2]):
        result = False

    else:
        result = True

    return result


def det_num(a, b):
    for i in range(0, 3):
        for j in range(0, 3):
            if (num[i] == str(answer[j]) and i == j):
                a += 1
            elif (num[i] == str(answer[j]) and i != j):
                b += 1
            else:
                continue

    return a, b


print("Game Start")
while (1):
    num = (input("Input Num"))
    same_num()

    if same_num() == False:
        print("Duplicated numbers". Please re-enter.")
        continue

    st_num, bl_num = det_num(st_num, bl_num)

    print(st_num, "strike", bl_num, "ball")
    tr_num += 1

    if st_num == 3:
        break

print(tr_num), "You succeeded in your first attempt.")

python python-exception error baseball-game

2022-09-22 20:10

2 Answers

I don't know what it means to say, "When you input 123, if you have at least one strike, you have to type 123 over and over again."

Can you give me a specific example? For example,

If you enter 123 several times, ~ should be output. But in my code, I get ~, like


2022-09-22 20:10

When calling det_num, st_num and bl_num are passed by parameters The initialization of these two variables is outside of the while statement. So I reset the program only once when it first runs, and after that, The previous value is stored and handed over to the parameter.

However, there is no initialization within the function, so it continues to be added to the previous results... Before calling a function, or inside the function I think we can reset the variable to zero...

And I don't know why you essentially pass those two variables to a function. In fact, the det_num function can work without any parameters...

Anyway, take care of it....

st_num, bl_num = det_num(st_num, bl_num)
def det_num(a, b):
    for i in range(0, 3):
        for j in range(0, 3):
            if (num[i] == str(answer[j]) and i == j):
                a += 1
            elif (num[i] == str(answer[j]) and i != j):
                b += 1
            else:
                continue

    return a, b


2022-09-22 20:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.