SHARE
TWEET

TicTacToe

a guest Feb 14th, 2020 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. gameRunning = True
  2.  
  3. class Player:
  4.     name = ""
  5.     state = 0b000000000
  6.     def __init__(self,playerCharacter):
  7.         self.name = playerCharacter
  8.  
  9. class Board:
  10.     winStates = [0b111000000,0b000111000,0b000000111,0b100100100,0b010010010,0b001001001,0b100010001,0b001010100]
  11.     boardArray = ["1","2","3","4","5","6","7","8","9"]
  12.     def __init__(self,players):
  13.         self.players = players
  14.     def printBoard(self):
  15.         print (self.boardArray[0] + "|" + self.boardArray[1] + "|" + self.boardArray[2])
  16.         print ("-----")
  17.         print (self.boardArray[3] + "|" + self.boardArray[4] + "|" + self.boardArray[5])
  18.         print ("-----")
  19.         print (self.boardArray[6] + "|" + self.boardArray[7] + "|" + self.boardArray[8])
  20.     def choose(self,player,locationNumber):
  21.         if self.validChoice(locationNumber):
  22.             self.boardArray[int(locationNumber)-1] = player.name
  23.             player.state |= 1 << int(locationNumber) - 1
  24.             return True
  25.         else:
  26.             return False
  27.     def boardTaken(self):
  28.         result = 0
  29.         for player in self.players:
  30.             result |= player.state
  31.  
  32.         return result
  33.     def validChoice(self,locationNumber):
  34.         choice = 1 << int(locationNumber)
  35.         bitboard = self.boardTaken()
  36.         if (choice & bitboard) == 0:
  37.             return True
  38.         else:
  39.             return False
  40.  
  41. #Game
  42.  
  43. board = Board([Player("X"),Player("O")])
  44. turn = 0;
  45.  
  46. # loop
  47. while gameRunning:
  48.     print("-------------------")
  49.     board.printBoard()
  50.     print ("{0} turn".format(board.players[turn % len(board.players)].name))
  51.     print ("select a number or type e to exit")
  52.     s = input()
  53.     if(s == "e"):
  54.         gameRunning = False
  55.         break
  56.  
  57.     if int(s) >= 1 and int(s) <=9 and board.choose(board.players[turn % len(board.players)],s):
  58.         turn += 1
  59.     else:
  60.         print("    V V V V That is not a valid choice please choose a valid location")
  61.  
  62.  
  63.     for wins in board.winStates:
  64.         for player in board.players:
  65.             check = player.state & wins
  66.             if check == wins:
  67.                 print("Player {} won!".format(player.name))
  68.                 exit()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top