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

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

问题描述

我是Python的新手(上个月开始学习Udemy课程,然后编写了我的第一行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 :)

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

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