将整数附加到空列表中,然后打印这些整数 (Tic-Tac-Toe) [英] Appending integers to an empty list, then printing those integers (Tic-Tac-Toe)

查看:28
本文介绍了将整数附加到空列表中,然后打印这些整数 (Tic-Tac-Toe)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 非常陌生(上个月开始参加 Udemy 课程,然后编写了我的第一行 Python 代码),所以我希望有人可以就 Python 的某个方面提供仁慈建议我正在开发的交互式井字游戏项目.注意:这是一个两人游戏,其中两个玩家将使用同一台计算机.

I'm very new to Python (started taking an Udemy course last month and wrote my first line of Python code then), so I am hoping someone can offer merciful advice on an aspect of an interactive tic-tac-toe project I'm developing. Note: This is a two-player game in which two players would use the same computer.

问题:

我正在尝试编写一个函数,该函数将接收 1-9 范围内的用户输入(位置"),将该输入作为整数存储在名为board"的空列表中,然后用称为标记"的变量替换位置;(X"或O").

I'm trying to write a function that will take in user input in range 1-9 inclusive ("position"), store that input as an integer in an empty list called "board," then replace the position with a variable called "marker" ('X' or 'O').

我的代码:

# POSITION IS SUPPOSED TO BE AN INT THAT IS STORED IN A LIST CALLED "BOARD"

board = [''] * 9
marker = ''
position = ''

def place_marker(board, marker, position):


# while our position is an acceptable value
    while position not in range(1,9+1):
        position = int(input("Choose a number from 1 through 9: " ))   
        board.append(position)

    print(board)

# NOW HOW DO I MAKE SURE THAT THE POSITION CORRESPONDS WITH EACH MARKER?

失败的解决方案尝试:

我已经忘记了我失败的解决方案尝试,但这里是其中之一:

I've sort of lost track of my failed solution attempts, but here is one of them:

board = [''] * 9
marker = ''
position = ''

def place_marker(board, marker, position):


# while our position is an acceptable value
    while position not in range(1,9+1):
        position = int(input("Choose a number from 1 through 9: " ))   
        board.append(position)

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

这导致:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-197-76194c5efcbd> in <module>
----> 1 board[position]

TypeError: list indices must be integers or slices, not str

也许我想一次做太多.我试过参考文档以及其他资源,如 W3Schools 和 Real Python,但我似乎无法找到适合我生活的解决方案.如果有人能指出我的不足或错误,或者给我一两条正确方向的线索,我将不胜感激.

Maybe I'm trying to do too much at a time. I've tried referring to the documentation as well as other resources like W3Schools and Real Python, but I can't seem to figure out the solution for the life of me. If someone could just point out where I've fallen short or gone wrong, or give me a clue or two in the right direction, I'd be super grateful.

推荐答案

当您使用这样的游戏时,我建议将棋盘作为整数列表.这将使编码变得更加容易,并且您将减少在变量类型之间来回切换的错误.要轻松切换回合,您可以将 -1 用作 X,将 1 用作 O,将 0 用作空白,这也将使检查空槽变得非常容易.

When you work with a game like this I would suggest having the board as a list of integers. This will make it much easier to code and you will make less mistakes going back and forth between variable types. To easily switch turn you can use -1 as X, 1 as O, and 0 as empty spaces, this will make checking for empty slots super easy as well.

获取用户输入:

board = [0]*9  # Init board
print_board(board)  # Print board at start of game
user_turn = True  # User goes first

# Game loop
while 1:

# User turn to move
    if user_turn:

        # Loop until we get a valid input from user
        while 1:

            # Get user input from the console
            user_input = input('\nPlease enter your move (1-9): ')

            # Check if user input is a number
            if user_input.isnumeric():

                # If it is a number, make the string is an integer and subtract 1 since array indices starts at 0
                user_input = int(user_input) - 1

                # Check if the input - 1 is in range 0-8
                if user_input in range(9):

                    # Check if the input is an empty square
                    if board[user_input] == 0:

                        # If all conditions are true: Make the move on the board, print the new board and change turn
                        board[user_input] = -1
                        print_board(board)
                        user_turn = not user_turn
                        break

打印黑板

这是您将整数板转换为 X、O 和空位的地方.可以通过这个简短的函数来完成.

This is where you convert your integer board to X, O and empty spots. It can be done by this short function.

def print_board(board):
    temp_board = [' ' if i == 0 else 'X' if i == -1 else 'O' if i == 1 else i for i in board]
    for row in range(3):
        print(f'\n{temp_board [row*3:3+row*3]}' if row == 0 else temp_board [row*3:3+row*3])

您将其转换为字符串元素,然后将其打印在不同的行上.

You convert it into string elements and then print it on different lines.

检查获胜者和全餐

您可以先定义所有获胜线:

You could first define all the winning lines:

winning_lines = ([0, 1, 2], [3, 4, 5], [6, 7, 8],  # Horizontally
             [0, 3, 6], [1, 4, 7], [2, 5, 8],  # Vertically
             [0, 4, 8], [2, 4, 6])  # Diagonally

然后您通过比较输入板和玩家回合来检查是否获胜,看它是否与获胜线匹配.

Then you check for a win by comparing input board and player turn to see if it matches the winning lines.

def is_winner(board, player):
    for pos in winning_lines:
        if board[pos[0]] == board[pos[1]] == board[pos[2]] == player:
            return 1

检查电路板是否已满更容易:

Checking to see if board is full is even easier:

def is_board_full(board):
    return 0 if 0 in board else 1

结束评论

当您在游戏循环中切换回合时,您还需要检查是否获胜或棋盘已满,以查看是否应该结束循环,并可能要求玩家再次玩游戏.您还可以在更改回合后添加一个 AI 玩家,例如让它使用 Negamax 算法进行游戏.

When you switch turn in your game loop you also need to check for win or board is full to see if you should end the loop, and possibly ask the player to play again. You could also add an AI player after you change turn and for example let it play with the Negamax algorithm.

如果您想要完整代码,可以查看我的井字游戏代码库.有几个版本,包括 Player vs Player (pvp) 和 Player vs Environment/AI (pve),您可以查看评论的和压缩的以获得一些灵感.如果您有任何问题,请告诉我 :)

If you want the full code you can check my Tic-Tac-Toe repository. There are several versions including both Player vs Player (pvp) and Player vs Environment/AI (pve), you can check both the commented ones and the compressed ones for some inspiration. Please let me know if you have any questions :)

这篇关于将整数附加到空列表中,然后打印这些整数 (Tic-Tac-Toe)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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