【问题标题】:How can i store my player moves data without writing tons of line of code?如何在不编写大量代码的情况下存储我的玩家移动数据?
【发布时间】:2019-04-28 02:34:56
【问题描述】:

我在互联网上搜索与 python 相关的项目并想出了一个井字游戏。但是现在我有点卡在代码的某些部分,因为我无法存储玩家动作。 好吧,老实说,我可能知道该怎么做,但我会使用很多 if、elif 和 else。是否有另一种方法可以在不编写 100 多行代码的情况下使用我当前的代码存储一些数据?

Ps:它需要是 OOP,因为我现在正在学习它:l


import msvcrt as m # Using it for 'Press any key to continue' thing.

import os
import keyboard

class TicTacToe:
    def __init__(self):
        self.difficultAI = 1
        self.playWith = 1  # 3 = Strings and Numbers

        self.playerOne = None
        self.PlayerTwo = None
    def menuSelection(self):
        os.system('cls')

        print(f'[1] - Play\n'
              f'[2] - Options\n'
              f'[3] - Exit')

        try:
            option = int(input('I\'ll go with '))
        except ValueError as valueError:
            print(f'Invalid Option\n'
                  f'Following error: {valueError}\n'
                  f'Press any key to continue...')

            m.getch() # Waiting for any key to be pressed.min
            os.system('cls')
            objectRun.menuSelection() # Call menuSelection again.


        if option == 1:
            objectRun.play()
        elif option == 2:
            pass
        elif option == 3:
            exit()
        else:
            print(f'You should choose something between 1 and 3, and not {option}'
                  f'Press any key to continue...')

            m.getch()
            objectRun.menuSelection()

    def drawBoard(self, topL='?', topM='!', topR='?',
                        midL='!', midM='?', midR='!',
                        lowL='?', lowM='!', lowR='?'):
        board = {
            'top-L': topL,
            'top-M': topM,
            'top-R': topR,

            'mid-L': midL,
            'mid-M': midM,
            'mid-R': midR,

            'low-L': lowL,
            'low-M': lowM,
            'low-R': lowR,
        }

        print(' {0} | {1} | {2}\n'
              '----------\n'
              ' {3} | {4} | {5}\n'
              '----------\n'
              ' {6} | {7} | {8}\n'.format(board['top-L'], board['top-M'], board['top-R'],
                                          board['mid-L'], board['mid-M'], board['mid-R'],
                                          board['low-L'], board['low-M'], board['low-R']))

    # change that stupid name when done
    def play(self):
        os.system('cls')

        print(f'[1] - Player VS Player\n'
              f'[2] - Player VS Machine\n'
              f'[3] - Return')

        try:
            option = int(input('I\'ll go with '))
        except ValueError as valueError:
            print(f'Invalid Option\n'
                  f'Following error: {valueError}\n'
                  f'Press any key to continue...')
            m.getch()
            objectRun.play()

        try:
            os.system('cls')
            self.drawBoard()
            if option == 1:           
                if self.playWith == 1:  # Numbers

                    isBoardFull = False  # Not using it right now, but ok... I guess.
                    while isBoardFull != True:
                        print('Player 1, it\'s your turn\n'
                            'You can choose between 1 (TOP LEFT) up to 9 (BOTTOM RIGHT)')

                        self.playerOne = int(input('I\'ll go with '))

                        self.playerOptions()

                elif self.playWith == 2:  # Strings
                    pass
                else:  # Strings and Numbers
                    pass
            elif option == 2:
                pass
            elif option == 3:
                objectRun.menuSelection()
            else:
                print(f'You should choose something between 1 and 3, and not {option}'
                      f'Press any key to continue...')

                m.getch()
                objectRun.play()

        except:
            print('ERROR AT LINE 126, GO FIND WHAT IS WRONG')

    def playerOptions(self):
        if self.playerOne == 1:
            os.system('cls')
            self.drawBoard(topL='X')
        elif self.playerOne == 2:
            os.system('cls')
            self.drawBoard(topM='X')
        elif self.playerOne == 3:
            os.system('cls')
            self.drawBoard(topR='X')
        elif self.playerOne == 4:
            os.system('cls')
            self.drawBoard(midL='X')
        elif self.playerOne == 5:
            os.system('cls')
            self.drawBoard(midM='X')
        elif self.playerOne == 6:
            os.system('cls')
            self.drawBoard(midR='X')
        elif self.playerOne == 7:
            os.system('cls')
            self.drawBoard(lowL='X')
        elif self.playerOne == 8:
            os.system('cls')
            drawBoard(lowM='X')
        elif self.playerOne == 9:
            os.system('cls')
            self.drawBoard(lowR='X')
        else:
            pass

    def options(self):
        os.system('cls')

        print(f'[1] - Difficult\n'
              f'[2] - P\n'
              f'[3] - Exit')

        try:
            option = int(input('I\'ll go with '))
        except ValueError as valueError:
            print(f'You should choose something between 1 and 3, and not {option}'
                  f'Press any key to continue...')

            m.getch()
            objectRun.menuSelection()


        self.difficultAI = int(input('[1] - EASY\n'
                                '[2] - MEDIUM\n'
                                '[3] - HARD\n'
                                'I\'ll go with '))

        self.playWith = int(input('[1] - NUMBERS\n'
                                '[2] - STRING\n'
                                '[3] - BOTH\n'
                                'I\'ll go with '))


if __name__ == '__main__':
    objectRun = TicTacToe()

    objectRun.menuSelection()

【问题讨论】:

  • 你可以为每个玩家使用一个列表并将每个move附加到列表中吗?

标签: python python-3.x oop


【解决方案1】:

将当前板存储为self中的字典。

使用默认起始字符初始化您的板。

    def __init__(self):
        self.difficultAI = 1
        self.playWith = 1  # 3 = Strings and Numbers
        self.playerOne = None
        self.PlayerTwo = None
        self.board = {'topL':'?', 'topM':'!', 'topR':'?',} #fill in the rest

你的画板需要像这样调整...

    def drawBoard(self):
        board = {
            'top-L': self.board['topL'],
            'top-M': self.board['topM'],
            'top-R': self.board['topR'],

然后我会有一个单独的“移动”方法

def makeMove(self, player, position):
    if self.board[position] not in ['X', 'O']:
        self.board[position] = player
        self.drawboard()
    else:
        # error statement and send back to make a new move...

一般来说,我会为游戏的主循环和其他所有内容设置不同的方法。现在你在主循环中发生了很多事情,而它应该只是将你发送到游戏的不同方法,如playerOptionsmakeMovedrawBoard 等,直到有人获胜或平局。

【讨论】:

  • 好的,我几乎明白了一切。但是makeMove中的'player'参数呢?我将如何分配它?
  • player 可以代表该玩家的标记,“O”或“X”。如果你像我写的那样直接使用它,它应该是某种字符串值,你可以将它重命名为“mark”或其他适合你的东西。
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2016-04-02
相关资源
最近更新 更多