def main(): print("LET'S PLAY ROCK-PAPER-SCISSORS!!\n") name = input("What is your name? ") human = Human(name) computer = Computer() cont = "yes" # rounds while cont.lower() == "yes": human.setChoice(input("Rock, Paper, Scissors? ")) computer.makeChoice() print("The computer chose " + computer.getChoice()) # determine winner of round humanChoice = human.getChoice() compChoice = computer.getChoice() if ((humanChoice == "Paper" and compChoice == "Rock") or (humanChoice == "Rock" and compChoice == "Scissors") or (humanChoice == "Scissors" and compChoice == "Paper")): winner = human elif (humanChoice == compChoice): winner = None else: winner = computer if winner: print("The winner is " + winner.getName()) winner.addScore() else: print("Cats Game!") cont = input("Want to play another round? (yes/no)") #calculating winner if human.getScore() > computer.getScore(): winner = human loser = computer elif human.getScore() == computer.getScore(): winner = None loser = None else: winner = computer loser = human if winner: print("Thanks for playing!! " + winner.getName() + " is the winner." ) print(winner.getName() + ": " + str(winner.getScore()) + "\n" + loser.getName() + ": " + str(loser.getScore())) else: print("Thanks for playing!! Your game ended as a cats game, tied at " + str(human.getScore()))
class Round(object): ############################################################## # Function Name: Constructor # Purpose: Constructor # Parameters: # self # Assistance Received: None ############################################################## def __init__(self): self.roundNumber = 1 self.stockPile = [] self.layout = [] self.humanHand = [[], [], []] self.computerHand = [[], [], []] self.humanCapture = [[], [], []] self.computerCapture = [[], [], []] self.numComPlayers = 0 self.numHumPlayers = 0 #Initalize classes here self.s = Serialization() self.deck = Deck() self.player = Player() self.computer1 = Computer() self.computer2 = Computer() self.computer3 = Computer() self.human1 = Human() self.human2 = Human() self.human3 = Human() ############################################################## # Function Name: setRound # Purpose: sets the round # Parameters: # self, int round # Assistance Received: None ############################################################## def setRound(self, round): self.roundNumber = round ############################################################## # Function Name: getRound # Purpose: returns the round # Parameters: # self # Assistance Received: None ############################################################## def getRound(self): return self.round ############################################################## # Function Name: showCard # Purpose: shows the hand # Parameters: # self, hand # Assistance Received: None ############################################################## def showCard(self, hand): for c in hand: c.print() ############################################################## # Function Name: setComputer # Purpose: Sets computer information from file # Parameters: # self, score, hand, capture, players # Assistance Received: None ############################################################## def setComputer(self, score, hand, capture, players): self.computer1.setScore(score[0]) self.computer2.setScore(score[1]) self.computer3.setScore(score[2]) self.computerHand = hand self.computerCapture = capture self.numComPlayers = players ############################################################## # Function Name: setHuman # Purpose: Sets human information from file # Parameters: # self, int face # Assistance Received: None ############################################################## def setHuman(self, score, hand, capture, players): self.human1.setScore(score[0]) self.human2.setScore(score[1]) self.human3.setScore(score[2]) self.humanHand = hand self.humanCapture = capture self.numHumPlayers = players ############################################################## # Function Name: setLayout # Purpose: sets the layout # Parameters: # self, layout # Assistance Received: None ############################################################## def setLayout(self, layout): self.layout = layout ############################################################## # Function Name: setStockPile # Purpose: sets the stockPile # Parameters: # self, stockPile # Assistance Received: None ############################################################## def setStockPile(self, stockPile): self.stockPile = stockPile ############################################################## # Function Name: setNextPlayer # Purpose: sets the nextPlayer # Parameters: # self, nextPlayer # Assistance Received: None ############################################################## def setNextPlayer(self, nextPlayer): if nextPlayer == "Human" or nextPlayer == "Human 1\n": self.human1.setTurn(True) elif nextPlayer == "Human 2\n": self.human2.setTurn(True) elif nextPlayer == "Human 3\n": self.human3.setTurn(True) elif nextPlayer == "Computer" or nextPlayer == "Computer 1\n": self.computer1.setTurn(True) elif nextPlayer == "Computer 2\n": self.computer2.setTurn(True) elif nextPlayer == "Computer 3\n": self.computer3.setTurn(True) ############################################################## # Function Name: draw # Purpose: draws a card from deck # Parameters: # self, hand # Assistance Received: None ############################################################## def draw(self, hand): hand.append(self.stockPile.pop()) return self ############################################################## # Function Name: setUpPlayers # Purpose: Sets the players and decks # Parameters: # self # Assistance Received: None ############################################################## def setUpPlayers(self): while (self.numComPlayers + self.numHumPlayers > 4 or self.numComPlayers + self.numHumPlayers == 0 or self.numComPlayers + self.numHumPlayers < 2): self.numComPlayers = int( input("How many how many computer players? (1-3): ")) self.numHumPlayers = int(input("How many human Players? (1-3): ")) if (self.numComPlayers + self.numHumPlayers > 4): print("Sorry there can only be four total players :(") #Get number of decks numofDecks = 0 while (numofDecks == 0 or numofDecks < 2 or numofDecks > 4): numofDecks = int( input("How many decks would you like to play with? (2-4): ")) if (numofDecks < 2 or numofDecks > 4): print("Sorry please try again") #Set up Decks self.deck.shuffle() self.stockPile = self.deck.getDeck() if numofDecks == 2: self.deck.shuffle() tempDeck1 = self.deck.getDeck() self.stockPile = self.stockPile + tempDeck1 elif numofDecks == 3: self.deck.shuffle() tempDeck1 = self.deck.getDeck() self.deck.shuffle() tempDeck2 = self.deck.getDeck() self.stockPile = self.stockPile + tempDeck1 + tempDeck2 elif numofDecks == 4: self.deck.shuffle() tempDeck1 = self.deck.getDeck() self.deck.shuffle() tempDeck2 = self.deck.getDeck() self.deck.shuffle() tempDeck3 = self.deck.getDeck() self.stockPile = self.stockPile + tempDeck1 + tempDeck2 + tempDeck3 print(self.humanHand) ############################################################## # Function Name: setUpRound # Purpose: sets up the round # Parameters: # self # Assistance Received: None ############################################################## def setUpRound(self): #Distribute the cards to all the hands i = 0 while i < self.numHumPlayers: for j in range(5): self.draw(self.humanHand[i]) i += 1 i = 0 while i < self.numComPlayers: for j in range(5): self.draw(self.computerHand[i]) i += 1 for j in range(4): self.draw(self.layout) i = 0 while i < self.numHumPlayers: for j in range(5): self.draw(self.humanHand[i]) i += 1 i = 0 while i < self.numComPlayers: for j in range(5): self.draw(self.computerHand[i]) i += 1 for j in range(4): self.draw(self.layout) ############################################################## # Function Name: determinePlayer # Purpose: determines player based off hand # Parameters: # self # Assistance Received: None ############################################################## def determinePlayer(self): human1Count = 0 human2Count = 0 human3Count = 0 computer1Count = 0 computer2Count = 0 computer3Count = 0 j = 0 highestCard = [ "K", "Q", "J", "X", "9", "8", "7", "6", "5", "4", "3", "2", "A" ] # If the round == 1 or the scores are equal # Loop through the deck of each player to # determine who has a better hand, the better # hand goes first if (self.roundNumber == 1): while True: num = 0 while num < self.numHumPlayers: for humH in self.humanHand[num]: if humH.compareFace(highestCard[j]): if num == 0: human1Count += 1 elif num == 1: human2Count += 1 elif num == 3: human3Count += 1 num += 1 num = 0 while num < self.numComPlayers: for comH in self.computerHand[num]: if comH.compareFace(highestCard[j]): if num == 0: computer1Count += 1 elif num == 1: computer2Count += 1 elif num == 3: computer3Count += 1 num += 1 if (human1Count > computer1Count and human1Count > computer2Count and human1Count > computer3Count and human1Count > human2Count and human1Count > human3Count): print("Human 1has the better hand and will start\n") self.human1.setTurn(True) break elif (human2Count > computer1Count and human2Count > computer2Count and human2Count > computer3Count and human2Count > human3Count): print("Human 2 has the better hand and will start\n") self.human2.setTurn(True) break elif (human3Count > computer1Count and human3Count > computer2Count and human3Count > computer3Count): print("Human 3 has the better hand and will start\n") self.human3.setTurn(True) break elif (computer1Count > computer2Count and computer1Count > computer3Count): print("Computer 1 has the better hand and will start\n") self.computer1.setTurn(True) break elif (computer2Count > computer3Count): print("Computer 2 has the better hand and will start\n") self.computer2.setTurn(True) break elif (computer3Count > computer2Count): print("Computer 3 has the better hand and will start\n") self.computer3.setTurn(True) break if (j == 13): print("All card mathced the round is starting over\n") round = Round() j += 1 elif (self.roundNumber > 1): if (self.human1.getScore() > self.computer1.getScore() and self.human1.getScore() > self.computer2.getScore() and self.human1.getScore() > self.computer3.getScore() and self.human1.getScore() > self.human2.getScore() and self.human1.getScore() > self.human3.getScore()): self.human1.setTurn(True) self.human2.setTurn(False) self.human3.setTurn(False) self.computer1.setTurn(False) self.computer2.setTurn(False) self.computer3.setTurn(False) elif (self.human2.getScore() > self.computer1.getScore() and self.human2.getScore() > self.computer2.getScore() and self.human2.getScore() > self.computer3.getScore() and self.human2.getScore() > self.human3.getScore()): self.human1.setTurn(False) self.human2.setTurn(True) self.human3.setTurn(False) self.computer1.setTurn(False) self.computer2.setTurn(False) self.computer3.setTurn(False) elif (self.human3.getScore() > self.computer1.getScore() and self.human3.getScore() > self.computer2.getScore() and self.human3.getScore() > self.computer3.getScore()): self.human1.setTurn(False) self.human2.setTurn(False) self.human3.setTurn(True) self.computer1.setTurn(False) self.computer2.setTurn(False) self.computer3.setTurn(False) elif (self.computer1.getScore() > self.computer2.getScore() and self.computer1.getScore() > self.computer3.getScore()): self.human1.setTurn(False) self.human2.setTurn(False) self.human3.setTurn(False) self.computer1.setTurn(True) self.computer2.setTurn(False) self.computer3.setTurn(False) elif (self.computer2.getScore() > self.computer2.getScore()): self.human1.setTurn(False) self.human2.setTurn(False) self.human3.setTurn(False) self.computer1.setTurn(False) self.computer2.setTurn(True) self.computer3.setTurn(False) elif (self.computer3.getScore() > self.computer2.getScore()): self.human1.setTurn(False) self.human2.setTurn(False) self.human3.setTurn(False) self.computer1.setTurn(False) self.computer2.setTurn(False) self.computer3.setTurn(True) ############################################################## # Function Name: nextPlayer # Purpose: returns the next player # Parameters: # self, hand # Assistance Received: None ############################################################## def nextPlayer(self): if self.human1.getIsTurn() == True: return "Human 1" elif self.human2.getIsTurn() == True: return "Human 2" elif self.human3.getIsTurn() == True: return "Human 3" elif self.computer1.getIsTurn() == True: return "Computer 1" elif self.computer2.getIsTurn() == True: return "Computer 2" elif self.computer3.getIsTurn() == True: return "Computer 3" ############################################################## # Function Name: display # Purpose: shows the display # Parameters: # self # Assistance Received: None ############################################################## def display(self): print() print("---------------------------") print("Round:", self.roundNumber) print() #Computer print("Computer 1:") print("Score:", self.computer1.getScore()) print("Hand:", end=" ") self.showCard(self.computerHand[0]) print() print("Capture Pile:", end=" ") self.showCard(self.computerCapture[0]) #Human print("\n") print("Human 1:") print("Score:", self.human1.getScore()) print("Hand:", end=" ") self.showCard(self.humanHand[0]) print() print("Capture Pile:", end=" ") self.showCard(self.humanCapture[0]) print("\n") #Computer2 if self.numComPlayers >= 2: print("Computer 2:") print("Score:", self.computer2.getScore()) print("Hand:", end=" ") self.showCard(self.computerHand[1]) print() print("Capture Pile:", end=" ") self.showCard(self.computerCapture[1]) #Human 2 if self.numHumPlayers >= 2: print("\n") print("Human 2:") print("Score:", self.human2.getScore()) print("Hand:", end=" ") self.showCard(self.humanHand[1]) print() print("Capture Pile:", end=" ") self.showCard(self.humanCapture[1]) print("\n") #Computer 3 if self.numComPlayers == 3: print("Computer 2:") print("Score:", self.computer3.getScore()) print("Hand:", end=" ") self.showCard(self.computerHand[2]) print() print("Capture Pile:", end=" ") self.showCard(self.computerCapture[2]) #Human 3 if self.numHumPlayers == 3: print("\n") print("Human 3:") print("Score:", self.human3.getScore()) print("Hand:", end=" ") self.showCard(self.humanHand[2]) print() print("Capture Pile:", end=" ") self.showCard(self.humanCapture[2]) print("\n") #Layout print("Layout:", end=" ") self.showCard(self.layout) print("\n") #Stock pile print("Stock Pile:", end=" ") self.showCard(self.stockPile) #Next Player print("\n") print("Next Player:", end=" ") print(self.nextPlayer()) print("--------\n") self.menu() ############################################################## # Function Name: menu # Purpose: menu for human # Parameters: # self # Assistance Received: None ############################################################## def menu(self): if sum(len(x) for x in self.humanHand) == 0 and sum( len(y) for y in self.computerHand) == 0: self.nextRound() #Check to make sure hand is not empty of current player self.checkHand() if (self.computer1.getIsTurn() == True): self.computerMenu() return elif (self.computer2.getIsTurn() == True): self.computerMenu() return elif (self.computer3.getIsTurn() == True): self.computerMenu() return print("1. Save the game") print("2. Make a move") print("3. Ask for help") print("4. Quit the game") while True: selection = int(input("Selection: ")) if (selection > 0 and selection < 5): break if selection == 1: computerScores = [0, 0, 0] humanScores = [0, 0, 0] nextPlayer = self.nextPlayer() print("Save the game") #Computer Scores computerScores[0] = self.computer1.getScore() if self.numComPlayers >= 2: computerScores[1] = self.computer2.getScore() if self.numComPlayers == 3: computerScores[2] = self.computer3.getScore() #Human Scores humanScores[0] = self.human1.getScore() if self.numHumPlayers >= 2: humanScores[1] = self.human2.getScore() if self.numHumPlayers == 3: humanScores[2] = self.human3.getScore() self.s.saveGame(self.roundNumber, computerScores, self.computerHand, self.computerCapture, self.numComPlayers, humanScores, self.humanHand, self.humanCapture, self.numHumPlayers, self.layout, self.stockPile, nextPlayer) #Save the Game elif selection == 2: self.move() elif selection == 3: if (self.human1.getIsTurn() == True): self.player.play(self.stockPile, self.layout, self.humanHand[0], self.humanCapture[0], self.computerCapture[0]) elif (self.human2.getIsTurn() == True): self.player.play(self.stockPile, self.layout, self.humanHand[1], self.humanCapture[1], self.computerCapture[0]) elif (self.human3.getIsTurn() == True): self.player.play(self.stockPile, self.layout, self.humanHand[2], self.humanCapture[2], self.computerCapture[0]) self.menu() elif selection == 4: self.endGame() ############################################################## # Function Name: computerMenu # Purpose: Menu for computer # Parameters: # self # Assistance Received: None ############################################################## def computerMenu(self): print("1. Save Game") print("2. Computer Move") print("3. Quit Game") while True: selection = int(input("Selection: ")) if (selection > 0 and selection < 4): break if selection == 1: computerScores = [0, 0, 0] humanScores = [0, 0, 0] nextPlayer = self.nextPlayer() print("Save the game") #Computer Scores computerScores[0] = self.computer1.getScore() if self.numComPlayers >= 2: computerScores[1] = self.computer2.getScore() if self.numComPlayers == 3: computerScores[2] = self.computer3.getScore() #Human Scores humanScores[0] = self.human1.getScore() if self.numHumPlayers >= 2: humanScores[1] = self.human2.getScore() if self.numHumPlayers == 3: humanScores[2] = self.human3.getScore() self.s.saveGame(self.roundNumber, computerScores, self.computerHand, self.computerCapture, self.numComPlayers, humanScores, self.humanHand, self.humanCapture, self.numHumPlayers, self.layout, self.stockPile, nextPlayer) print("Save the game") elif selection == 2: self.move() elif selection == 3: self.endGame() ############################################################## # Function Name: switchPlayer # Purpose: switches current player # Parameters: # self # Assistance Received: None ############################################################## def switchPlayer(self): #Order alternates com hum, com, hum if (self.computer1.getIsTurn() == True): self.computer1.setTurn(False) self.human1.setTurn(True) elif (self.human1.getIsTurn() == True): self.human1.setTurn(False) if self.numComPlayers >= 2: self.computer2.setTurn(True) elif self.numHumPlayers >= 2: self.human2.setTurn(True) else: self.computer1.setTurn(True) elif (self.computer2.getIsTurn() == True): self.computer2.setTurn(False) if self.numHumPlayers >= 2: self.human2.setTurn(True) elif self.numComPlayers == 3: self.computer3.setTurn(True) else: self.human1.setTurn(True) elif (self.human2.getIsTurn() == True): self.human2.setTurn(False) if self.numComPlayers == 3: self.computer3.setTurn(True) elif self.numHumPlayers == 3: self.human3.setTurn(True) else: self.computer1.setTurn(True) elif (self.computer3.getIsTurn() == True): self.computer3.setTurn(False) if self.numHumPlayers == 3: self.human3.setTurn(True) else: self.human1.setTurn(True) elif (self.human3.getIsTurn() == True): self.human3.setTurn(False) self.computer1.setTurn(True) ############################################################## # Function Name: checkHand # Purpose: switches current player if no cards in hand # Parameters: # self # Assistance Received: None ############################################################## def checkHand(self): if (self.computer1.getIsTurn() and len(self.computerHand[0]) == 0): print("Hand is empty, moving to next player") self.switchPlayer() elif (self.computer2.getIsTurn() and len(self.computerHand[1]) == 0): print("Hand is empty, moving to next player") self.switchPlayer() elif (self.computer3.getIsTurn() and len(self.computerHand[2]) == 0): print("Hand is empty, moving to next player") self.switchPlayer() elif (self.human1.getIsTurn() and len(self.humanHand[0]) == 0): print("Hand is empty, moving to next player") self.switchPlayer() elif (self.human2.getIsTurn() and len(self.humanHand[1]) == 0): print("Hand is empty, moving to next player") self.switchPlayer() elif (self.human3.getIsTurn() and len(self.humanHand[2]) == 0): print("Hand is empty, moving to next player") self.switchPlayer() ############################################################## # Function Name: move # Purpose: Makes a move for current player # Parameters: # self # Assistance Received: None ############################################################## def move(self): if (self.computer1.getIsTurn() == True): self.computer1.play(self.stockPile, self.layout, self.computerHand[0], self.computerCapture[0], self.humanCapture[0]) elif (self.computer2.getIsTurn() == True): self.computer2.play(self.stockPile, self.layout, self.computerHand[1], self.computerCapture[1], self.humanCapture[0]) elif (self.computer3.getIsTurn() == True): self.computer3.play(self.stockPile, self.layout, self.computerHand[2], self.computerCapture[2], self.humanCapture[0]) elif (self.human1.getIsTurn() == True): self.human1.play(self.stockPile, self.layout, self.humanHand[0], self.humanCapture[0]) elif (self.human2.getIsTurn() == True): self.human2.play(self.stockPile, self.layout, self.humanHand[1], self.humanCapture[1]) elif (self.human3.getIsTurn() == True): self.human3.play(self.stockPile, self.layout, self.humanHand[2], self.humanCapture[2]) self.switchPlayer() self.display() ############################################################## # Function Name: nextRound # Purpose: starts the next round # Parameters: # self # Assistance Received: None ############################################################## def nextRound(self): str = "" while (str != "YES" and str != "NO"): str = input( "The round is over would you like to play another round? (Yes or No): " ) str = str.upper() if str == "YES": self.computerHand = [[], [], []] self.humanHand = [[], [], []] self.layout.clear() self.stockPile.clear() self.humanCapture = [[], [], []] self.computerCapture = [[], [], []] self.roundNumber += 1 self.setUpPlayers() self.setUpRound() self.determinePlayer() self.display() else: self.endGame() ############################################################## # Function Name: endGame # Purpose: ends the game # Parameters: # self # Assistance Received: None ############################################################## def endGame(self): if (self.human1.getScore() == self.computer1.getScore() and self.human1.getScore() == self.computer2.getScore() and self.human1.getScore() == self.computer3.getScore() and self.human1.getScore() == self.human2.getScore() and self.human1.getScore() == self.human3.getScore()): print("TIE GAME") elif (self.human1.getScore() > self.computer1.getScore() and self.human1.getScore() > self.computer2.getScore() and self.human1.getScore() > self.computer3.getScore() and self.human1.getScore() > self.human2.getScore() and self.human1.getScore() > self.human3.getScore()): print("Congrats Human 1 you won!") elif (self.human2.getScore() > self.computer1.getScore() and self.human2.getScore() > self.computer2.getScore() and self.human2.getScore() > self.computer3.getScore() and self.human2.getScore() > self.human3.getScore()): print("Congrats Human 2 you won!") elif (self.human3.getScore() > self.computer1.getScore() and self.human3.getScore() > self.computer2.getScore() and self.human3.getScore() > self.computer3.getScore()): print("Congrats Human 3 you won!") elif (self.computer1.getScore() > self.computer2.getScore() and self.computer1.getScore() > self.computer3.getScore()): print("Computer 1 has won") elif (self.computer2.getScore() > self.computer2.getScore()): print("Computer 2 has won") elif (self.computer3.getScore() > self.computer2.getScore()): print("Computer 3 has won")
class GameEngine: #Constructors: def __init__(self,isHumanTurn = None): #Member Variables: #round of the game self.round = 0 #flag for human as last capturer self.lastCapturer = "None" #set true as deafault self.humanTurn = True #Game inheriting all the class self.gameTable = Table() #empty deck as default self.gameDeck = Deck(False) self.human = Human() self.computer = Computer() #for new game if isHumanTurn is not None: #set the human turn self.humanTurn = isHumanTurn #create new new deck with cards self.gameDeck = Deck(True) #deal cards self.newDealCards(True) #Selectors: #returns game Table object def getGameTable(self): return self.gameTable #returns human object def getHuman(self): return self.human #returns computer object def getComputer(self): return self.computer #returns the boolean value for human turn def isHumanTurn(self): return self.humanTurn def getDeck(self): return self.gameDeck def getLastCapturer(self): return self.lastCapturer def getRound(self): return self.round #Utilities: #deals 4 new cards for each players, table if dealTable==true def newDealCards(self, dealTable): #Distribute card from the deck to table and hands if dealTable == True: for i in range(4): self.gameTable.storeTable(self.gameDeck.getNewCard()) for i in range(4): self.computer.storeHand(self.gameDeck.getNewCard()) for i in range(4): self.human.storeHand(self.gameDeck.getNewCard()) #prints all the cards in table and player's hand in systematic layout def printGameBoard(self): print(" Deck:",end='') self.gameDeck.printDeckCards() print(" |--------------------------------") #Display the round print(" | Round: "+str(self.round)+"\n |") #Display the round print(" | Last Capturer: "+self.lastCapturer) print(" |") #score print(" | \t: Score: " + str(self.computer.getScore())) #isplay the comp hand print(" | Comp: Hand:",end='') self.computer.printHandOrPile(True) #Display the comp pile print(" | \t: Pile:",end='' ) self.computer.printHandOrPile(False) print(" |") #Display table cards print(" | Table: ",end='') self.gameTable.printTable() print(" |") #score print(" | \t: Score: " + str(self.human.getScore())) #isplay the comp hand print(" | Human: Hand:",end='') self.human.printHandOrPile(True) #Display the comp pile print(" | \t: Pile:", end='') self.human.printHandOrPile(False) print(" |") print(" |--------------------------------\n\n") #called by GUI #return a string as a way to communicate with GUI after executing move def makeMove(self,moveInfo): self.printGameBoard() feedBack = [] if moveInfo[0] == "Help": feedBack = "HELP: \n" #clearing the vector to store moveInfo following the convention of first element #storing the player turn information moveInfo.clear() #adding the turn as the first element #For help only turn in the moveInfo moveInfo.append("Human") moveCheck = GameMoveCheck(moveInfo,self.gameTable,self.human) bestValidCaptureMove = moveCheck.getBestValidMove(True) bestValidBuildMove = moveCheck.getBestValidMove(False) if len(bestValidCaptureMove) == 2 and len(bestValidBuildMove) == 2: #no valid cpature or build move #trail the first card feedBack += "No Better Move: Trail" else: #get the num of cards to compare #and remove from the list numCardCapture = int(bestValidCaptureMove.pop()) numCardBuild = int(bestValidBuildMove.pop()) #get the score of cards to compare #and remove the info from the vector scoreCapture = int(bestValidCaptureMove.pop()) scoreBuild = int(bestValidBuildMove.pop()) #get the build value and erase from the bestValidBuildMove #check size since invlaid build move lacks buildValue info buildValue = -1 if bestValidBuildMove: buildValue = int(bestValidBuildMove.pop()) #store the best build,best capture and best move in the feedBack #to return to the GUi feedBack+= "The Best Capture Move: " for pos in bestValidCaptureMove: feedBack += str(pos)+" " feedBack += "\nScore: "+str(scoreCapture)+" NumCards: "+ str(numCardCapture)+"\n" feedBack+= "The Best build Move: " for pos in bestValidBuildMove: feedBack += str(pos)+" " feedBack += "\nScore: "+str(scoreBuild)+" NumCards: "+ str(numCardBuild)+"\n The Best Move: " #get the best move if scoreCapture > scoreBuild or (scoreCapture == scoreBuild and numCardCapture >=numCardBuild ): feedBack += "Capture: " feedBack += self.human.getHandCard(int(bestValidCaptureMove.pop(0)))+" and " tempTable = self.gameTable.getAllCards() for pos in bestValidCaptureMove: tempInfo = ''.join(tempTable[int(pos)]) feedBack += tempInfo+" " else: feedBack += "Build: " feedBack += self.human.getHandCard(int(bestValidBuildMove.pop(0)))+" and " tempTable = self.gameTable.getAllCards() for pos in bestValidBuildMove: tempInfo = ''.join(tempTable[int(pos)]) feedBack += tempInfo+" " elif moveInfo[0] == "Computer": feedBack = "Computer: \n" #clearing the vector to store moveInfo following the convention of first element #storing the player turn information moveInfo.clear() #adding the turn as the first element #For help only turn in the moveInfo moveInfo.append("Computer") moveCheck = GameMoveCheck(moveInfo,self.gameTable,self.computer) bestValidCaptureMove = moveCheck.getBestValidMove(True) bestValidBuildMove = moveCheck.getBestValidMove(False) print(bestValidCaptureMove,bestValidBuildMove) if len(bestValidCaptureMove) == 2 and len(bestValidBuildMove) == 2: #no valid cpature or build move #trail the first card feedBack += "No Better Move: Trailed 0" self.trail(0) else: #get the num of cards to compare #and remove from the list numCardCapture = int(bestValidCaptureMove.pop()) numCardBuild = int(bestValidBuildMove.pop()) #get the score of cards to compare #and remove the info from the vector scoreCapture = int(bestValidCaptureMove.pop()) scoreBuild = int(bestValidBuildMove.pop()) #get the build value and erase from the bestValidBuildMove #check size since invlaid build move lacks buildValue info buildValue = -1 if bestValidBuildMove: buildValue = int(bestValidBuildMove.pop()) #store the best build,best capture and best move in the feedBack #to return to the GUi feedBack+= "The Best Capture Move: " for pos in bestValidCaptureMove: feedBack += str(pos)+" " feedBack += "\nScore: "+str(scoreCapture)+" NumCards: "+ str(numCardCapture)+"\n" feedBack+= "The Best build Move: " for pos in bestValidBuildMove: feedBack += str(pos)+" " feedBack += "\nScore: "+str(scoreBuild)+" NumCards: "+ str(numCardBuild)+"\n The Best Move: " #get the best move if scoreCapture > scoreBuild or (scoreCapture == scoreBuild and numCardCapture >=numCardBuild ): #capture as best move feedBack += "Capture: " handPosition = int(bestValidCaptureMove.pop(0)) tableCardPosition = bestValidCaptureMove[:] feedBack += self.computer.getHandCard(handPosition)+" and " tempTable = self.gameTable.getAllCards() for pos in bestValidCaptureMove: tempInfo = ''.join(tempTable[int(pos)]) feedBack += tempInfo+" " #calling the capture function self.capture(handPosition,tableCardPosition) #setting the last capturer to the given turn self.lastCapturer = "Computer" else: #build as best move feedBack += "Build: " #get the hand position and erase from the vector handPosition = int(bestValidBuildMove.pop(0)) tableCardPosition = bestValidBuildMove[:] feedBack += self.computer.getHandCard(handPosition)+" and " tempTable = self.gameTable.getAllCards() for pos in bestValidBuildMove: tempInfo = ''.join(tempTable[int(pos)]) feedBack += tempInfo+" " #set the hand and table position and generate build pairs moveCheck.setPosTableHand(handPosition,tableCardPosition) moveCheck.generateBuildPairs(buildValue); #calling the capture function self.build(handPosition,tableCardPosition,moveCheck.getCurrentBuildPairds()) #change the turn self.humanTurn = True else: feedBack = "Human: \n" moveInfo.append("Human") #check if the move is valid moveCheck = GameMoveCheck(moveInfo,self.gameTable,self.human) if not moveCheck.moveCheck(): feedBack += "InValid move..Please Enter Valid Move" return feedBack feedBack += "The move is VALID\n" #Check for move type and valid move #trail if moveCheck.getMoveType() == "t": #trail feedBack += "Trailed: "+ str(moveCheck.getHandPosition()) self.trail(moveCheck.getHandPosition()) elif moveCheck.getMoveType() == "c": feedBack += "Captured: "+ str(moveCheck.getHandPosition())+" " for pos in moveCheck.getTablePosition(): feedBack += str(pos)+" " #capture self.capture(moveCheck.getHandPosition(),moveCheck.getTablePosition()) #Setting the last capturer to the given turn self.lastCapturer = "Human" else: #build feedBack += "Build: "+ str(moveCheck.getHandPosition())+" " for pos in moveCheck.getTablePosition(): feedBack += str(pos)+" " self.build(moveCheck.getHandPosition(),moveCheck.getTablePosition(),moveCheck.getCurrentBuildPairds()) #change the turn self.humanTurn = False return feedBack #carries out trail action for human or computer with given hand position def trail(self,handPosition): #Check human or computer #get the card from hand and store in the table board if self.humanTurn: self.gameTable.storeTable(self.human.popHandCard(handPosition)) else: self.gameTable.storeTable(self.computer.popHandCard(handPosition)) self.humanTurn = not self.humanTurn return True #carries out capture action for human or computer with given hand position and table card position def capture(self, handPosition, tableCardPosition): #since Capture involves deleting elements from table #arrange the tableCardPosition in descending order #prevents removing less indexed element before higher ones localTableCardPos = sorted(tableCardPosition,reverse=True) #get the current player currentPlayer = Player() if self.humanTurn: currentPlayer = self.human else: currentPlayer = self.computer #remove the card from hand and store into human pile currentPlayer.storePile(currentPlayer.popHandCard(handPosition)) #storing selected table cards into human pile for currentTableCardPos in localTableCardPos: #convert from string to int currentTableCardPos = int(currentTableCardPos) #check for build cards if len(self.gameTable.getAllCards()[currentTableCardPos]) > 2: #local variable to store the vector with buildInfo buildCard = self.gameTable.popTableCard(currentTableCardPos) #get each card from the build for card in buildCard: #bug when poping a multi build from the build #deletes the first [ and ] but fails to delete other occasions if card !="[" and card !="]": currentPlayer.storePile(card) else: #loose card currentPlayer.storePile(self.gameTable.popTableCard(currentTableCardPos)[0]) return True #carries out build action for human or computer with given hand position,table card position and build pairs def build(self, handPosition, tableCardPosition, buildPairs): #since build involves deleting elements from table #arrange the tableCardPosition in descending order #prevents removing less indexed element before higher ones localTableCardPos = sorted(tableCardPosition,reverse=True) #removing selected table cards for card in localTableCardPos: self.gameTable.popTableCard(int(card)) #removing the hand cards from the player if self.humanTurn: self.human.popHandCard(handPosition) else: self.computer.popHandCard(handPosition) #storing the build info as string to store in table buildCurrent = [] #value buildCurrent.append(buildPairs[0][0]) #owner buildCurrent.append(buildPairs[0][1]) #Multi or Single, multi as default, change to single when required in the loop below buildCurrent.append("Multi") #make a local copy of the parameter buildPairsLocal = buildPairs[:] #remove the first element which is the information of value and owner del buildPairsLocal[0] #replace the multi if len(buildPairsLocal) == 1: buildCurrent[2] = "Single" #loop to get each pair for pairCurrent in buildPairsLocal: #if single card then if len(pairCurrent) == 1: buildCurrent.append(pairCurrent[0]) continue #store "[" as start of single builds if buildCurrent[2] == "Multi": buildCurrent.append("[") #for pairs access each of them and store in the table for card in pairCurrent: buildCurrent.append(card) #store "]" as the end of single builds if buildCurrent[2] == "Multi": buildCurrent.append("]") #store the build vector in table self.gameTable.storeTable(buildCurrent) return True #loads the game with given file name def loadGame(self,fileName): file = open(fileName, "r") loadHuman = False for line in file: #splitting the line by delimiter space and storing in list lineList = line.split( ) #ignore empty list if len(lineList) > 0: #Check the label if lineList[0] == "Round:": #Round #converting string to int self.round = int(lineList[1]) elif lineList[0] == "Computer:": #Computer data loadHuman = False elif lineList[0] == "Human:": #Human Data loadHuman = True elif lineList[0] == "Score:": #get the score, check the player type and set the score score = lineList[1] if loadHuman: self.human.setScore(score) else: self.computer.setScore(score) elif lineList[0] == "Hand:": #delete the label, Hand: del lineList[0] #store each card in specified player hand for card in lineList: if loadHuman: self.human.storeHand(card) else: self.computer.storeHand(card) elif lineList[0] == "Pile:": #delete the label, Pile: del lineList[0] #store each card in specified player hand for card in lineList: if loadHuman: self.human.storePile(card) else: self.computer.storePile(card) elif lineList[0] == "Table:": #delete the label, Table: del lineList[0] #store each card in table ignoring build cards while(True and lineList): card = lineList.pop(0) #if build table found remove the card if card == "[": while card != "]": card = lineList.pop(0) elif card.find("[") != -1: while card.find("]") == -1: card = lineList.pop(0) else: #add the single cards to table self.gameTable.storeTable(card) #break if list empty if not lineList: break elif lineList[0] == "Build": #build ownership #delete the label, Build del lineList[0] #delete the label, Owner: del lineList[0] #ignored build cards at label "Table" #call store build function self.storeBuildTable(lineList) elif lineList[0] == "Last": self.lastCapturer = lineList[2] elif lineList[0] == "Deck:": #delete the label, Deck: del lineList[0] #store each card in deck for card in lineList: self.gameDeck.storeDeck(card) elif lineList[0] == "Next": #check for human or computer to set the turn if lineList[2] == "Computer": self.humanTurn = False else: self.humanTurn = True #stores one build multi or single into the table for human and computer def storeBuildTable(self,data): #make a copy of the data listCard = data[:] #get next card card = listCard.pop(0) buildCards = [] buildValue = 0 if card == "[": #multi build buildCards.append("Multi") #get next card card = listCard.pop(0) #6 types of card info # [ , [S8 , S8, S8], [S8] , ] #but ony [S8] and [S8 starts the single build #loop until the end of the build while card != "]" : #type S8 if len(card)==3 and card[0] == "[": #adding [ and S8 from [S8 to vector as separate elements buildCards.append("[") #removing the "[" form the card card = card.replace("[","") buildCards.append(card) #get next card card = listCard.pop(0) #loop until the end of the single build of type [S8 .. S8] #end means data with value S8] while len(card) != 3: #if not the end card S8] #then the value must be individual card S8 buildCards.append(card) #get next card card = listCard.pop(0) #adding ] and S8 from S8] to vector as separate elements #removing the "]" form the card S8] card = card.replace("]","") buildCards.append(card) buildCards.append("]") else: #type [S8] #removing the "[" and "]" form the card and adding only S8 part card = card.replace("[","") card = card.replace("]","") buildCards.append(card) #get new single build or "]" as end of the multi build card = listCard.pop(0) start = buildCards.index('[')+1 end = buildCards.index(']') elif len(card) == 3 and card[0] == '[': #single build buildCards.append("Single") #type [S8 #erasing "[" and adding S8 from [S8 to vector card = card.replace("[","") buildCards.append(card) #get new card card = listCard.pop(0) #loop until the end of the single build of type [S8 .. S8] #end means data with value S8] while len(card) != 3: #if not the end card S8] #then the value must be individual card S8 buildCards.append(card) #get new card to compare as single card card = listCard.pop(0) #erasing "]" and adding S8 from S8] to vector and ending the single build card = card.replace("]","") buildCards.append(card) #calculate the build value start and end index start = 1 end = len(buildCards) #calculating the build value #fails to calculate the buildValue for case # [0,Human, Multi, H6,C6, S6] since no [ and ] for i in range(start, end): buildValue += self.cardStringToValue(buildCards[i]) #for case: [0,Human, Multi, H6,C6, S6] if buildValue == 0: buildValue = self.cardStringToValue(buildCards[1]) #print "build:", buildCards,"value",buildValue #adding build value buildCards.insert(0,str(buildValue)) #get the build owner info card = listCard.pop(0) buildCards.insert(1,card) self.gameTable.storeTable(buildCards) #converts card value in character to numeric value def cardStringToValue(self,key): if key[1] == "A" : return 1 elif key[1] == "K" : return 13 elif key[1] == "Q" : return 12 elif key[1] == "J" : return 11 elif key[1] == "X" : return 10 else: return int(key[1]) #saves game of given filename def saveGame(self,fileName): #add .txt and path to the user input file name pathFileName = str(Path().absolute())+'\\serializationTest\\' pathFileName += fileName + ".txt" print(pathFileName) f = open(pathFileName, "w") #prompts f.write("Round: "+str(self.round)+"\n\nComputer: \n Score: " +str(self.computer.getScore())+"\n Hand: ") #hand Cards for card in self.computer.getAllHandCards(): f.write(card+" ") #pile Cards f.write("\n Pile: ") for card in self.computer.getAllPileCards(): f.write(card+" ") #Storing Human info f.write("\n\nHuman: \n Score: "+str(self.human.getScore())+"\n Hand: ") #hand Cards for card in self.human.getAllHandCards(): f.write(card+" ") #pile Cards f.write("\n Pile: ") for card in self.human.getAllPileCards(): f.write(card+" ") #table f.write("\n\nTable: ") #empty vector to store all build info for Build Owner Section of file vectorCards = [] for cardVector in self.gameTable.getAllCards(): #accessing elements of the table board #check the table element size for build #>2 means its a build if len(cardVector) == 2: f.write(cardVector[1]+" ") else: #build #to store each build seperately buildInfo = "" #check if multi or single build, stored as 3rd element of the table if cardVector[2] == "Single": buildInfo +="[" #Single build so simply store the cards for i in range(3,len(cardVector)): #adding the cards without any space in between buildInfo += cardVector[i] #Check if it's the last element of the build #since no need to add " " to the last element if i != len(cardVector)-1 : buildInfo += " " else: #multi build buildInfo +="[ " #loop to get the cards form the given element of the table #card's info starts from index 3 i = 3 while i<len(cardVector): #find if it's single or multi card if cardVector[i] == "[": #multi card build #/adding start buildInfo += "[" #increasing index to get new card i += 1 while (cardVector[i]) != "]": buildInfo += cardVector[i] i += 1 if cardVector[i] != "]": buildInfo += " " #adding end buildInfo += "] " else: #single card #no bs just write the card inside [ ] buildInfo += "["+cardVector[i]+"] " #increase the index i += 1 #addding the build info in "Table: " section of file f.write(buildInfo+"] ") buildInfo += "] "+cardVector[1] vectorCards.append(buildInfo) #adding the build owner info from vector to the content for build in vectorCards: f.write("\n\nBuild Owner: "+build) #last capturer f.write("\n\nLast Capturer: "+self.lastCapturer +"\n\nDeck: ") #Deck for card in self.gameDeck.getDeck(): f.write(card+" ") #adding the next Player f.write("\n\nNext Player: ") if self.humanTurn: f.write("Human") else: f.write("Computer") f.close() #check for changes for dealing cards, new round and end of the tournamemt def checkGameChanges(self): feedBack ="" dealTable = False #check if both player's hand is empty if self.human.getHandSize() ==0 and self.computer.getHandSize() == 0: if self.gameDeck.getDeckSize() == 0: #Round "<<round<<" Complete feedBack += "\n****** Round Complete ****** \n" #clear the table and store the cards to the pile of last capturer tableCards = self.gameTable.getAllCards() for card in tableCards: if self.lastCapturer == "Human": self.human.storePile(card[1]) else: self.computer.storePile(card[1]) #create new table self.gameTable = Table() #calculate and display score humanScoreInfo = self.calculatePlayerScore(self.human) computerScoreInfo = self.calculatePlayerScore(self.computer) humanScore = int(humanScoreInfo[0] ) computerScore = int(computerScoreInfo[0]) #check for player with higher num of cards if humanScoreInfo[1] > computerScoreInfo[1]: humanScore += 3 elif humanScoreInfo[1] < computerScoreInfo[1]: computerScore += 3 #check for player with higher num of spade cards if humanScoreInfo[2] > computerScoreInfo[2]: humanScore +=1 elif humanScoreInfo[2] < computerScoreInfo[2]: computerScore +=1 feedBack += "Total Num of Cards: Human: "+ str(humanScoreInfo[1])+" Computer: "+str(computerScoreInfo[1])+"\n Num of Spades: Human: "+ str(humanScoreInfo[2])+" Computer: "+str(computerScoreInfo[2])+"\n Score for this round: Human: "+str(humanScore)+" Computer: "+str(computerScore) #update score and round humanScore += int(self.human.getScore()) computerScore += int(self.computer.getScore()) self.human.setScore(humanScore) self.computer.setScore(computerScore) #get the final score to compare finalScoreHuman = self.human.getScore() finalScoreComputer = self.computer.getScore() feedBack += "\nTournament score: Human: "+str(finalScoreHuman)+" Computer: "+str(finalScoreComputer) #add the pile info feedBack+="\n Human Pile: " for card in self.human.getAllPileCards(): feedBack+= str(card)+" " feedBack+="\n Computer Pile: " for card in self.computer.getAllPileCards(): feedBack+= str(card)+" " #check if the score of any player is above 21 if finalScoreHuman > 21 or finalScoreComputer > 21: #find the winner feedBack += "\n****** Game Over ******\n Winner: " #std::cout<<"\tWinner of the game: " if finalScoreHuman > finalScoreComputer: feedBack+="Human" elif finalScoreHuman < finalScoreComputer: feedBack+="Computer" else: feedBack+="Draw" #exit return feedBack #increase the round num self.round+=1 #create new deck self.gameDeck = Deck(True) #clear pile for both player self.human.clearPile() self.computer.clearPile() #deal table dealTable =True #set the turn for next round based on last Capturer if self.lastCapturer == "Human": self.humanTurn = True else: self.humanTurn = False feedBack += "\n**Dealt New 4 Cards for each player**" self.newDealCards(dealTable) return feedBack #calculates and returns the score for given player pile,also finds # the num of total cards and num of spade cards def calculatePlayerScore(self,player): #varibles to store the info scoreData = [] score = 0 countSpade = 0 #get the list of pile cards from the player pile = player.getAllPileCards() for card in pile: if card[0] == 'S': countSpade+=1 score += self.scoreCalculator(card) #store the info in the vector scoreData.append(score) scoreData.append(len(pile)) scoreData.append(countSpade) return scoreData #Check the card for aces and DX and S2 and calculates the score def scoreCalculator(self, card): score = 0 if card == "CA" or card == "DA" or card == "SA" or card == "HA" or card == "S2": score = 1 elif card == "DX": score = 2 return score