def __init__(self, r_name, r_id, x_off, y_off, theta_offset): Human.__init__(self, r_name, r_id, x_off, y_off, theta_offset) #Initialise worker state to empty string self.worker_state = "" #Initialise dictionary of various robot coordinates self.robot_locations = {} #Array that stores coordinate information corresponding to orchard row gaps self.orchard_row_gaps = [] #This will hold the dictionary of properties defined in the config.properties file self.config = {} #Generate the coordinates for the orchard row gaps self.define_orchard_row_gaps() #This is the current orchard row gap that the worker will be travelling to, or is currently patrolling self.empty_row_target = [0, 0] #Keep track of the last row the worker patrolled self.last_patrolled_row = [0, 0] #Track the position of the robot which caused the worker to leave an orchard row self.detected_robot_position = [0, 0] #Create subscribers to the positions for both picker and carrier self.sub_to_picker_positions = rospy.Subscriber("picker_position", String, self.Robot_Locations_Callback) self.sub_to_carrier_positions = rospy.Subscriber("carrier_position", String, self.Robot_Locations_Callback) self.lock = threading.Lock() #Define the actions to be used for the action stack self._actions_ = { 0: self.move_forward, 1: self.goto_yx, 2: self.goto_xy, 3: self.turn, 4: self.stop, 5: self.go_to_empty_orchard_row, 6: self.patrol_orchard, 7: self.avoid_robot }
def __init__(self, timelimit): self.pygame = pygame self.pygame.init() self.fpsClock = pygame.time.Clock() self.board = Board() self.whitePlayer = Human(self, self.board, Board.white) self.blackPlayer = MinimaxAI(self, self.board, Board.black, timelimit) self.currentPlayer = self.blackPlayer self.screen = self.drawscreen()
def __init__(self, r_name, r_id, x_off, y_off, theta_offset): Human.__init__(self, r_name, r_id, x_off, y_off, theta_offset) #Initialise the publisher self.pub_to_dog = rospy.Publisher("visitor_dog_topic", String, queue_size=10) #Set the state to initially empty self.visitor_state = "" #Set the actions to be used by the Visitor class self._actions_ = { 0: self.move_forward, 1: self.goto_yx, 2: self.turn, 3: self.stop, 4: self.random_nav, 5: self.go_to_rand_location, 6: self.face_direction }
def __init__(self): Human.__init__(self) self.avatarType = AvatarTypes.Townfolk
class GUIboard(object): # Load pygame def __init__(self, timelimit): self.pygame = pygame self.pygame.init() self.fpsClock = pygame.time.Clock() self.board = Board() self.whitePlayer = Human(self, self.board, Board.white) self.blackPlayer = MinimaxAI(self, self.board, Board.black, timelimit) self.currentPlayer = self.blackPlayer self.screen = self.drawscreen() def drawscreen(self): # Setup screen sqs = 70 bs = 8*sqs screen = self.pygame.display.set_mode((bs, bs)) tit = 'Othello ala Linus och Kasper!' pygame.display.set_caption(tit) pygame.mouse.set_visible(True) self.myfont = self.pygame.font.SysFont("monospace", 20) return screen def updatescreen(self): black = pygame.Color(0, 0, 0) white = pygame.Color(255, 255, 255) green = pygame.Color(0, 128, 0) sqs = 70 bs = 8*sqs self.screen.fill(green) for y in xrange(8): for x in xrange(8): # Draw black background squares self.pygame.draw.rect(self.screen, black, (y*sqs, x*sqs, sqs, sqs), 2) # Draw coordinate label = self.myfont.render("("+str(y)+","+str(x)+")", 1, (0,0,0)) self.screen.blit(label, (x*sqs+5, y*sqs+5)) # Draw disks if self.board.grid[y][x] == Board.black: self.pygame.draw.circle(self.screen, black, (x*sqs+sqs/2, y*sqs+sqs/2), sqs/2, 0) elif self.board.grid[y][x] == Board.white: self.pygame.draw.circle(self.screen, white, (x*sqs+sqs/2, y*sqs+sqs/2), sqs/2, 0) def rungame(self): # Main application loop while True: self.updatescreen() self.pygame.display.update() self.fpsClock.tick(30) # Handle actions canWhite = self.board.canMakeMove(Board.white) canBlack = self.board.canMakeMove(Board.black) if not canWhite and not canBlack: print "Score (black, white):", self.board.score() while True: for event in self.pygame.event.get(): if event.type == QUIT: self.pygame.quit() sys.exit() elif self.currentPlayer == self.whitePlayer and canWhite: y,x = self.whitePlayer.makeMove() self.currentPlayer = self.blackPlayer elif self.currentPlayer == self.whitePlayer and not canWhite: self.currentPlayer = self.blackPlayer elif self.currentPlayer == self.blackPlayer and canBlack: y,x = self.blackPlayer.makeMove() self.currentPlayer = self.whitePlayer elif self.currentPlayer == self.blackPlayer and not canBlack: self.currentPlayer = self.whitePlayer
class Poker: def __init__(self): self.__human = Human(1200) self.__computer = Computer(1200) self.__bet = 0 self.__table = [] def NewGame(self): from time import sleep cont = 1 while self.__computer.Money() > 0 and self.__human.Money() > 0 and cont == 1: system("CLS") __bet = 0 deck = Deck() deck.Shuffle() for _ in range(2): self.__human.TakeACard(deck.Deal()) self.__computer.TakeACard(deck.Deal()) for _ in range(3): self.__table.append(deck.Deal()) self.__PrintTheGame__() sleep(4) self.__Bet__() system("CLS") self.__table.append(deck.Deal()) self.__PrintTheGame__() sleep(4) self.__Bet__() system("CLS") self.__table.append(deck.Deal()) self.__PrintTheGame__() sleep(4) self.__Bet__() system("CLS") sleep(6) self.__Winner__() sleep(3) system("CLS") cont = int(input("Continue?(1 - yes/0 - no): ")) def __PrintTheGame__(self): print("Your opponent’s money: " + str(self.__computer.Money()) + "\n") print("Table: ", end=" ") for card in self.__table: print(card, end=" ") print("\n") print("Your's money: " + str(self.__human.Money())) print("Your's hand: " + self.__human.StrHand()) def __Bet__(self): humanBet = self.__human.Bet() if humanBet == 0: self.__computer.ChangeMoney(-self.__bet) computerBet = self.__computer.Bet() if computerBet > humanBet: diff = computerBet - humanBet choise = int(input("Your's opponent bet is more on {0}\nCall?(1 - yes/ 0 - no): ".format(diff))) if choise == 1: humanBet = computerBet self.__human.ChangeMoney(diff) else: from random import randint if randint(1, 11) % 11 == 0: computerBet = humanBet self.__computer.ChangeMoney(computerBet - humanBet) self.__bet = humanBet + computerBet def __Winner__(self): sortedHumanHand = sorted(self.__human.Hand() + self.__table) sortedCompHand = sorted(self.__computer.Hand() + self.__table) if self.__RoyalFlush__(sortedHumanHand): self.__human.ChangeMoney(-self.__bet) print("You're win!\nYou have a Royal Flush!!") elif self.__RoyalFlush__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has a Royal Flush!!") elif self.__StraightFlush__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!nYou have a Straight Flush") elif self.__StraightFlush__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has a Straight Flush") elif self.__FourOfAKind__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have a Four of a kind") elif self.__FourOfAKind__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has a Four of a kind") elif self.__FullHouse__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have a Full House") elif self.__FullHouse__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has a Full House") elif self.__Flush__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have a Flush") elif self.__Flush__(sortedCompHand): self.__computer.ChangeMoney(-1 * self.__bet) print("Your's opponent are win\nYour opponent has a Flush") elif self.__Straight__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have a Straight") elif self.__Straight__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has a Straight") elif self.__Set__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have a Set") elif self.__Set__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has a Set") elif self.__TwoPairs__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have two Pairs") elif self.__TwoPairs__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has two Pairs") elif self.__Pair__(sortedHumanHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have a Pair") elif self.__Pair__(sortedCompHand): self.__computer.ChangeMoney(-1*self.__bet) print("Your's opponent are win\nYour opponent has a Pair") elif self.__High__(sortedHumanHand) > self.__High__(sortedCompHand): self.__human.ChangeMoney(-1*self.__bet) print("You're win!\nYou have a high card") else: self.__computer.ChangeMoney(-1 * self.__bet) print("Your's opponent are win\nYour opponent has a high card") def __RoyalFlush__(self, sortedHand): firstCardRank = sortedHand[0].Rank() firstCardSuit = sortedHand[0].Suit() flag = True for card in sortedHand: if card.Suit() != firstCardSuit or card.Rank() != firstCardRank: flag = False break else: firstCardRank += 1 return flag def __StraightFlush__(self, sortedhand): return self.__Straight__(sortedhand) and self.__Flush__(sortedhand) def __FourOfAKind__(self, sortedHand): count = 0 firstCardRank = sortedHand[0].Rank() for card in sortedHand: if card.Rank() == firstCardRank: count +=1 if count == 4: return True return False def __FullHouse__(self, sortedHand): newSortedHand = sortedHand.copy() for card in range(1, len(sortedHand) - 1): if sortedHand[card].Rank() == sortedHand[card + 1].Rank() and sortedHand[card].Rank() == sortedHand[card - 1].Rank(): del newSortedHand[card - 1] del newSortedHand[card] del newSortedHand[card + 1] break else: return False if self.__Pair__(newSortedHand): return True return False def __Flush__(self, sortedHand): count = 0 for card in range(len(sortedHand) - 1): if sortedHand[card].Suit() == sortedHand[card + 1].Suit(): count += 1 if count == 5: return True return False def __Straight__(self, sortedHand): count = 0 for card in range(len(sortedHand) - 1): if sortedHand[card].Rank() == sortedHand[card + 1].Rank() + 1: count += 1 if count == 5: return True return False def __Set__(self, sortedHand): for card in range(1, len(sortedHand) - 1): if sortedHand[card].Rank() == sortedHand[card + 1].Rank() and sortedHand[card].Rank() == sortedHand[card - 1].Rank(): return True return False def __TwoPairs__(self, sortedHand): newSortedHand = sortedHand.copy() for card in range(len(sortedHand) - 1): if sortedHand[card].Rank() == sortedHand[card + 1].Rank(): del newSortedHand[card] del newSortedHand[card + 1] break else: return False for card in range(len(newSortedHand) - 1): if newSortedHand[card].Rank() == newSortedHand[card + 1].Rank(): return True return False def __Pair__(self, sortedHand): for card in range(len(sortedHand) - 1): if sortedHand[card].Rank() == sortedHand[card + 1].Rank(): return True return False def __High__(self, sortedHand): high = sortedHand[0].Rank() for card in sortedHand: if card.Rank() > high: high = card.Rank() return high
def __init__(self, other=None): Human.__init__(self, other) self.avatarType = AvatarTypes.Pirate
def __init__(self, rect=None, color=None, deathSound=None): Human.__init__(self, rect, color, deathSound)
def __init__(self, firstName, lastName, id): Human.__init__(self, firstName, lastName, id)
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
s = f.read().strip().split("\n")[-1] slist = s.split(",") rate = float(slist[3]) learn([CNNAI(0, search_nodes=search_nodes, all_parameter_zero=True), CNNAI(1, search_nodes=search_nodes)], restart=True, initial_rate=rate, skip_first_selfplay=False) elif sys.argv[1] == "debug_learn": # 1つ目のAIを距離だけで考えるものとして、そこからどれだけ学習の結果強くなれるかを検証する debug_learn([CNNAI(0, search_nodes=search_nodes, v_is_dist=True, p_is_almost_flat=True), CNNAI(1, search_nodes=search_nodes, v_is_dist=True)]) elif sys.argv[1] == "view": AIs = [CNNAI(0, search_nodes=search_nodes, tau=0.5), CNNAI(1, search_nodes=search_nodes, tau=0.5)] AIs[0].load("./parameter/post.ckpt") AIs[1].load("./parameter/post.ckpt") normal_play(AIs) elif sys.argv[1] == "vs": AIs = [Human(0), CNNAI(1, search_nodes=search_nodes, tau=0.5)] AIs[1].load("./parameter/post.ckpt") normal_play(AIs) elif sys.argv[1] == "test": #np.random.seed(0) AIs = [CNNAI(0, search_nodes=search_nodes, tau=0.5), CNNAI(1, search_nodes=search_nodes, tau=0.5)] AIs[0].load("./parameter/epoch8.ckpt") AIs[1].load("./parameter/epoch8.ckpt") for i in range(100): print("============={}==============".format(i)) normal_play(AIs) elif sys.argv[1] == "measure": np.random.seed(0) game_num = 10 AIs = [CNNAI(0, search_nodes=search_nodes, tau=1), CNNAI(1, search_nodes=search_nodes, tau=1)] AIs[0].load("./parameter/post.ckpt")
class Game(object): """Driver for a single instance of a game""" #* ********************************************************************* #Function Name: __init__ #Purpose: Construct Game Object #Algorithm: #1) Create new Human Object #2) Create new Computer Object #3) Create new BoardView Object #4) Create new Board Object #5) Create new Tournament Object #Assistance Received: none #********************************************************************* */ def __init__(self): self.viewBoard = ViewBoard() self.board = Board() self.human = Human() self.computer = Computer() self.tournament = Tournament() # Getters def getHuman(self): return self.human def getComputer(self): return self.computer def getBoard(self): return self.board def getViewBoard(self): return self.viewBoard def getTournament(self): return self.tournament # Setters def setTournament(self, newTournament): self.tournament = newTournament def setBoard(self, newBoard): self.board = newBoard def setHuman(self, newHuman): self.human = newHuman def setComputer(self, newComputer): self.computer = newComputer # /* ********************************************************************* #Function Name: saveGame #Purpose: To save the game to a file #Parameters: # nextPlayer, string containing the next player #Return Value: void #Local Variables: # tempBoard, vector<vector<Die>> which is filled with the current state of the board # file, ostream object to save the file # fileName, string containing the filename #Algorithm: #1) Get filename from user #2) Loop through gameboard #3) Save 0 to file if space is empty #4) Write die to file if space is occupied #5) Write all the wins and the next player #6) Close file #Assistance Received: none #********************************************************************* */ def saveGame(self, nextPlayer): tempTournament = self.getTournament() tempBoardObj = self.getBoard() # Get gameboard tempBoard = tempBoardObj.getGameBoard() print("************************************") print("* ~~ Save Game ~~ *") print("************************************") print() fileName = str(input("Enter File Name: ")) fileName += ".txt" file = open(fileName, "w") file.write("Board:\n") for row in range(7, -1, -1): for col in range(0, 9): if (tempBoard[row][col].isEmpty() == True): file.write(" 0 ") else: file.write(tempBoard[row][col].displayDie() + " ") file.write("\n") file.write("\n") file.write("Computer Wins: " + str(tempTournament.getComputerWins()) + "\n\n") file.write("Human Wins: " + str(tempTournament.getHumanWins()) + "\n\n") file.write("Next Player: " + nextPlayer) file.close() #********************************************************************* #Function Name: loadGame #Purpose: Load a game from a save file #Parameters: None #Return Value: void #Local Variables: # file, fstream object which contains the loaded file # fileVec, 2D vector of strings which holds all the loaded gameboard in string form # gameBoard, 2D vector of die which holds all the loaded gameboard in die form # nextPlayer, string holding next player from the file # fileName, string containing the file name to open # iss, istringstream to parse out the file #Algorithm: #1) Get Filename #2) Open File #3) Loop until end of file #4) Using istringstream push each position on the board to the fileVec #5) When the board is complete get the number of wins and the next player #6) Loop through the fileVec parsing out the die #7) Using that data calculate all sides and create a new die #8) Push that to the correct position on the gameboard #9) Set the board in the game class #10) Call startFromLoad #Assistance Received: none #********************************************************************* */ def loadGame(self): tempBoard = Board() tempTournament = Tournament() MAX_COL = 9 MAX_ROW = 8 rowLine = 0 strboard = [[]] gameboard = [[Die() for j in range(MAX_COL)] for i in range(MAX_ROW)] print("************************************") print("* ~~ Load Game ~~ *") print("************************************") print() fileName = str(input("Enter File Name: ")) fileName += ".txt" file = open(fileName, 'r') # Skip first line containing Board: file.readline() for line in file: line = line.split(' ') for i in line: if (i != ''): strboard[rowLine].append(i) rowLine += 1 if (rowLine == MAX_ROW): break strboard.append([]) # Skip Blank file.readline() # Read computer wins string computerstr = file.readline() computerstr = computerstr.split(' ') computerwin = int(computerstr[2]) # Skip Blank file.readline() humanstr = file.readline() humanstr = humanstr.split(' ') humanwin = int(humanstr[2]) # Skip Blank file.readline() # Read Next Player next = file.readline() next = next.split(' ') nextPlayer = next[2] # Create Board iter = 0 for row in range(7, -1, -1): for col in range(0, 9): tmp = strboard[row][col] if (tmp != "0" and tmp != "0\n"): player = tmp[0] topNum = int(tmp[1]) rightNum = int(tmp[2]) gameboard[iter][col] = self.board.dieSwitch( topNum, rightNum, player) iter += 1 # Set Objects tempBoard.setGameBoard(gameboard) tempTournament.setComputerWins(computerwin) tempTournament.setHumanWins(humanwin) self.setTournament(tempTournament) self.setBoard(tempBoard) self.startGame(nextPlayer, False) # /* ********************************************************************* #Function Name: firstPlayer #Purpose: To randomly select first player #Parameters: #Return Value: The player who will go first #Local Variables: #human, an int that will contain the random number for the human #computer, an int that will contain the random number for the computer #player, a string containing the player who will go first #Algorithm: #1) Seed the random function with the current time #2) Start loop which continues if there is a tie #3) Randomly select a number 1-6 for human #4) Randomly select a number 1-6 for computer #5) Compare the two numbers and return the player with highest value #Assistance Received: none #********************************************************************* */ def firstPlayer(self): while True: human = randrange(1, 7) computer = randrange(1, 7) print( " +=================================================+" ) print( " | Roll a die to see who goes first! |" ) print( " | Please Select an Option |" ) print( " | |" ) print(" | You rolled a " + str(human) + " |") print(" | Computer rolled a " + str(computer) + " |") print( " | |" ) if (human > computer): print( " | You go first! |" ) print( " +=================================================+" ) player = "Human" return player elif (computer > human): print( " | Computer goes first |" ) print( " +=================================================+" ) player = "Computer" return player elif (computer == human): print( " | It's a tie! |" ) print( " | Roll again... |" ) print( " +=================================================+" ) continue # /* ********************************************************************* #Function Name: displayWinner #Purpose: Display the winner of the tournament #Parameters: None #Return Value: void #Local Variables: # computerWins, an int containing the total number of computer wins # humanWins, an int containing the total number of human wins # winner, string containing the winner message #Algorithm: #1) Check if computerWins > humanWins or vice versa #2) Set appropriate winner string #3) Display the total number of wins each and the winner string #Assistance Received: none #********************************************************************* */ def displayWinner(self): tempTournament = self.getTournament() computerWins = tempTournament.getComputerWins() humanWins = tempTournament.getHumanWins() if (computerWins > humanWins): winner = "* You lose... *" elif (computerWins < humanWins): winner = "* You win!!! *" else: winner = "* It's a tie! *" print("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*") print("* ~~ Tournament Results ~~ *") print("* The Computer finished with " + str(computerWins) + " wins *") print("* You finished with " + str(humanWins) + " wins *") print("* *") print(winner) print("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*") print("~~ Good Bye ~~") os.system('pause') # Restart the Program exit() # /* ********************************************************************* #Function Name: playAgain #Purpose: Ask the player if they would like to play again, if not display winner #Parameters: None #Return Value: return true to start another game #Assistance Received: none #********************************************************************* */ def playAgain(self): while True: try: print("****************************************************") print("* Would you like to play another round? *") print("* Enter 'y' for yes or 'n' for no *") print("****************************************************") print() selection = str(input(" Selection: ")) except ValueError: print("Invalid Response. Please try again") continue if (selection != 'y' and selection != 'n'): print("Invalid Response. Please try again") continue else: break if (selection == 'y'): return True elif (selection == 'n'): self.displayWinner() return False # /* ********************************************************************* #Function Name: askHel #Purpose: Prompt the user if they need help #Parameters: None #Return Value: Void #Assistance Received: none #********************************************************************* */ def askHelp(self): tempHuman = self.getHuman() while True: try: print("****************************************************") print("* ~~ Help? ~~ *") print("* Would you like some help? *") print("* Enter 'y' for yes or 'n' for no *") print("****************************************************") print() selection = str(input(" Selection: ")) except ValueError: print("Invalid Response. Please try again") continue if (selection != 'y' and selection != 'n'): print("Invalid Response. Please try again") continue else: break if (selection == 'y'): tempHuman.help() # /* ********************************************************************* #Function Name: savePrompt #Purpose: Ask user if they would like to save #Parameters: # nextPlayer, string containing the next player #Return Value: return true if user wishes to save #Assistance Received: none #********************************************************************* */ def savePrompt(self, nextPlayer): while True: try: print("****************************************************") print("* ~~ Save & Exit? ~~ *") print("* Would you like to save and exit the game? *") print("* Enter 'y' for yes or 'n' for no *") print("****************************************************") print() selection = str(input(" Selection: ")) except ValueError: print("Invalid Response. Please try again") continue if (selection != 'y' and selection != 'n'): print("Invalid Response. Please try again") continue else: break if (selection == 'y'): self.saveGame(nextPlayer) print() print("~~ Good Bye ~~") os.system('pause') # Exit Program exit() elif (selection == 'n'): return False # /* ********************************************************************* #Function Name: setWin #Purpose: Add a win to the player who has won the game #Parameters: # player, string containing the player #Return Value: return true on successful execution #Algorithm: #1) Set win++ depending on the player passed #Assistance Received: none #********************************************************************* */ def setWin(self, player): tempTournament = self.getTournament() tempHuman = self.getHuman() tempComputer = self.getComputer() if (player == "H"): if (tempHuman.checkHumanWin()): humanWins = tempTournament.getHumanWins() humanWins += 1 tempTournament.setHumanWins(humanWins) self.setTournament(tempTournament) return True else: if (tempComputer.checkComputerWin()): computerWins = tempTournament.getComputerWins() computerWins += 1 tempTournament.setComputerWins(computerWins) self.setTournament(tempTournament) return True return False # /* ********************************************************************* #Function Name: humanMove #Purpose: Execute a single round for the human player #Return Value: void #Algorithm: #1) Get the board, human, and viewboard and save to temp objects #2) Display the board #3) Ask to save #4) Set the board in the human class to manipulate #5) Ask for help #6) Display the board again #7) Call the Human play function and set the game class board #Assistance Received: none #********************************************************************* */ def humanMove(self): tempBoardObj = self.getBoard() tempHuman = self.getHuman() tempView = self.getViewBoard() tempBoard = tempBoardObj.getGameBoard() # Display Board tempView.displayBoard(tempBoard) # Ask Save self.savePrompt("Human") # Set board in human class tempHuman.setBoard(tempBoardObj) # Ask Help self.askHelp() # Display Board again tempView.displayBoard(tempBoard) # Play and set board self.setBoard(tempHuman.play()) tempHuman.setBoard(self.getBoard()) self.setHuman(tempHuman) # /* ********************************************************************* #Function Name: computerMove #Purpose: Execute a single round for the computer player #Return Value: void #Algorithm: #1) Get the board, human, and viewboard and save to temp objects #2) Display the board #3) Ask to save #4) Set the board in the computer class to manipulate #5) Call the Computer play function and set the game class board #Assistance Received: none #********************************************************************* */ def computerMove(self): tempBoardObj = self.getBoard() tempComputer = self.getComputer() tempView = self.getViewBoard() tempBoard = tempBoardObj.getGameBoard() # Display Board tempView.displayBoard(tempBoard) # Ask Save self.savePrompt("Computer") # Set board in Computer class tempComputer.setBoard(tempBoardObj) # Play and set board self.setBoard(tempComputer.play()) tempComputer.setBoard(self.getBoard()) self.setComputer(tempComputer) # /* ********************************************************************* #Function Name: startGame #Purpose: Start a round of the game #Parameters: None #Return Value: void #Local Variables: # player, string containing the player who goes first #Algorithm: #1) Run firstPlayer function to get player who goes first #2) Set the boardObj to the game class #3) Loop until endGame is true #4) execute a round in the player class #5) At end of round, ask player if they would like to play again #6) Reset the board #7) Recursively run startTournament again #Assistance Received: none #********************************************************************* */ def startGame(self, player, newGame): tempView = self.getViewBoard() if (newGame == True): # Get Starting Player player = self.firstPlayer() endGame = False if (player == "Human"): while (endGame == False): self.humanMove() if (self.setWin("H") == True): tempView.displayBoard(self.getBoard().getGameBoard()) print() print() print("*****************************************") print("* You Win! *") print("* Congrats, want a medal? *") print("*****************************************") print() if (self.playAgain() == True): tempBoard = Board() self.setBoard(tempBoard) self.human.setBoard(tempBoard) self.computer.setBoard(tempBoard) self.startGame("TEMP", True) self.computerMove() if (self.setWin("C") == True): tempView.displayBoard(self.getBoard().getGameBoard()) print() print() print("*****************************************") print("* You Lose *") print("* Maybe Next Time... *") print("*****************************************") print() if (self.playAgain() == True): tempBoard = Board() self.setBoard(tempBoard) self.human.setBoard(tempBoard) self.computer.setBoard(tempBoard) self.startGame("TEMP", True) else: while (endGame == False): self.computerMove() if (self.setWin("C") == True): tempView.displayBoard(self.getBoard().getGameBoard()) print() print() print("*****************************************") print("* You Lose *") print("* Maybe Next Time... *") print("*****************************************") print() if (self.playAgain() == True): tempBoard = Board() self.setBoard(tempBoard) self.human.setBoard(tempBoard) self.computer.setBoard(tempBoard) self.startGame() self.humanMove() if (self.setWin("H") == True): tempView.displayBoard(self.getBoard().getGameBoard()) print() print() print("*****************************************") print("* You Win! *") print("* Next time I won't go so easy on you *") print("*****************************************") print() if (self.playAgain() == True): tempBoard = Board() self.setBoard(tempBoard) self.human.setBoard(tempBoard) self.computer.setBoard(tempBoard) self.startGame()
def __init__(self): self.viewBoard = ViewBoard() self.board = Board() self.human = Human() self.computer = Computer() self.tournament = Tournament()
class Game: #Default Constructor def __init__(self): #GameBoard, display and notification objects self.board = Board() self.boardView = BoardView() self.notifications = Notifications() #Player objects self.human = Human() self.computer = Computer() #Toss Variables self.humanDieToss = 0 self.computerDieToss = 0 #Control variables self.humanTurn = False self.computerTurn = False #Variables to store user input of coordinates self.startRow = 0 self.startCol = 0 self.endRow = 0 self.endCol = 0 #1 for vertical first, 2 for lateral first self.path = 0 """ ********************************************************************* Function Name: implement_game Purpose: Runs a full game until someone wins or user requests serialization Parameters: restoringGame, boolean value stating whether a restore of previous game was requested by user nextPlayer, a string that contains who's turn is next (if restoring) (Computer or Human) Return Value: 'c' if bot wins, 'h' if human wins, 'S' if serialization requested during bot turn, 's' if serialization requested during human turn Local Variables: none Assistance Received: none ********************************************************************* """ #Implements a Round. #Return value is 'h' for human winner, 'c' for computer winner, 'S' for serializing during computer's turn, 's' for serializing during human's turn def implement_game(self, restoringGame, nextPlayer=""): #Set the turns if restoring a game from saved state if restoringGame: if (nextPlayer == "Computer"): self.computerTurn = True if (nextPlayer == "Human"): self.humanTurn = True #Draw Initial Board self.boardView.draw_board(self.board) #Conduct a toss if the controls haven't been assigned while restoring if (not self.humanTurn and not self.computerTurn): self.toss_to_begin() #Continue the loop until one of the king is captured, one of the key squares gets occupied or user chooses to serialize and quit while True: refresh = False #If it is computer's turn if self.computerTurn: self.notifications.msg_turns("COMPUTER'S TURN") if (self.computer.play(self.board, False)): #Transfer Controls self.computerTurn = False self.humanTurn = True self.notifications.msg_turns("BOARD AFTER COMPUTER'S MOVE") refresh = True #Using this boolean to prevent human's loop from running immediately else: continue #If it is human's Turn if not refresh: if self.humanTurn: self.notifications.msg_turns("YOUR TURN") if self.turn_help_mode_on(): self.notifications.msg_helpmode_on() #Calling computer Play in Help Mode self.computer.play(self.board, True) self.get_user_input() if (self.human.play(self.startRow, self.startCol, self.endRow, self.endCol, self.board, self.path)): self.humanTurn = False self.computerTurn = True #Transferring controls self.notifications.msg_turns( "BOARD AFTER HUMAN'S MOVE") else: self.notifications.msg_invalid_move() continue #After the move is made #Re-draw the board after each move self.boardView.draw_board(self.board) #If game over condition met if (self.game_over_condition_met()): #Whoever just received the control is the one who lost if self.humanTurn: self.notifications.msg_game_over("COMPUTER") return 'c' #Bot Winner else: self.notifications.msg_game_over("HUMAN") return 'h' #Human Winner """Stop the game and return if user wants to serialize return 'S' if serializing during computer's turn, 's' if serializing during human's turn""" if self.user_wants_to_serialize(): if self.computerTurn: return 'S' if self.humanTurn: return 's' """ ********************************************************************* Function Name: turn_help_mode_on Purpose: Ask human player if they want to turn help mode on Parameters: none Return Value: true if user requests help mode, false otherwise Local Variables: none Assistance Received: none ********************************************************************* """ # Receives user input on whether they want to turn on help mode def turn_help_mode_on(self): #Continue asking user for input until they press 'y' or 'n' while True: self.notifications.msg_help_mode_prompt() input = getche() if (input == 'y' or input == 'Y'): return True if (input == 'n' or input == 'N'): return False self.notifications.msg_improper_input() """ ********************************************************************* Function Name: user_wants_to_serialize Purpose: Ask human player if they want to serialize Parameters: none Return Value: true if user requests serialization, false otherwise Local Variables: none Assistance Received: none ********************************************************************* """ # Asks if user wants to serialize & returns true if user wants to serialize def user_wants_to_serialize(self): #Continue asking user for input until they press 'y' or 'n' while True: self.notifications.msg_serialize_prompt() input = getche() if (input == 'y' or input == 'Y'): return True if (input == 'n' or input == 'N'): return False self.notifications.msg_improper_input() """ ********************************************************************* Function Name: game_over_condition_met Purpose: To check if the condition for game over has been met Parameters: none Return Value: true if condition met for game to be over, false otherwise Local Variables: none Assistance Received: none ********************************************************************* """ # Checks if the condition to end the game has been met def game_over_condition_met(self): #If one of the kings captured if (self.board.get_human_king().captured or self.board.get_bot_king().captured): return True #If the human key square is occupied by the bots king die if (self.board.get_square_resident(0, 4) != None): if (self.board.get_square_resident(0, 4).botOperated): if (self.board.get_square_resident(0, 4).king): return True #If the computer key square is occupied by the Human king die if (self.board.get_square_resident(7, 4) != None): if (not self.board.get_square_resident(7, 4).botOperated): if (self.board.get_square_resident(7, 4).king): return True #If none of the game over conditions are met return False """ ********************************************************************* Function Name: get_user_input Purpose: To get user input for coordinates Parameters: none Return Value: none Local Variables: none Assistance Received: none ********************************************************************* """ # Gets user input for coordinates if it is a human's turn def get_user_input(self): self.startRow = 0 self.startCol = 0 self.endRow = 0 self.endCol = 0 self.path = 0 #Continue asking user for input until they press all the digits #Ask for origin row while True: self.notifications.msg_enter_origin_row() input = getche() try: self.startRow = int(input) break except ValueError: self.notifications.msg_improper_input() #Ask for origin column while True: self.notifications.msg_enter_origin_column() input = getche() try: self.startCol = int(input) break except ValueError: self.notifications.msg_improper_input() #Ask for destination row while True: self.notifications.msg_enter_destination_row() input = getche() try: self.endRow = int(input) break except ValueError: self.notifications.msg_improper_input() #Ask for destination column while True: self.notifications.msg_enter_destination_column() input = getche() try: self.endCol = int(input) break except ValueError: self.notifications.msg_improper_input() #In case of a 90 degree turn, ask the path preference as well if ((self.startRow != self.endRow) and (self.startCol != self.endCol)): while True: self.notifications.msg_90degree_path_selection() input = getche() try: if (int(input) == 1 or int(input) == 2): self.path = int(input) break except ValueError: self.notifications.msg_improper_input() """ ********************************************************************* Function Name: toss_to_begin Purpose: To conduct a toss and set the turn of appropriate player to true Parameters: none Return Value: none Local Variables: none Assistance Received: none ********************************************************************* """ # Does a toss to determine which team will start the game def toss_to_begin(self): #Continue until both have different toss results while True: self.humanDieToss = randint(1, 6) self.computerDieToss = randint(1, 6) if (self.humanDieToss != self.computerDieToss): break #Whoever has the highest number on top - wins the toss if (self.humanDieToss > self.computerDieToss): self.humanTurn = True self.notifications.msg_toss_results("You", self.humanDieToss, self.computerDieToss) else: self.computerTurn = True self.notifications.msg_toss_results("Computer", self.humanDieToss, self.computerDieToss)
import abc from Human import Human class AbsCompare(metaclass=abc.ABCMeta): @abc.abstractmethod def compare(self, human1, human2): pass class HeightCompare(AbsCompare): def compare(self, human1, human2): if human1.height > human2.height: return 1 else: return -1 class WeightCompare(AbsCompare): def compare(self, human1, human2): if human1.weight > human2.weight: return 1 else: return -1 if __name__ == 'main': height = HeightCompare() human1 = Human('tanaka', 4, 6, 3) human2 = Human('takesi', 6, 3, 4) x = height.compare(human1, human2)
def __init__(self): self.__human = Human(1200) self.__computer = Computer(1200) self.__bet = 0 self.__table = []
def __init__(self): self.player_one = Player() self.player_two = Player() self.computer = Computer() self.human = Human()
def create_human(self, position, strength=4, cooldown=0): self.is_player_on_board = True human = Human(self, position, strength, cooldown) self.add_organism_to_world(human) self.human = human self.update_labels()
# order that they should play player_list = [] # The parameters should be specified in a json file. The file will contain # the players/types of players, the number of simulations to run, a # flag to indicate whether we should shuffle the order of play, and a # flag to determine if we want to write to a csv file filename = "catan_input.json" index = 1 with open(filename) as f: data = json.load(f) current_nn = None for player in data["players"]: if player["type"] == "human": player_list.append(Human(index)) elif player["type"] == "random": player_list.append(RandomPlayer(index)) elif player["type"] == "MCTS": MCTS_player = MCTSPlayer(index, int(player["num_simulations"])) player_list.append(MCTS_player) elif player["type"] == "MCTSNN": player_list.append(MCTSNNPlayer(index, int(player["num_simulations"]))) modelFile = os.path.join("trainExamplesMCTS/", "temp.pth.tar") current_nn = nn() if os.path.isfile(modelFile): print("using saved weights!") current_nn.nnet.model.load_weights(modelFile) elif player["type"] == "NN": player_list.append(NNetPlayer(index, int(player["num_simulations"]))) modelFile = os.path.join("trainExamplesMCTS/", "temp.pth.tar")
from Human import Human human = Human(id="@human", name="human", age=17, description="New Human") print(Human)
from Creature import Creature from God import God from Human import Human God1 = God('Father', 'True', 'False', 'True') human1 = Human('Ivan', 'True', 'man', 'True') print(God1) print(Human)
def game_loop(self): if self.difficulty == 1: speed = 5 distance = 30 elif self.difficulty == 2: speed = 6 distance = 40 elif self.difficulty == 3: speed = 8 distance = 40 # fill screen with black self.screen.fill((0, 0, 0)) # add scoreboard font = pygame.font.Font('freesansbold.ttf', 32) score1 = 0 score1_text = font.render(str(score1), True, (255, 255, 255)) score1_rect = score1_text.get_rect() score2 = 0 score2_text = font.render(str(score2), True, (255, 255, 255)) score2_rect = score2_text.get_rect() score1_rect.center = (self.screen_width / 2 - 50, 20) score2_rect.center = (self.screen_width / 2 + 50, 20) # add two paddles paddle_width = 20 paddle_height = 110 # paddle starting coordinates init_x_1 = 5 * self.screen_width / 6 - paddle_width / 2 init_y_1 = self.screen_height / 2 - paddle_height / 2 init_x_2 = self.screen_width / 6 - paddle_width / 2 init_y_2 = self.screen_height / 2 - paddle_height / 2 # create paddles right_paddle = Paddle(paddle_width, paddle_height, init_x_1, init_y_1) left_paddle = Paddle(paddle_width, paddle_height, init_x_2, init_y_2) # create first paddle right_paddle.rect.x = init_x_1 # update position of paddle right_paddle.rect.y = init_y_1 self.screen.blit(right_paddle.surf, (init_x_1, init_y_1)) # put paddle on screen # create second paddle left_paddle.rect.x = init_x_2 # update position of paddle left_paddle.rect.y = init_y_2 self.screen.blit(left_paddle.surf, (init_x_2, init_y_2)) # create human characters human_1 = Human(right_paddle, self.screen_height, K_UP, K_DOWN) # create second human if necessary if self.gamemode == 1: human_2 = Human(left_paddle, self.screen_height, K_a, K_z) # create computer if necessary elif self.gamemode == 2: computer = Computer(left_paddle, self.screen_height, distance) # create ball ball_len = 10 init_x_ball = self.screen_width / 2 init_y_ball = self.screen_height / 2 ball = Ball(ball_len, init_x_ball, init_y_ball, speed, self.screen_height, self.screen_width) self.screen.blit(ball.surf, (init_x_ball, init_y_ball)) # put ball on screen # keep game running until closed by user on = True # as long as this while loop is running (and by extension, the program), # the window stays open while on: # check for quit by user for event in pygame.event.get(): if event.type == pygame.QUIT: on = False # update background before showing other objects self.screen.fill((0, 0, 0)) # check for key press pressed_keys = pygame.key.get_pressed() # if key pressed, move paddle human_1.update(pressed_keys) if self.gamemode == 1: human_2.update(pressed_keys) elif self.gamemode == 2: computer.update(ball.rect.x, ball.rect.y) # check for collision if pygame.sprite.collide_rect(ball, right_paddle): ball.reverse() elif pygame.sprite.collide_rect(ball, left_paddle): ball.reverse() if ball.rect.right <= 0: ball.reset() ball.x_speed = ball.init_speed score2 += 1 score2_text = font.render(str(score2), True, (255, 255, 255)) if ball.rect.left >= ball.screen_width: ball.reset() ball.x_speed = -ball.init_speed score1 += 1 score1_text = font.render(str(score1), True, (255, 255, 255)) # update ball position ball.update() # update graphics self.screen.blit(right_paddle.surf, right_paddle.rect) self.screen.blit(left_paddle.surf, left_paddle.rect) self.screen.blit(ball.surf, ball.rect) self.screen.blit(score1_text, score1_rect) self.screen.blit(score2_text, score2_rect) # flip (refresh) the screen pygame.display.flip() pygame.display.quit() pygame.quit() sys.exit()
def __init__(self, rect=None, color=None, deathSound=None): Human.__init__(self, rect, color, deathSound) Alive.count += 1 self.aliveID = Alive.count self.MAX_SPEED_X = 9.0 self.MAX_SPEED_Y = 9.0
# ширина окна, 19 блоков по 64 пикселя w = 64 * 19 # высота окна, 10 блоков по 84 пикселя h = 84 * 10 size = w, h screen = pygame.display.set_mode(size) # запускаем таймер 60 fps clock = pygame.time.Clock() fps = 60 running = True shift = False # создаем человека human = Human() # создаем пулю bullet = Bullet() # создаем пулю field = Field() # создаем красный портал red_portal = Portal('red_vert.png', 'red_horz.png') # создаем синий портал blue_portal = Portal('blue_vert.png', 'blue_horz.png') # создаем надпись на экране с картинкой label = Label(w, h) # создаем меню menu = Menu(w, h)
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")
cv.imshow("Plane", cv.resize(plane, None, None, 5, 5, cv.INTER_NEAREST)) # 給大約各 100 位男女,隨機分配真實分數 list___men, list_women = [], [] list_2D_plane = [i for i in range(70)] #= np.ndarray(shape=(70, 70)) for i in range(len(list_2D_plane)): list_2D_plane[i] = [i for i in range(70)] for j in range(len(list_2D_plane[i])): rand_case = np.random.randint(0, 3) # python style switch-case list_2D_plane[i][j] = { 0: None, 1: Human('M', np.random.randint(0, 100)), 2: Human('F', np.random.randint(0, 100)) }[rand_case] display_plane(list_2D_plane) print("初始值") cv.waitKey(0) for T in range(1000): # print("T={}".format(T)) # 找到周圍最高分位置 for i in range(len(list_2D_plane)): for j in range(len(list_2D_plane[i])): if (None == list_2D_plane[i][j]): continue #這個位置沒人 list_2D_plane[i][j].set_find_round_highest_xy(i, j, list_2D_plane)
races_class_list = [] for char in races_list: races_class_list.append(char.replace("-","_")) very_common_races_file.close() common_races_file.close() exotic_races_file.close() """ LOCATIONS/HOMES """ vren = Home("Vren", 0.34, {Human(): 0.46, Elf(): 0.08, Dwarf(): 0.08, Halfling(): 0.10, Dragonborn(): 0.02, Gnome(): 0.02, Half_elf(): 0.03, Half_orc(): 0.07, Tiefling(): 0.03, Goliath(): 0.02, Firbolg(): 0.01, Tabaxi(): 0.01, Aarakocra(): 0.00, Aasimar(): 0.02, Genasi(): 0.02, Kenku(): 0.00, Lizardfolk(): 0.01, Minotaur(): 0.01, Tortle(): 0.01, Loxodon(): 0.00}) enil = Home("Enil", 0.33, {Human(): 0.42, Elf(): 0.25, Dwarf(): 0.03, Halfling(): 0.04, Dragonborn(): 0.01, Gnome(): 0.03, Half_elf(): 0.10, Half_orc(): 0.01, Tiefling(): 0.01, Goliath(): 0.01, Firbolg(): 0.02, Tabaxi(): 0.02, Aarakocra(): 0.00, Aasimar(): 0.01, Genasi(): 0.01, Kenku(): 0.00, Lizardfolk(): 0.01, Minotaur(): 0.00, Tortle(): 0.02, Loxodon(): 0.00}) skyhold = Home("Skyhold", 0.33, {Human(): 0.45, Elf(): 0.02, Dwarf(): 0.20, Halfling(): 0.10, Dragonborn(): 0.01, Gnome(): 0.05, Half_elf(): 0.02, Half_orc(): 0.05, Tiefling(): 0.01, Goliath(): 0.05, Firbolg(): 0.01, Tabaxi(): 0.00, Aarakocra(): 0.00, Aasimar(): 0.01, Genasi(): 0.01, Kenku(): 0.00, Lizardfolk(): 0.00, Minotaur(): 0.01, Tortle(): 0.00, Loxodon(): 0.00}) locations = [vren, enil, skyhold]
def run_game(player1, player2, loaded_model, iterations): grid = np.full((3, 3), 0) # create the game g = Game(grid) agent1 = Agent() agent2 = Agent() human = Human() score = 0 moves = [] output = 0 # iterations = 1000 it = 0 X_wins = 0 O_wins = 0 Draws = 0 while it < iterations: # The moves for each game for i in ["X", "O"]: while True: if i == "X": loc = agent1.set_location(grid, player1, loaded_model) # loc = human.set_location(grid) # Make sure the move is to a blank space before exiting the loop if g.make_move(loc, -1): break if i == "O": loc = agent2.set_location(grid, player2, loaded_model) # loc = human.set_location(grid) # Make sure the move is to a blank space before exiting the loop if g.make_move(loc, 1): break # print(grid) res = g.check_win(grid) last_state = grid.tolist() moves.append(last_state) # Goes here if there is a result if res: print("Game: " + str(it)) print(res) # X wins if res[:1] == 'X': X_wins += 1 grid = np.full((3, 3), 0) g = Game(grid) output = -1 # O wins elif res[:1] == 'O': O_wins += 1 grid = np.full((3, 3), 0) g = Game(grid) output = 1 # Draw else: Draws += 1 grid = np.full((3, 3), 0) g = Game(grid) output = 0 it += 1 # If the game is won by less than nine moves then append the last board state to make the array 9 long. # Not sure how to make Keras deal with uneven data sizes while len(moves) < 9: moves.append(last_state) for m in moves: history.append((output, copy.deepcopy(m))) moves = [] break return history, X_wins, O_wins, Draws
import numpy as np from Human import Human env = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, -1, 0], [0, 0, 0, 0]]) human = Human(environment=env, beta=10, discount=0.9, robot_goal=[3, 3], grid_size=[4, 4]) print(human.give_correction([1, 2], 2))
class Game: def __init__(self): self.player0 = Human() self.player1 = None def single_player(self): """ single player game against the computer, with option for easy/hard mode :return: """ mode = input('Choose game mode (easy/hard): ').lower() while mode not in ['easy', 'hard']: mode = input('please enter a valid input: ') self.player1 = Computer(mode) self.player0.place_battleships() self.player1.place_battleships() while True: result = self.player0.turn(self.player1) if result == 'win': print('player 0 has won!') return result = self.player1.turn(self.player0) if result == 'win': print('player 1 has won!') return def multi_player(self): """ multiplayer game, the second player can join through running SecondPlayer.py :return: """ self.player0.output('waiting for another player...') server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((socket.gethostname(), 1234)) server.listen(1) conn, addr = server.accept() self.player1 = Human(conn) self.player1.output('waiting for opponent to place battleships...') self.player0.place_battleships() self.player0.output('waiting for opponent to place battleships...') self.player1.place_battleships() while True: self.player1.output('Opponent\'s turn:') result = self.player0.turn(self.player1) if result == 'win': self.player0.output('player 0 has won!') self.player1.output('player 0 has won!') return self.player0.output('Opponent\'s turn:') result = self.player1.turn(self.player0) if result == 'win': self.player0.output('player 1 has won!') self.player1.output('player 1 has won!') return
def sex(man, woman, name): return Human(name)
def test_human(self): human = Human("testName", "assets/shy.png", 50, 50) self.assertTrue(type(human) is Human)
class World(object): """description of class""" def __init__(self, app): self.__organisms = [] self.__born = [] self.__dead = [] self.__sheeps = [] self.__heracleums = [] self.__organismsC = 0 self.__start = False self.__changed = False self.__layout = Layout(self, app) @property def age(self): self.__organismsC += 1 return self.__organismsC @age.setter def age(self, value): self.__organismsC = value @property def start(self): return self.__start @start.setter def start(self, value): self.__start = value @property def layout(self): return self.__layout @property def finish(self): return self.__player.isAlive @property def input(self): pass @input.setter def input(self, code): self.__player.input = code def __Populate(self, n): for i in range(n): for entity in Entities: o = entity.Create() #o = Entities.CreateString("Fox") o.age = self.age o.world = self self.AddToWorld(o, Navigation.NULL_POINT) def __ClearLegend(self): legend = self.layout.legend legend.Clear() def NextTurn(self): self.Notify("New turn!") if len(self.__born) != 0: for o in self.__born: self.__organisms.append(o) self.__born.clear() self.__born.sort(key = Organism.compareTo) for o in self.__organisms: if o.isAlive == True: o.Action() if len(self.__dead) != 0: for o in self.__dead: self.__organisms.remove(o) self.__dead.clear() if self.__changed == True: for sheep in self.__sheeps: p = self.__SeekClosest(sheep) sheep.target = p self.__change = False def __SeekClosest(self, sheep): if len(self.__heracleums) == 0: return None max = -1 seek = None for heracleum in self.__heracleums: result = 0 result += abs(sheep.location.x - heracleum.location.x) result += abs(sheep.location.y - heracleum.location.y) if (max == -1) or result < max: max = result seek = heracleum.location return seek def WorldInit(self, oc): rows = self.layout.height cols = self.layout.width self.__board = Board(cols, rows) self.__player = Human(self.age, self) self.AddToWorld(self.__player, Navigation.NULL_POINT) self.__Populate(oc) def Notify(self, s): self.__layout.Print(s) def AddToWorld(self, o, p): self.__born.append(o) if p == Navigation.NULL_POINT: self.__board.SetAt(o) else: self.__board.SetAtPoint(p, o) self.__layout.Update(o) if isinstance(o, CyberSheep.CyberSheep): self.__sheeps.append(o) if isinstance(o, HeracleumSosnowskyi.HeracleumSosnowskyi): self.__heracleums.append(o) self.__changed = True def RemoveFromWorld(self, o): self.__layout.Clear(o.location) self.__board.KillAt(o.location) self.__dead.append(o) if isinstance(o, CyberSheep.CyberSheep): self.__sheeps.remove(o) if isinstance(o, HeracleumSosnowskyi.HeracleumSosnowskyi): self.__heracleums.remove(o) self.__changed = True def MassRemoveFromWorld(self, s, p, foo): x = 0 if p.x - 1 < 0 else p.x - 1 y = 0 if p.y - 1 < 0 else p.y - 1 yMax = p.x if p.x + 1 == self.__board.row else p.x + 1 xMax = p.y if p.y + 1 == self.__board.col else p.y + 1 temp = Point(0, 0) for i in range(x, xMax + 1): for j in range(y, yMax + 1): if (i == p.x) and (y == p.y): continue temp.set(i, j) o = self.__board.GetAt(temp) if o == None: continue if foo(o) == False: continue else: o.Kill(s) def PointValidate(self, p): return self.__board.Validate(p) def SeekForFree(self, p): return self.__board.SeekForFree(p) def GetAt(self, p): return self.__board.GetAt(p) def MoveTo(self, p, o): self.__layout.Clear(o.location) self.__board.SetAtPoint(p, o) self.__layout.Update(o) def LegendUpdate(self, dir): self.__ClearLegend() legend = self.layout.legend legend.AppendText("STATISTICS:\n") legend.AppendText("Strength: " + str(self.__player.strength) + "\n") legend.AppendText("Position: " + self.__player.location.string + "\n") legend.AppendText("\n") if dir != WorldDirections.DIR_NULL: legend.AppendText("Current direction: " + Navigation.string(dir) + "\n") legend.AppendText("\n") legend.AppendText("Cooldown: " + str(self.__player.cooldown) + "\n") legend.AppendText("Duration: " + str(self.__player.duration) + "\n") if self.__player.duration > 0: legend.AppendText("\n") legend.AppendText("Player empowered.\n") def ClearInput(self): self.__direction = WorldDirections.DIR_NULL def Save(self, e): f = open("C:/Users/abc/source/repos/PythonApplication1/PythonApplication1/General/Resources/save.txt", "w") #saving self.Notify("Saving...") #world f.write("%d\n" %self.__organismsC) #board f.write("%d\n%d\n" %(self.__board.row, self.__board.col)) p = Point(0, 0) #organisms for y in range(self.__board.row): for x in range(self.__board.col): p.set(x, y) o = self.GetAt(p) if o == None: f.write("%d\n" %0) else: f.write("%d\n%c\n%d\n%d\n" %(1, o.token, o.age, o.strength)) #born f.write("%d\n" %len(self.__born)) for o in self.__born: if o == None: f.write("%d\n" %0) else: f.write("%d\n%d\n%d\n" %(1, o.location.x, o.location.y)) #dead f.write("%d\n" %len(self.__dead)) for o in self.__dead: if o == None: f.write("%d\n" %0) else: f.write("%d\n%d\n%d\n" %(1, o.location.x, o.location.y)) f.write("%d\n%d" %(self.__player.cooldown, self.__player.duration)) f.close() self.Notify("Saving complete!") def Load(self, e): f = open("C:/Users/abc/source/repos/PythonApplication1/PythonApplication1/General/Resources/save.txt", "r") #loading self.Notify("Loading...") i1 = int(f.readline()) self.age = i1 #board i1 = int(f.readline()) i2 = int(f.readline()) self.layout.Build(i1, i2) self.__born.clear() self.__dead.clear() #organisms for y in range(self.__board.row): for x in range(self.__board.col): p = Point(x, y) i1 = int(f.readline()) if i1 == 0: continue else: t = f.readline()[0] i2 = int(f.readline()) i3 = int(f.readline()) o = Entities.CreateChar(t) o.world = self o.age = i2 o.strength = i3 o.location = p self.AddToWorld(o, p) self.__board.Print() #born i1 = int(f.readline()) for i in range(i1): i2 = int(f.readline()) if i2 == 0: continue else: i3 = int(f.readline()) i4 = int(f.readline()) p = Point(i3, i4) self.__born.append(self.GetAt(p)) #dead i1 = int(f.readline()) for i in range(i1): i2 = int(f.readline()) if i2 == 0: continue else: i3 = int(f.readline()) i4 = int(f.readline()) p = Point(i3, i4) self.__dead.append(self.GetAt(p)) i1 = int(f.readline()) i2 = int(f.readline()) self.__player.SetActive(i1, i2) f.close() self.__ClearLegend() self.Notify("Loading complete!")
def __init__(self, other = None): Human.__init__(self, other) self.avatarType = AvatarTypes.Pirate
class Game: def __init__(self): self.player_one = Player() self.player_two = Player() self.computer = Computer() self.human = Human() def run_game(self): self.welcome() self.computer_player() def welcome(self): print( 'Welcome to RPSLS or better known as Rock, Paper, Scissors, Lizard, Spock.' ) def computer_player(self): computer_question = input( 'Will you be playing a computer or player today?') if computer_question == 'computer': k = 1 players = [self.player_one, self.computer] while k < 3: self.player_one.name = input('Enter player one name here: ') self.computer.name = 'Computer' print(self.player_one.name + ' is first to go.') self.player_one.choice = self.human.human_choice() print(self.computer.name + ' is next.') self.computer.choice = self.computer.computer_choice() print(self.computer.name + ' choice is: ' + self.computer.choice) self.gesture_comparison(players) k += 1 self.diplay_winner(players) elif computer_question == 'player': k = 1 players = [self.player_one, self.player_two] while k < 4: self.player_one.name = input('Enter player one name here: ') self.player_two.name = input('Enter player two name here: ') print(self.player_one.name + ' is first to go.') self.player_one.choice = self.human.human_choice() print(self.player_two.name + ' is next') self.player_two.choice = self.human.human_choice() self.gesture_comparison(players) k += 1 self.diplay_winner(players) def gesture_comparison(self, players): length = len(players) for i in range(length): for j in range(i): player_compare = self.comparison(players[j], players[i]) print(players[j].name + ' score is: ' + str(player_compare[0])) print(players[i].name + ' score is: ' + str(player_compare[1])) def comparison(self, player_one, player_two): if 'rock' in (player_one.choice, player_two.choice) and 'scissors' in (player_one.choice, player_two.choice): print('Rock Crushes Scissors') if player_one.choice == 'rock': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'rock': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'scissors' in (player_one.choice, player_two.choice) and 'paper' in ( player_one.choice, player_two.choice): print('Scissors cuts Paper') if player_one.choice == 'scissors': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'scissors': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'paper' in (player_one.choice, player_two.choice) and 'rock' in (player_one.choice, player_two.choice): print('Paper covers Rock.') if player_one.choice == 'paper': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'paper': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'rock' in (player_one.choice, player_two.choice) and 'lizard' in (player_one.choice, player_two.choice): print('Rock crushes Lizard.') if player_one.choice == 'rock': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'rock': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'lizard' in (player_one.choice, player_two.choice) and 'Spock' in ( player_one.choice, player_two.choice): print('Lizard poisons Spock') if player_one.choice == 'lizard': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'lizard': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'Spock' in (player_one.choice, player_two.choice) and 'scissors' in ( player_one.choice, player_two.choice): print('Spock smashes scissors.') if player_one.choice == 'Spock': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'Spock': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'scissors' in (player_one.choice, player_two.choice) and 'lizard' in ( player_one.choice, player_two.choice): print('Scissors decapitates lizard') if player_one.choice == 'scissors': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'scissors': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'lizard' in (player_one.choice, player_two.choice) and 'paper' in ( player_one.choice, player_two.choice): print('Lizard eats Paper') if player_one.choice == 'lizard': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'lizard': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'paper' in (player_one.choice, player_two.choice) and 'Spock' in (player_one.choice, player_two.choice): print('Paper disproves Spock') if player_one.choice == 'paper': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'paper': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif 'Spock' in (player_one.choice, player_two.choice) and 'rock' in (player_one.choice, player_two.choice): print('Spock Vaporizes Rock') if player_one.choice == 'Spock': player_one.score += 1 player_two.score += 0 return [player_one.score, player_two.score] elif player_two.choice == 'Spock': player_one.score += 0 player_two.score += 1 return [player_one.score, player_two.score] elif player_one.choice == player_two.choice: print('We have a tie!') player_one.score += 0 player_two.score += 0 return [player_one.score, player_two.score] def diplay_winner(self, players): if players[0].score > players[1].score: print(players[0].name + ' is the winner!') elif players[1].score > players[0].score: print(players[1].name + ' is the winner!') elif players[1].score == players[0].score: print('We have a tie for the whole game!')