TicTacToe Python,选择板尺寸

时间:2017-04-18 21:47:44

标签: python

拼命尝试为python TicTacToe游戏创建代码。

我是Python的新手,所以我坚持使用我要添加的功能。

这个想法是玩家可以选择他是想玩2,3个玩家还是玩电脑。

然后他选择他是想成为X还是O(或3名球员的Y)

然后,他选择任何最高9x9的纸板尺寸。

到目前为止一切顺利,两个播放器,NbyN和X或O选择工作,我已经将代码分成三个单独的文件(两个类)以方便。

我迷失在试图弄清楚如何创建计算机算法并将游戏扩展到3个玩家。

有谁知道我怎么能这样做?

以下是代码:

播放器文件:

class Player:
def __init__(self, player_name, shape):
    self.player_name = player_name
    self.shape = shape

def get_player_loc_input(self, rows, columns):
    player_input = input('Enter in location for your move: ')  # player input is with respect to field index location/values
    converted_input = int(player_input)

    if 1 <= converted_input <= (rows * columns): # bound checking
        converted_input -= 1 # adjust from n+1 to n
        transformed_value = (rows-(converted_input//columns)-1, converted_input%columns) # (row,col) tuple obj
        return transformed_value
    else:
       raise ValueError('Input is not an index on the playing field. Try again\n')#

TicTac文件:

class TicTac:
def __init__(self, rows, columns):
    #self.playing_field = [ [7,8,9], [4,5,6], [1,2,3] ] #init the playing field to their respective nums on the numpad: 3x3

    self.winner_found = False
    self.is_full = False
    self.possible_moves_left = columns * rows
    self.rows = rows

    def DefineBoard():
        field = []
        value = (rows * columns)
        for row in range(rows):
            field.append([])
            for col in range(columns):
                field[row].insert(0, value)
                value = value - 1
        return field

    self.playing_field = DefineBoard()

    #value = (rows * columns)
    #def decrement(x): return (x-1)
    #self.playing_field = [ [ decrement(value) for i in range(columns) ] for i in range(rows)]

def DrawBoard(self): #prints playing field based on size input
    print('-------------')
    for list in self.playing_field:
        print('| ', end='')
        for item in list:
            print(str(item) + ' | ', end='')
        print('\n-------------')

def Instructions(self):
    print('\n-------------------------------------')
    print('When entering in the location please enter the number of the index you want to replace with your shape.')
    print('\nPrinting Initial Playing Field...')
    self.DrawBoard()
    print('\nLet the game begin!')
    print('-------------------------------------')

def PlayerMove(self, index, shape):
    row, col = index[0], index[1]
    field_value = self.playing_field[row][col]

    #if the value is of type int we can replace it
    if isinstance(field_value, int):
        self.playing_field[row][col] = shape #overwrite the value
        self.possible_moves_left -= 1 #reduce the moves left

        #check possible moves after its been updated
        if self.possible_moves_left == 0:
            self.is_full = True
            raise EnvironmentError('All index posistions filled.\nGame Over. Nobody won.')

    #else its the Player's shape (string)
    else:
        raise ValueError('Invalid Index. Position already filled. Try again.\n')

def ConsecutiveSymbols(self):
    def check_list(passed_list):
        #fast & quick check to tell if the "row" is incomplete
        if isinstance(passed_list[0], str):
            player_shape = passed_list[0] # set to first val

            #compare the values to each other
            for val in passed_list:
                if isinstance(val, int) or player_shape != val:
                    return False #we found an inconsistency
            return True #everything matched up

    def Diagonal(orientation):
        DiagonalList = []
        counter = 0 if orientation is 'LtR' else self.rows-1
        for row in self.playing_field:
            DiagonalList.append(row[counter])
            counter = counter+1 if orientation is 'LtR' else counter-1
        return DiagonalList

    # check rows for match
    for row_list in self.playing_field:
        if check_list(row_list):
            return True

    #check cols for match
    transposed_playing_field = [list(a) for a in zip(*self.playing_field)] #convert our tuples from zip to a list format
    for col_list in transposed_playing_field:
        if check_list(col_list):
            return True


    #check diagonals for match
    if check_list(Diagonal('LtR')): #LtR \ gets replaced each time we check
        return True
    if check_list(Diagonal('RtL')):  # RtL / gets replaced each time we check
        return True

    return False #if we got here then no matches were found

主档案:

try:
from .TicTac import TicTac
from .Player import Player
except Exception:
from TicTac import TicTac
from Player import Player


winners=[]

def GameBegins():
Game=input("Would you like to play with 2, 3 players or against the CPU?").upper()
if Game=="2":
      selection=input("Player 1: Would you like to play as X or O?").upper()
      if selection == "X":
          Players = {'Player_1': Player('Player_1', "X"), 'Player_2': Player('Player_2', "O")}
      elif selection == "O":
          Players = {'Player_1': Player('Player_1', "O"), 'Player_2': Player('Player_2', "X")}
      else:
          print("Please enter either X or O")
          return False

if Game=="3":
      selection=input("Player 1: Would you like to play as X, O or Y?").upper()
      if selection == "X":
          selection2=input("Player 2: Would you like to play as O or Y?").upper()
          if selection2=="O":
                Players = {'Player_1': Player('Player_1', "X"),"Player_2":Player("Player_2","O"),"Player_3":Player("Player_3","Y")}
          elif selection2=="Y":
                Players = {'Player_1': Player('Player_1', "X"),"Player_2":Player("Player_2","Y"),"Player_3":Player("Player_3","O")}
          else:
                print("Please enter either O or Y")
                return False
      elif selection == "O":
          selection2=input("Player 2: Would you like to play as X or Y?").upper()
          if selection2=="X":
                Players = {'Player_1': Player('Player_1', "O"),"Player_2":Player("Player_2","X"),"Player_3":Player("Player_3","Y")}
          elif selection2=="Y":
                Players = {'Player_1': Player('Player_1', "O"),"Player_2":Player("Player_2","Y"),"Player_3":Player("Player_3","X")}
          else:
                print("Please enter either X or Y")
                return False
      elif selection=="Y":
          selection2=input("Player 2: Would you like to play as X or O?").upper()
          if selection2=="X":
                Players = {'Player_1': Player('Player_1', "Y"),"Player_2":Player("Player_2","X"),"Player_3":Player("Player_3","O")}
          elif selection2=="O":
                Players = {'Player_1': Player('Player_1', "Y"),"Player_2":Player("Player_2","O"),"Player_3":Player("Player_3","X")}
          else:
                print("Please enter either X or O")
                return False
if Game=="CPU":
    CPU()



x=input("enter boardsize: ")
if x >="2":
    rows, columns = int(x),int(x) #Players input becomes board size
else:
    print("Please enter a boardsize of 3 or more")
    GameBegins()
global game
game = TicTac(rows, columns)
game.Instructions()
player_id = 'Player_1'  # index to swap between players, Player_1 starts
while (game.winner_found == False and game.is_full == False):
    print('\nIt\'s ' + Players[player_id].player_name + ' Turn')

    # loop until user inputs correct index value
    while True:
        try:
            index = Players[player_id].get_player_loc_input(rows,columns)
            shape = Players[player_id].shape
            game.PlayerMove(index, shape)
        except ValueError as msg:
            print(msg)
            continue
        except EnvironmentError as msg:
            print(msg)
        break
    game.winner_found = game.ConsecutiveSymbols()  # check if a player has won
    game.DrawBoard()

    if game.winner_found:
        print(Players[player_id].player_name + ' has won!') # print player who won
        winners.append(str(Players[player_id].player_name))
    player_id = 'Player_2' if player_id is 'Player_1' else 'Player_1'  # switch between the 2 players

Replay() # Game has ended. Play Again?

def Replay():
PlayerDecision = input('\nDo you want to play again? (Y/N) ')
PlayerDecision = PlayerDecision.upper() #force to uppercase for consistency
if PlayerDecision == 'Y':
    GameBegins()
elif PlayerDecision == 'N':
    file=open("winners.txt","w")
    for w in winners:
        file.write(str(winners))
    file.close()
    exit(0)
else:
    print('Incorrect input.')
    Replay()


def main():
  while True:
    GameBegins()

if __name__ == '__main__':
main()

非常感谢一些建议,提前谢谢!

0 个答案:

没有答案