该函数将识别列表中的空字符串并在其中打印标记/符号(Python Tic-Tac-Toe) [英] Function that will identify an empty string in a list and print a marker/symbol there (Python Tic-Tac-Toe)

查看:43
本文介绍了该函数将识别列表中的空字符串并在其中打印标记/符号(Python Tic-Tac-Toe)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里编码新手,使用我的第一个python井字游戏板.

Coding newbie here, working on my first tic-tac-toe board in Python.

最近,我问了

Recently, I asked this question, and those who responded were very helpful. Beyond the fact that my code was incorrect/wasn't written in a way that could return the results I wanted, I realized I was getting ahead of myself. I needed to first write a function that would ask the two players (using 1 computer) in my tic-tac-toe game to take a turn, which I successfully completed. I then realized I needed to identify if there is a free space on my tic-tac-toe board to place a marker ('X' or 'O'), which I expressed as:

def space_check(board, position):
    
    return board[position] == ' '


space_check(test_board, 8)

问题:

现在,我很难编写一个可以识别板上特定位置的功能,然后将玩家的标记("X"或"O")放在空白处.

Now, I am having a really hard time with writing a function that will identify that a particular position on the board is free and then place the player's marker ('X' or 'O') in the empty space.

尝试的解决方案(请注意:下面的这些板是测试板,我使用"$"作为测试标记):

board = ['#','a','b','c','d','e','f','g','h',' ']
marker = "$"
position=0

def place_marker(board, marker, position):


# while our position is an acceptable value (an int between 1 and 9)
    while position not in range(0,10):
        position = int(input("Choose a number from 1 through 9: " ))   
        

# at the board's position, place marker 'X' or 'O'
    board[position] = marker
    print(board)

place_marker(board, marker, position)

虽然这确实以列表形式返回输出,但是当我显示面板时,该面板不受影响:

While this does return an output in the form of a list, when I display the board, the board is unaffected:

place_marker(board, marker, position)
display_board(board)

输出:

 | |  
g|$|$
 | |  
______
 | |  
d|e|f
 | |  
______
 | |  
a|$|c
 | |  

我也尝试过这种方法,但是即使它在Jupyter笔记本中也可以工作,但是代码无法在VSC(我用于该项目的主要IDE)中运行:

I also tried this, but the code won't run in VSC (the primary IDE I'm using for this project), even though it works in Jupyter notebook:

test_board = ['#','a','b','c','d','e','f','g','h',' ']

def player_choice(board):

    position = 0
    
    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
        position = int(input("Choose your next position (1-9): " ))
        
    return position

player_choice(test_board)

输出:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-169-72130d7eb126> in <module>
----> 1 player_choice(test_board)

<ipython-input-168-37d67e2d2b88> in player_choice(board)
      7 
      8     while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
----> 9         position = int(input("Choose your next position (1-9): " ))
     10 
     11     return position

ValueError: invalid literal for int() with base 10: ''

我知道我的理解上有差距,但是我不知道自己缺少什么或如何进行.现在已经在这里停留了几天,所以非常感谢您的帮助!

I know there's a gap in my understanding here, but I don't know what I'm missing or how to proceed. Been stuck here for a few days now, so I'd appreciate the help! 

更新:解决方案

 # NEXT STEP: write a function that can check for input in acceptable range AND check for free space

def player_choice(board):

# while player is taking a turn
while True:
    try:
        # ask player for input
        position = int(input("Choose a Number (1 -9): " ))
        
        assert 0 < position < 10 # ensure that this input is within range
        assert board[position] == ' ' # ensure that there is a free space on which to place the input as marker
    
    except ValueError: # override the ValueError exception

        print("You didn't enter a number. Try again!") # tell player that input was not in range
        
    except AssertionError as e:
        print(e)

    else:
        return position

推荐答案

乍一看,如果位置变量为空字符串,则将 int(input())用作位置变量似乎会导致错误(''),这是您遇到的错误,请尝试以下操作:

At first glance, it looks like taking int(input() for your position variable will cause errors if it is an empty string (''), which is the error you are getting. Instead, try this:

position = input("Choose Position (1-9):   ")
try:
    position = int(position) # Trying to make position into an integer
except: # If there is an error, 
    if position == '':
        # Do whatever if position is empty
    else: # This means the position is not an integer, and not an empty string
        # Do something to force the player to enter an integer or an empty string
    

我们没有足够的代码来独自尝试,因此我将在这里尝试并提供帮助:)

We don't have enough code to try this on our own, so I'll just try and help from here :)

更新

marker = '$'
while True:
    try:
        position = int(input('Choose a Number (1 -9)   '))
        break
    except ValueError:
        if not position:  # 'not' compares to an emptry value, or a False boolean.
                          # It's much clearer imo than == ''
            position = marker
        pass

针对您的第三条评论, NoneType 异常是当您期望另一个值(字符串或整数)时具有 None 值.收到错误消息后,您可以随时搜索错误消息的含义.编程时需要开发的另一件事是记住一些基本错误,例如 NoneType parsing error .就您而言,类型错误 NoneType 意味着列表中有一个 None 值.

In response to your third comment, the NoneType Exception is when you have a None value when another value (string or integer) is expected. When you get an error, you can always google what the error means. Another thing that is good to develop when programming is to remember what some of the basic errors are, such as NoneType and parsing error. In your case, the Type Error NoneType means that you have a None value inside of your list.

这篇关于该函数将识别列表中的空字符串并在其中打印标记/符号(Python Tic-Tac-Toe)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆