简体   繁体   English

我的代码有什么问题? Python。 尝试制作游戏列表游戏

[英]What is wrong with my code? Python. Trying to make a gamelist game

I am learning python and want to learn from my mistake instead of just look at the course answer to this task.我正在学习 python 并希望从我的错误中吸取教训,而不是仅仅看这个任务的课程答案。

I am trying to make a gamelist game.我正在尝试制作游戏列表游戏。 We have a list gamelist = [1,2,3] and the user will then get the opportunity to change a value in the list.我们有一个列表 gamelist = [1,2,3],然后用户将有机会更改列表中的值。 The user will be able to choose between 0-2 (index position in the list) and after the user will be able to input a value.用户将能够在 0-2(列表中的索引位置)之间进行选择,之后用户将能够输入一个值。 After this iteration, the gamelist will update.在此迭代之后,游戏列表将更新。

My problem:我的问题:

  • I am able to change index position 2 and 1 but not 0.我可以更改索引位置 2 和 1 但不能更改 0。
  • And I can do it in the sequence [2][1] but I cant change the gamelist if I got the other way around.我可以按照 [2][1] 的顺序进行,但如果我反过来,我就无法更改游戏列表。

Code:代码:

def userindextry():
    User_input = 'u'
    index_range = range(0,3)
    range_check = False
    while User_input.isdigit() == False and range_check == False:
        User_input = input('Please enter a number: ')
        if User_input.isdigit() == True:
            if int(User_input) not in index_range:
                User_input.isdigit() == False
                range_check == False
                print('not in range')
            else:
                print('You choosed', User_input)
                break
            
        
        else:
            print('Number please')
    return(int(User_input))


def uservalue():
    input_value = input('Please enter a value: ')
    return(input_value)

and

def game():
    gamelist = [1,2,3]
    while True:
        userindex = userindextry()
        userV = uservalue()
        for i in range(len(gamelist)):
            number = gamelist[i]
            if number == userindex:
                gamelist[number] = userV
        cmd = input('Do you want to quit? Enter \'q\'!')
            
        if cmd == 'q':
            print('You did now Quit')
            break
        else:
            pass
        print(gamelist)

game()

What is going wrong with my code?我的代码出了什么问题?

def game():
    gamelist = [1, 2, 3]
    while True:
        userindex = userindextry()
        #print("userindex", userindex)
        userV = uservalue()
        #print("userV", userV)
        for i in range(len(gamelist)):
            number = gamelist[i]
            if i == userindex:
                gamelist[i] = userV
        cmd = input('Do you want to quit? Enter \'q\'!')
        if cmd == 'q':
            print('You did now Quit')
            break
        else:
            pass
    print(gamelist)

Your errors are in the game() function.您的错误在 game() 函数中。 Study the rewrite of game() I wrote with the corrections (there are two corrections).研究我用更正(有两个更正)编写的 game() 的重写。 You compared an index with the extracted value.您将索引与提取的值进行了比较。 You will see that the corrected code has two fixes:您将看到更正后的代码有两个修复:

    if i == userindex:
        gamelist[i] = userV

Your function userindextry() returns a number of 0 to 2 .您的函数userindextry()返回一个0 to 2

Your function game() compares this return of 0 to 2 to the value in your gamelist = [1,2,3] - it does not contain 0 -> so 0 can not be changed.您的函数game()0 to 2返回与您的gamelist = [1,2,3]进行比较 - 它不包含 0 -> 所以 0 不能更改。 The content of gamelist are initially integers but after you replace them with something from userindextry they contain a mix of strings and integers.内容gamelist最初是整数,但之后你userindextry的东西代替它们所包含字符串和整数的组合。

I have reworked your code a lot, maybe this will make it more clear.我已经对你的代码进行了很多修改,也许这会让它更清楚。

def get_user_index():
    allowed_nums= range(0,4)
    while True:
        number = input('Please enter a number, 0 to quit: ')
        try:
            n = int(number)
            if n in allowed_nums:
                return n
            print(f"Number must be one of: ", ' '.join(map(str, allowed_nums)))
        except Exception:
            print("Not a number!")

def get_value():
    return input('Please enter a value: ') or get_value() # hack-ish

Game:游戏:

def game():
    gamelist = [1,2,3]
    while True:
        index = get_user_index() # will return 0, 1, 2
        if index == 0: 
            print('\nGood bye.\n')
            break

        value = get_value() # will return a string

        found_it = False
        for idx, old in enumerate(gamelist):
            if index == old:
                found_it = True
                print(f"# Replacing pos #{idx} old value '{old}' ({type(old)}) "
                      f"with '{value}' ({type(value)}) ")
                gamelist[idx] = value
        if not found_it:
            print("This place was already set earlier.")
    print(gamelist)

game()

Output of a run with all cases done at least once:所有案例至少完成一次的运行输出:

Please enter a number, 0 to quit: 1
Please enter a value: Vlaue1
# Replacing pos #0 old value '1' (<class 'int'>) with 'Vlaue1' (<class 'str'>)
Please enter a number, 0 to quit: 32
Number must be one of:  0 1 2 3
Please enter a number, 0 to quit: sadfg
Not a number!
Please enter a number, 0 to quit: 1
Please enter a value: oo
This place was already set earlier.
Please enter a number, 0 to quit: 2
Please enter a value: V2
# Replacing pos #1 old value '2' (<class 'int'>) with 'V2' (<class 'str'>)
Please enter a number, 0 to quit: 3
Please enter a value: V3
# Replacing pos #2 old value '3' (<class 'int'>) with 'V3' (<class 'str'>)
Please enter a number, 0 to quit: 0

Good bye.

['Vlaue1', 'V2', 'V3']

HTH HTH

You might want to read through Asking the user for input until they give a valid response to get a better idea how to safely get input from users.您可能想要通读询问用户输入,直到他们给出有效的响应,以更好地了解如何安全地从用户那里获取输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用python项目Euler#4。 我的代码有什么问题? - Project Euler #4 with python. What;s wrong with my code? 我正在尝试制作一个程序来查找圆的面积,作为我在 python 中的第一个项目。有人知道我做错了什么吗? - I am trying to make a program that finds the area of a circle as my first project in python. does anything know what I did wrong? 我正在尝试用Python制作四连冠游戏。 这是我印刷电路板的代码。 运行结果导致列表索引超出范围错误 - I'm trying to make a connect four game in Python. This is my code for printing the board. Running results in a list index out of range error 蟒蛇。 如何使我的代码更快? - Python. How to make the my code faster? 这个Python游戏代码有什么问题? - What is wrong with this Python game code? (用于Nim游戏的Python NegaMax算法)我的代码出了什么问题? - (Python NegaMax Algorithm for Game of Nim) What is wrong with my code? 在python中测量代码计时。 我怎么了 - Measure code timing in python. What did I wrong? 在 python 中获取 for 语句的无限循环。这段代码有什么问题? - Getting an Infinite Loop in for statement in python. What is wrong in this code? 尝试在 Python 上制作 Snake 游戏。 我在哪里下载光标扩展 - Trying to make the Snake game on Python. Where do I download the cursor extension 尝试制作游戏时python代码无法正常工作 - python code not working while trying to make a game
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM