def printTableState(self): gameStateMapping = ["PREFLOP","FLOP","TURN","RIVER"] print "Player List: {0}".format(self.tableObj.playerList) print "Betting Round: {0}".format(gameStateMapping[self.tableObj.gameState]) print "Pots: {0}\tCurrent Bet: {1}".format(self.tableObj.pots, self.tableObj.currentBet) print "Player: {0}\tHand: {1}".format( self.tableObj.playerList[self.tableObj.turn].name, \ Cards.convertNumToCards(self.tableObj.playerList[self.tableObj.turn].hand) ) print "Money: {0}\tBet Amount: {1}".format(self.tableObj.playerList[self.tableObj.turn].money, self.tableObj.playerList[self.tableObj.turn].betAmount) print "Community: {0}".format(Cards.convertNumToCards(self.tableObj.communityCards))
def step(self): self.players[self.playing_player].character.win(self) on_turn_begin(self.playing_player) Cards.ask_about_house(self) self.players[self.playing_player].play_card(self) if self.players[self.playing_player].must_remove_card: selected_card = my_select_card(self.players[self.playing_player].cards, self.playing_player) del(self.players[self.playing_player].cards[self.players[self.playing_player].cards.index(selected_card)]) cards_in_arm = len(self.players[self.playing_player].cards) + self.players[self.playing_player].bad_cards self.players[self.playing_player].append_card(max(0, 5 - cards_in_arm), self) self.playing_player = (self.playing_player + 1) % self.number_of_players for region in self.desk.regions: region.played = False
def charge_particle_content(self): """ find the ingoing and outgoing particles for this Subprocess store this information in self.particles=[list of PID] return the dictionary """ self.particles = Cards.read_leshouches_file(self.dir+'/leshouche.inc') return self.particles
def import_ext_part(self,dir_file): """ read leshouches.inc information """ pid_list = Cards.read_leshouches_file(dir_file+'/'+'leshouche.inc') #create the particle object and put them in the content of the diag #add the mass corresponding to the card for i in range(1,len(pid_list)+1):#MG start at one a=external_part(i,pid_list[i-1]) self.add_content(i,a)
def hit(self): """hit a hand, and return new value()""" card = Cards.draw() print(card.name()) self.add(card) self.showvalue(reveal=True) if self.busted(): print("[BUST]") return 0 else: return self.value()
def __init__(self,current_dir,cond='',ParticlesFile=''): """we need to read information from leshouche.inc and from configs.inc""" mglabel2pid_list=Cards.read_leshouches_file(current_dir+'/leshouche.inc') # create a dict: mglabel2pid_dic={} for index, pid in enumerate(mglabel2pid_list): mglabel2pid_dic[index+1]=pid topology=self.read_config(current_dir+'/configs.inc', mglabel2pid_dic) #process_line,multi=self.read_proc_card(proc_card,cond) #self.decay_diag=self.pass_in_pid(process_line,multi) self.decay_diag=self.decay_structure(topology,mglabel2pid_dic) if ParticlesFile is not None: self.ParticlesFile=ParticlesFile #avoid multiple load of this file
def __init__(self): self.deck = [] for i in range(0, 4): for j in range(1, 14): card = Cards.card() card.suit = Cards.validsuits()[i] card.rank = Cards.rankString()[j] self.deck.append(card) for i in range(0, 4): for j in range(1, 14): card = Cards.card() card.suit = Cards.validsuits()[i] card.rank = Cards.rankString()[j] self.deck.append(card) self.shuffle()
def populate_cards(): global cards cards = map(lambda c: Model.card(c).get(), Cards.get_cards()) random.shuffle(cards)
if len(cnts) == 0: print('No contours found!') quit() card = cnts[0] # Approximate the corner points of the card peri = cv2.arcLength(card,True) approx = cv2.approxPolyDP(card,0.01*peri,True) pts = np.float32(approx) x,y,w,h = cv2.boundingRect(card) # Flatten the card and convert it to 200x300 warp = Cards.flattener(image,pts,w,h) # Grab corner of card image, zoom, and threshold corner = warp[0:84, 0:32] #corner_gray = cv2.cvtColor(corner,cv2.COLOR_BGR2GRAY) corner_zoom = cv2.resize(corner, (0,0), fx=4, fy=4) corner_blur = cv2.GaussianBlur(corner_zoom,(5,5),0) retval, corner_thresh = cv2.threshold(corner_blur, 155, 255, cv2. THRESH_BINARY_INV) # Isolate suit or rank if i <= 13: # Isolate rank rank = corner_thresh[20:185, 0:128] # Grabs portion of image that shows rank dummy, rank_cnts, hier = cv2.findContours(rank, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) rank_cnts = sorted(rank_cnts, key=cv2.contourArea,reverse=True) x,y,w,h = cv2.boundingRect(rank_cnts[0]) rank_roi = rank[y:y+h, x:x+w]
## Define font to use font = cv2.FONT_HERSHEY_SIMPLEX # Initialize camera object and video feed from the camera. The video stream is set up # as a seperate thread that constantly grabs frames from the camera feed. # See VideoStream.py for VideoStream class definition ## IF USING USB CAMERA INSTEAD OF PICAMERA, ## CHANGE THE THIRD ARGUMENT FROM 1 TO 2 IN THE FOLLOWING LINE: videostream = VideoStream.VideoStream((IM_WIDTH, IM_HEIGHT), FRAME_RATE, 2, 0).start() time.sleep(1) # Give the camera time to warm up # Load the train rank and suit images path = os.path.dirname(os.path.abspath(__file__)) train_ranks = Cards.load_ranks(path + '/Card_Imgs/') train_suits = Cards.load_suits(path + '/Card_Imgs/') ### ---- MAIN LOOP ---- ### # The main loop repeatedly grabs frames from the video stream # and processes them to find and identify playing cards. cam_quit = 0 # Loop control variable # Begin capturing frames while cam_quit == 0: # Grab frame from video stream image = videostream.read() # Start timer (for calculating frame rate)
listdir=os.listdir('./Source/MadWeight/transfer_function/data') print 'Available transfer functions:\n ', print '\n '.join([content[3:-4] for content in listdir if (content.startswith('TF') and content.endswith('dat'))]) name=raw_input('Choose your transfer Function\n') P_dir,MW_dir=detect_SubProcess(P_mode=1) os.chdir('./Source/MadWeight/transfer_function') change_tf.create_TF_main(name,0,MW_dir) print os.getcwd() os.chdir('../../..') break if MWparam.run_opt['param']: create_param.Param_card(run_name=MWparam) MWparam.update_nb_card() Cards.create_include_file(MWparam) update_cuts_status(MWparam) if MWparam.run_opt['analyzer']: write_MadWeight.create_all_fortran_code(MWparam) if MWparam.run_opt['madweight_main']: Launch_all_SubProcess(MWparam) if MWparam.run_opt['plot']: import plot plot.Likelihood(mw_param=MWparam,auto=1) if MWparam['mw_run']['histo']: plot.Differential_Graph(MWparam,auto=1) if MWparam.run_opt['clean']: print 'cleaning in progress ....'
class AceyDeucey(): #create class variables, manipulate deck game = Cards.cardDeck() game.buildDeck() game.shuffle() #create constructor, take in playerName and playerCash def __init__(self, name, cash): self.name = name self.cash = cash #create method for the intro to the game to modularize code a bit def intro(self): print("\nWelcome to Acey Deucey, ", self.name, "!\n") print("You have ", self.cash, "dollars to play with.\n") print("Let's get started!\n") #create method for playing the game def playGame(self): ante = int(input("How much are you willing to ante?: \n")) self.cash -= ante print("\nHere are your two cards: ") card1 = AceyDeucey.game.deal() card2 = AceyDeucey.game.deal() print("\nTime to wager. You can only bet up to the ante.") wager = int(input("How much are you willing to bet?: \n")) if wager > ante: print("\nThat bet is not possible, try again please.") wager = int(input("How much are you willing to bet?: ")) #Wiki rules High/Low situation if card1 == card2: print("Your cards match. You must now guess if the next card is higher or lower.") guess = str(input("High or Low? :")) print("You guessed ", guess, ". Here is your card: ") card3 = AceyDeucey.game.deal() if (guess == 'High') and (card3 > card1): self.cash += (wager*2) print("You won! You win ", wager, "dollars and now have ", self.cash, "dollars.") return elif (guess == 'High') and (card3 < card1): self.cash -= wager print("You lost. You lose ", wager, "dollars and now have ", self.cash, "dollars.") return elif (guess == 'Low') and (card3 < card1): self.cash += (wager*2) print("You won! You win ", wager, "dollars and now have ", self.cash, "dollars.") return else: self.cash -= wager print("You lost. You lose ", wager, "dollars and now have ", self.cash, "dollars.") return #if no High/Low, then proceed as usual print("\nYour bet has been placed. Here is your third card: ") card3 = AceyDeucey.game.deal() #compare cards, determine result if (card3 > card1 and card3 < card2) or (card3 > card2 and card3 < card1): print("\nYou won!") self.cash += (wager*2) print("You just won ", wager, "dollars and now have " , self.cash, "dollars!") elif (card3 == card1 or card3 == card2): print("\nYou have two identical values. You must now add to the pot double your wager.") wager = wager*2 self.cash -= wager print("You now have ", self.cash, "dollars.") else: print("\nYou lost.") self.cash -= wager print("You just lost ", wager, "dollars and now have ", self.cash, "dollars.") #see if player wants to play again play = str(input("\nWould you like to play again? Y/N: ")) print() if play == 'Y': AceyDeucey.playGame(self) else: print("Have a great day!")
def pass_in_pid(self,process_line,multi): """ convert information in pid information """ if hasattr(self,'ParticlesFile'): ParticlesFile=self.ParticlesFile else: ParticlesFile=Cards.Particles_file('./Source/MODEL/particles.dat') pid=ParticlesFile.give_pid_dict() # # Update information with multi_particle tag # for couple in multi.items(): text=couple[1] tag=couple[0] pid_list=[] len_max=3 key_list=pid.keys() while text: text,add=self.first_part_pid(text,pid) pid_list+=add pid.update({tag:pid_list}) # # pid list is now complete # convert line in decay pid information decay_rule=[] #1) take only the decay part: for letter in ['$','/','\\','@','#','\n']: if letter in process_line: process_line=process_line[:process_line.index(letter)] #break # only one such symbol to signify the end of the decay part process_line=process_line[process_line.index('>')+1:] decay_diag=[] level_decay=0 while process_line: if process_line[0] in [' ', '\t']: process_line=process_line[1:] continue if process_line[0]=='>': process_line=process_line[1:] continue if process_line[0]=='(': process_line=process_line[1:] level_decay+=1 new_decay=1 continue if process_line[0]==')': level_decay-=1 current_part=current_part.mother process_line=process_line[1:] continue process_line,pid_content=self.first_part_pid(process_line,pid) if level_decay==0 or (level_decay==1 and new_decay): new_decay=0 part=Proc_decay(pid_content) decay_diag.append(part) current_part=part elif new_decay: new_decay=0 part=current_part.add_desint(pid_content) #return new part current_part=part else: current_part.add_desint(pid_content) return decay_diag
tic = time.time() def training_ascii(): date, hours = utils.create_timestamp() print '\033[1m\033[32m================================================================\033[0m' print 'GENERATING POKER_HAND TRAINING DATA %s - %s' % (date, hours) print '[-' + '-' * int(60 * (round + 1) / N) + '-]' print '\033[1m[%ss Elapsed] \t \t %s percent complete' % ( str(time.time() - tic), str(100 * float(round) / N)) print '\033[1m\033[32m================================================================\033[0m' if '-run' in sys.argv: hands = [] deck = Cards.Deck() content = '' for hand in range(100): try: # TODO: need to double check for card collisions (or fix root cause) table = deck.deal(7) content += Cards.show_cards(table) + '\n' hands.append(table) except IndexError: deck.initialize() table = deck.deal(7) content += Cards.show_cards(table) + '\n' hands.append(table) print 'Finished Simulating %d Hands. [%ss Elapsed]' % ( len(hands), str(time.time() - tic)) if os.path.isfile('unlabeled_training_data.txt'): open('unlabeled_training_data.txt', 'a').write(content)
self.gameover = False def distribute(self, names): cardsdealt = 0 piles = [[] for _ in range(self.__numplayers)] while cardsdealt < 52: for x in range(self.__numplayers): piles[x].append(self.__gamedeck.pile[cardsdealt]) cardsdealt += 1 if cardsdealt == 52: break for x in range(self.__numplayers): self.__playerarray.append(player.player(names[x], piles[x])) #piles[x]. def gameOver(self, player): for player in self.__numplayers: if player.getcardsleft == 0: return True else: return False d = Cards.deck() a = player.player("ronald", d.pile) a.getcardsleft() names = ["john", "ron", "bo"] first = BSgame(names) store = first.playerarray[0].playCard('5', 1) first.playerarray[0].getcardsleft
def startGame(self): self.activeDeck = Cards.Deck()
def __init__(self): self.name = "" self.cards = Cards.Cards() self.guessed_tricks = 0 self.won_tricks = 0 self.score = 0
def __init__(self): self.all_cards = [] for suit in suits: for rank in ranks: self.all_cards.append(Cards(suit, rank))
import Cards import KAI import random import time deck = Cards.Deck(hand_size = 7) valid_input = {'A' : 'A', 'K' : 'K', 'Q' : 'Q', 'J' : 'J', '10' : 'T', '9' : '9', '8' : '8', '7' : '7', '6' : '6', '5' : '5', '4' : '4', '3' : '3', '2' : '2', 'T' : 'T'} game_over = False def find_card(card:str, player) -> list: """It Is Assumed Card Is The Value, Not The Suit""" results = [] count = 0 for c in deck.players[player].in_hand: if c[0] == valid_input[card]: results.append(count) count += 1 return results def take_card(cards : list, player : int, target : int): for c in sorted(cards, reverse = True): deck.players[player].in_hand.append(deck.players[target].in_hand.pop(c)) print('You Got {}!'.format(len(cards))) def count_score(player : int): count_hand = {} global game_over
import cv2 import numpy as np import time import os import Cards from skimage.measure import compare_ssim import imutils THRESHOLD_MIN = 127 CARD_LONG_2_SHORT_FACTOR = 6.5 / 5 CARD_WRAP_LONG_MAX = 300 CARD_WRAP_SHORT_MAX = int(CARD_WRAP_LONG_MAX / CARD_LONG_2_SHORT_FACTOR) # Load the train rank and suit images path = os.path.dirname(os.path.abspath(__file__)) test_image = Cards.load_image_bw(path, '/test/image10.jpg') test_w = test_image.shape[1] test_h = test_image.shape[0] test_image_norm = [] if (test_w > test_h): test_image_norm = cv2.resize(test_image, (CARD_WRAP_LONG_MAX, CARD_WRAP_SHORT_MAX)) else: test_image_norm = cv2.resize(test_image, (CARD_WRAP_SHORT_MAX, CARD_WRAP_LONG_MAX)) (thresh, test_image_binary) = cv2.threshold(test_image_norm, THRESHOLD_MIN, 255, cv2.THRESH_BINARY) Cards.show_thumb("diff-{}".format(-1), test_image_binary, 0, 0) ##from https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/
def placeCards(self): self.mapCards = Cards.MapCards(self.cards) self.mapCards.placeCards()
def parseFile(line_generator, config, *args): ''' Main parsing function. line_generator can be a tail for live execution, or a file object for testing. ''' lineNo = 0 from re import match showEntity = None for line in line_generator(*args): lineNo += 1 line_parts = match('^D \d{2}:\d{2}:\d{2}\.\d{7} ([a-zA-Z]*\.[a-zA-Z]*\(\)) -\s*([A-Z_]{2,}|)(.*)', line) if line_parts is None: # Any of the error messages won't match, but it's not safe to use them continue source = line_parts.group(1) type = line_parts.group(2) data = parse(line_parts.group(3)) if source == 'GameState.DebugPrintEntityChoices()': if 'ChoiceType' in data and data['ChoiceType'] == 'MULLIGAN': if data['Player'] == config['username']: logging.debug('You are player id %s' % data['id']) Utilities.us = data['id'] else: logging.debug('Opponent is player id %s' % data['id']) Utilities.them = data['id'] if source == 'GameState.DebugPrintEntitiesChosen()': # Cards that were not mulliganed if data.keys()[0][:8] == 'Entities': # Entities[0], e.g. if data.values()[0]['zone'] == 'HAND': Hand.keep(data.values()[0]) if showEntity is not None: if type: showEntity = None elif 'tag' in data and data['tag'] == 'ZONE' and data['value'] == 'GRAVEYARD': Hand.discard(showEntity) if source == 'PowerTaskList.DebugPrintPower()': if type == 'BLOCK_END': Legendaries.blockEnd() elif type == 'BLOCK_START': if data['BlockType'] == 'TRIGGER': if 'zone' in data['Entity']: if data['Entity']['zone'] == 'GRAVEYARD': Cards.die(data['Entity']) Legendaries.die(data['Entity']) elif data['Entity']['zone'] == 'PLAY': Cards.trigger(data['Entity']) elif data['BlockType'] == 'POWER': # When a card actually hits the board if 'Target' in data and isinstance(data['Target'], dict): Cards.play3(data['Entity'], data['Target']) # A card targets another card. Legendaries.play3(data['Entity'], data['Target']) else: Cards.play2(data['Entity']) Legendaries.play2(data['Entity']) elif type == 'SHOW_ENTITY': # Start of a SHOW_ENTITY block of data showEntity = data['Entity'] elif type == 'TAG_CHANGE': if data['tag'] == 'FIRST_PLAYER': logging.warning('New game started') Utilities.wentFirst(data['Entity'] == config['username']) if data['tag'] == 'JUST_PLAYED': if data['Entity']['zone'] == 'HAND': Hand.play(data['Entity']) # When a card is removed from a player's hand elif data['tag'] == 'RESOURCES': if data['Entity'] != config['username']: Utilities.resources = data['value'] elif data['tag'] == 'STEP': if data['value'] == 'FINAL_GAMEOVER': Hand.reset() Utilities.reset() Legendaries.reset() print 'Game Over' if data['value'] == 'MAIN_READY': if Utilities.ourTurn(): Hand.turnover() Cards.turnover() Legendaries.turnover() elif data['tag'] == 'TURN': Utilities.turn = int(data['value']) elif data['tag'] == 'ZONE_POSITION': if 'zone' in data['Entity'] and data['Entity']['zone'] == 'DECK': Hand.draw(data['Entity'], int(data['value'])-1)
## Define font to use font = cv2.FONT_HERSHEY_SIMPLEX # Initialize camera object and video feed from the camera. The video stream is set up # as a seperate thread that constantly grabs frames from the camera feed. # See VideoStream.py for VideoStream class definition ## IF USING USB CAMERA INSTEAD OF PICAMERA, ## CHANGE THE THIRD ARGUMENT FROM 1 TO 2 IN THE FOLLOWING LINE: videostream = VideoStream.VideoStream((IM_WIDTH,IM_HEIGHT),FRAME_RATE,0).start() time.sleep(1) # Give the camera time to warm up # Load the train rank and suit images path = os.path.dirname(os.path.abspath(__file__)) train_suits = Cards.load_suits( path + '/Training_Set/') ### ---- MAIN LOOP ---- ### # The main loop repeatedly grabs frames from the video stream # and processes them to find and identify playing cards. cam_quit = 0 # Loop control variable # Begin capturing frames while cam_quit == 0: # Grab frame from video stream image = videostream.read() # Start timer (for calculating frame rate)
def randomCards(self): self.cards = Cards.Cards(self.tmxList) self.cards.randomCards(self.startID, self.endID, self.count)
IM_WIDTH = 1280 IM_HEIGHT = 720 FRAME_RATE = 10 frameRateCalc = 1 freq = cv2.getTickFrequency() font = cv2.FONT_HERSHEY_DUPLEX videostream = VideoStream.VideoStream((IM_WIDTH, IM_HEIGHT), FRAME_RATE, 2, 0).start() time.sleep(1) path = os.path.dirname(os.path.abspath(__file__)) train_ranks = Cards.load_ranks(path + '/Cards/') train_suits = Cards.load_suits(path + '/Cards/') camQuit = False while not camQuit: img = videostream.read() t1 = cv2.getTickCount() prePro = Cards.preprocess_image(img) cntSort, cntIsCard = Cards.find_cards(prePro) if len(cntSort) != 0: cards = [] k = 0 for i in xrange(len(cntSort)): if (cntIsCard[i] == 1):
def __init__(self): self.deck = Cards.Deck() self.deck.shuffle()
class Game: gameCount = 0 universities = {'Arts': {'start_p': '10', 'rf': 10, 'cr': 1, 'cs': 2, 'ss': 2}, # TODO position adapt 'Music': {'start_p': '16', 'rf': 1, 'cr': 10, 'cs': 10, 'ss': 1}, 'Science': {'start_p': '14', 'rf': 4, 'cr': 7, 'cs': 7, 'ss': 0}, 'Building': {'start_p': '12', 'rf': 7, 'cr': 4, 'cs': 4, 'ss': 1} # 'Building': {'start_p': '12', 'rf': 7, 'cr': 4, 'cs': 4, 'ss': 11} # to test penguin } stat_max = {'rf': 50, 'cr': 25, 'cs': 50, 'ss': 10} stat_min = {'rf': 1, 'cr': 1, 'cs': 1, 'ss': 0} cards = Cards.generate_card_dict('Tactic Card') events = Cards.generate_card_dict('Event Card') positions = {'1': {'visitors': 1100, 'rf_min_req': 35}, '2': {'visitors': 1000, 'rf_min_req': 35}, '3': {'visitors': 900, 'rf_min_req': 35}, '4': {'visitors': 800, 'rf_min_req': 35}, '5': {'visitors': 675, 'rf_min_req': 20}, '6': {'visitors': 600, 'rf_min_req': 20}, '7': {'visitors': 525, 'rf_min_req': 20}, '8': {'visitors': 450, 'rf_min_req': 20}, '9': {'visitors': 350, 'rf_min_req': 10}, '10': {'visitors': 300, 'rf_min_req': 10}, '11': {'visitors': 250, 'rf_min_req': 10}, '12': {'visitors': 200, 'rf_min_req': 10}, '13': {'visitors': 125, 'rf_min_req': 0}, '14': {'visitors': 100, 'rf_min_req': 0}, '15': {'visitors': 75, 'rf_min_req': 0}, '16': {'visitors': 50, 'rf_min_req': 0} } conversion_rate = {x+1: 0.5 + x * 0.05 for x in range(25)} # eg. {1: 0.5, 2: 0.55} def __init__(self, pids): print('SEOwar.py', 'creating Game ', pids) self.won = False self.player_stage = 'play' # or 'throw' self.round = 1 self.card_stack = [] self.shuffle_cards() self.event_stack = [str(i) for i in range(len(Game.events))] random.shuffle(self.event_stack) # self.card_stack = [] # self.card_stack += random.shuffle([str(i) for i in range(len(Game.cards)-len(self.card_stack))]) self.players = {} # just for init universities sequence = [k for k in Game.universities.keys()] random.shuffle(sequence) for pid in pids: # print('creating player: pid = '+pid) player = dict() player['admission'] = 0 player['university'] = sequence.pop(0) player['position'] = Game.universities[player['university']]['start_p'] player['rf'] = Game.universities[player['university']]['rf'] player['cr'] = Game.universities[player['university']]['cr'] player['cs'] = Game.universities[player['university']]['cs'] player['ss'] = Game.universities[player['university']]['ss'] player['cards'] = self.draw_card(5) self.players[pid] = player self.round_queue = self.determine_queue() # self.round = 0 # self.turn = '' self.history = [] # [-1]=last_played msg = {'type': 'custom', 'msg': 'Game initialized'} self.history.append(msg) self.current = 0 Game.gameCount += 1 def make_json(self): game = dict() game['players'] = self.players game['history'] = self.history[self.current:] game['round_queue'] = self.round_queue game['won'] = self.won game['player_stage'] = self.player_stage game['round'] = self.round self.current = len(self.history) # pp = pprint.PrettyPrinter(indent=4) # pp.pprint(game) return json.dumps(game) def make_cards(self): return json.dumps(Game.cards) def make_events(self): return json.dumps(Game.events) def make_positions(self): return json.dumps(Game.positions) # def add_history(self, pid, action, card, target=None): # self.history.append({'pid': pid, # 'action': action, # 'card': card, # 'target': target # }) def handle_move(self, move): pid = move[0] action = move[1] card = move[2] target = move[3] if action == 'play': self.play_card(pid, card, target) elif action == 'end_play': self.player_draw(pid, 3) elif action == 'throw': self.player_throw(pid, card) elif action == 'end_throw': self.end_turn(pid) return self.make_json() def check_winner(self, pid): if self.players[pid]['admission'] >= 50: print('won', pid) msg = {'type': 'custom', 'msg': pid+' Won!'} self.history.append(msg) return True return False def adjust_stats(self, pid, stats): for idx, stat in enumerate(['rf', 'cr', 'cs', 'ss']): original = self.players[pid][stat] change = stats[idx] new_stat = original + change if new_stat < Game.stat_min[stat]: new_stat = Game.stat_min[stat] elif new_stat > Game.stat_max[stat]: new_stat = Game.stat_max[stat] self.players[pid][stat] = new_stat if original != self.players[pid][stat]: msg = {'type': 'adjust', 'pid': pid, 'stat': stat, 'original': original, 'new': new_stat} self.history.append(msg) if stats[0] > 0: self.adjust_position(pid) def adjust_position(self, pid): # input: [(player, position, rf)] rf = self.players[pid]['rf'] # int position = int(self.players[pid]['position']) # str->int original = str(position) up_one_position = position - 1 # int position_list = [self.players[pid]['position'] for pid in self.players] # str if up_one_position not in position_list and rf >= Game.positions[str(up_one_position)]['rf_min_req']: self.players[pid]['position'] = str(up_one_position) position = int(self.players[pid]['position']) # str->int lower_rf_list = [(pid, self.players[pid]['position'], self.players[pid]['rf']) for pid in self.players if self.players[pid]['rf'] < rf] if len(lower_rf_list) == 0: return # print('before sort=', lower_rf_list) s = sorted(lower_rf_list, key=lambda x: int(x[1])) # sort by p['position'] in asc # print('sorted=', s) if int(s[0][1]) < position: self.players[s[0][0]]['position'], self.players[pid]['position'] = self.players[pid]['position'], self.players[s[0][0]]['position'] # swap if self.players[pid]['position'] != original: msg = {'type': 'adjust', 'pid': pid, 'stat': 'position', 'original': original, 'new': self.players[pid]['position']} self.history.append(msg) def adjust_admission(self, pid, k): original = self.players[pid]['admission'] self.players[pid]['admission'] += k # TODO changed: += instead of = msg = {'type': 'adjust', 'pid': pid, 'stat': 'admission', 'original': original, 'new': self.players[pid]['admission']} self.history.append(msg) if self.check_winner(pid): self.won = pid def shuffle_cards(self): c = [str(i) for i in range(len(Game.cards))] random.shuffle(c) self.card_stack = c def draw_card(self, n): if len(self.card_stack) < n: self.shuffle_cards() drawn = self.card_stack[:n] self.card_stack = self.card_stack[n:] return drawn def play_card(self, pid, card, target): # skip criteria part print('SEOwar.py play_card() ', pid, card, target) subject = pid if target != '': # an attack card subject = target msg = {'type': 'attack', 'pid': pid, 'card': card, 'target': subject} else: msg = {'type': 'play', 'pid': pid, 'card': card} self.history.append(msg) the_card = Game.cards[card] self.adjust_stats(subject, the_card['stat']) self.players[pid]['cards'].remove(card) def player_draw(self, pid, n): new_cards = self.draw_card(n) self.players[pid]['cards'] += new_cards self.player_stage = 'throw' msg = {'type': 'draw', 'pid': pid, 'card': new_cards} self.history.append(msg) def player_throw(self, pid, card): self.players[pid]['cards'].remove(card) msg = {'type': 'throw', 'pid': pid, 'card': card} self.history.append(msg) def end_turn(self, pid): self.draw_events(pid) self.round_queue.pop(0) self.player_stage = 'play' if len(self.round_queue) == 0: self.end_round() def end_round(self): print('SEOwar.py end_round()') msg = {'type': 'custom', 'msg': 'End of Round'} self.history.append(msg) pens = self.get_penguins() for pid in self.players: if pid not in pens: position = self.players[pid]['position'] v = Game.positions[position]['visitors'] cr = self.players[pid]['cr'] k = self.conversion_map(v, cr) self.adjust_admission(pid, k) self.link_earning(pid) else: msg = {'type': 'custom', 'msg': pid+' penguined'} self.history.append(msg) self.players[pid]['ss'] = 0 self.round_queue = self.determine_queue() self.round += 1 return def link_earning(self, pid): rf = math.floor(int(self.players[pid]['cs'])/5) if rf >= 0: msg = {'type': 'custom', 'msg': pid+' link earning: +'+str(rf)+'rf'} self.history.append(msg) self.adjust_stats(pid, [rf, 0, 0, 0]) def conversion_map(self, v, cr): conversion_rate = Game.conversion_rate[cr]/100 admission = conversion_rate*v return math.ceil(admission) def get_penguins(self): pid_ss = [(pid, self.players[pid]['ss']) for pid in self.players] penguins = [p[0] for p in pid_ss if p[1] >= 10] return penguins def determine_queue(self): pid_rf = [(pid, self.players[pid]['rf']) for pid in self.players] sort = sorted(pid_rf, key=lambda x: int(x[1]), reverse=True) return [s[0] for s in sort] def draw_events(self, pid): print('SEOwar.py draw_events()') event_no = self.event_stack.pop(0) # TODO would not reshuffle when run out self.adjust_stats(pid, Game.events[event_no]['stat']) msg = {'type': 'event', 'pid': pid, 'event': event_no} self.history.append(msg)
Created on Fri Jul 19 17:00:07 2019 @author: shivank agrawal """ import Cards, random_measure, time #myprint: controls printing run_mode = "prod" def myprint(mode, *arg): if (run_mode == "test"): print arg first = Cards.deck() #first.reset() second = Cards.deck() #second.reset #myprint (first.pile,"separation",second.pile) print("successfully made decks") time.sleep(5) a = random_measure.randomm(first) b = random_measure.randomm(second) a.chronology() a.same() print("chronology test: ", a.chronper, "same number test: ", a.sameper) b.chronology() b.same() print("chronology test: ", b.chronper, "same number test: ", b.sameper) #time.sleep(8)
def read_card(name_card): """put all card information in a dictionary""" card = Cards.Card(name_card) return card.info
## Initialize calculated frame rate because it's calculated AFTER the first time it's displayed frame_rate_calc = 1 freq = cv2.getTickFrequency() # Initialize camera object and video feed from the camera. The video stream is set up # as a seperate thread that constantly grabs frames from the camera feed. # See VideoStream.py for VideoStream class definition ## IF USING USB CAMERA INSTEAD OF PICAMERA, ## CHANGE THE THIRD ARGUMENT FROM 1 TO 2 IN THE FOLLOWING LINE: videostream = VideoStream.VideoStream((IM_WIDTH,IM_HEIGHT),FRAME_RATE,2,0).start() time.sleep(1) # Give the camera time to warm up # Load the train rank and suit images path = os.path.dirname(os.path.abspath(__file__)) train_ranks = Cards.load_ranks( path + '/Card_Imgs/') train_suits = Cards.load_suits( path + '/Card_Imgs/') ### ---- MAIN LOOP ---- ### # The main loop repeatedly grabs frames from the video stream # and processes them to find and identify playing cards. cam_quit = 0 # Loop control variable # Begin capturing frames while cam_quit == 0: # Grab frame from video stream image = videostream.read()
ret.blit(pygame.transform.scale(card.Image, (rect.width, rect.height)), rect) count += 1 return ret pygame.init() displayinfo = pygame.display.Info() size = width, height = displayinfo.current_w, displayinfo.current_h speed = [2, 2] black = 0, 0, 0 screen = pygame.display.set_mode(size) deck = Cards.Deck(full=False, shuffle=True) cards = deck.draw(18) #hand = createHand(width/2, height/6, cards[:6]) field = createField(3 * width / 6, 2 * height / 6, cards[6:12], cards[12:18]) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(black) """ handRect = hand.get_rect() handRect.left = (width - handRect.width) / 2 handRect.top = 0 screen.blit(hand, handRect) """
import Cards class Player: def __init__(self, name): self.name = name self.all_cards = [] def remove_one(self): self.all_cards.pop(0) def add_cards(self, new_card): if (type(new_card) == type([])): self.all_cards.extend(new_card) else: self.all_cards.append(new_card) def __str__(self): return "Player {} has {} cards".format(self.name, len(self.all_cards)) jose = Player("Jose") print(jose) new_card = Cards("Spades", "Seven") jose.add_cards(new_card) print(jose) jose.add_cards([new_card, new_card, new_card]) print(jose)
def deal (self): self.add(Cards.draw()); self.add(Cards.draw());
num_hands = len(self.hands) while matches < 25: matches += self.play_one_turn(turn) turn = (turn + 1) % num_hands print("---------- Game is Over") self.print_hands() #----------------------------------------------------- # SCRIPT #---------------------------------------------------- red_deck = Deck() print(red_deck) deck = Deck() deck.shuffle() hand = Hand("frank") deck.deal([hand],5) print(hand) game = CardGame() hand = OldMaidHand("frank") game.deck.deal([hand], 13) print(hand) hand.remove_matches() print(hand) import Cards game = Cards.OldMaidGame() game.play(["Allen","Jeff","Chris"])
# @Email: [email protected] # @Filename: main2.py # @Last modified time: 20-05-2017 # from Cards import * from Board import * from ClassMoney import * from Player import * game = True while game: ask_name = raw_input("Please input your name: ") play1 = Player(ask_name) play1card = Cards() '''First turn of player 1, we get two random cards''' card1 = play1card.rand_card() play1card.mod_card(card1) card2 = pla1card.rand_card() play1card.mod_card(card2) if play1.points == 21: print "BLACKJACK - PLAYER1 WINS!!!!" break else: print "It´s turn for the crupier!!" crup = Player('crupier') crupcard = Cards() '''Now it´s turn to get two cards for the crupier'''
def format_card(self, card, base=150): """ Format the entire card, does not add text. Just the template and the card art and returns it PARAMETERS: - card: The card to be formatted and returned - base: Where the card should be placed on the returned canvas. Do either 150 (for MPC) or 0 (for regular) RETURNS - A pygame Surface of the card, centered if set for MPC """ card_type = card["type_line"] colours = card["colors"] # A bunch of flags to be set when processing the card, before generating the image # Determines the borders and background land = False if "Land" in card_type: land = True # Determines the P/T box creature = False if "Creature" in card_type: creature = True # Determines if we need to overlay the Nyx enchantment border nyx = False if "Enchantment" in card_type: if "Creature" in card_type or "Artifact" in card_type: nyx = True # First get the main background, either land or nonland if land == True: background = pygame.image.load( "template-data/basic/background/land.png") title_box = pygame.image.load( "template-data/basic/title-boxes/land.png") # Determine land text colours by the mana they produce, or if they are an artifact if "Artifact" in card_type: text_t = "artifact" elif "produced_mana" in card: temp = card[ "produced_mana"] # Store temporary list, to handle fetchlands and stuff text_t = self.get_file_name_colour(temp, 3) # Default to land else: text_t = "land" text_box = pygame.image.load( "template-data/basic/land-textboxes/" + text_t + ".png") else: # Determine the background, text-boxes, and title-boxes from the colours and types title_t = self.get_file_name_colour( colours, 2) # The title does not care about artifact if "Artifact" in card_type: back_t = "artifact" else: if Cards.two_colour_background(card): back_t = self.get_file_name_colour(colours, 3) title_t = "land" else: back_t = self.get_file_name_colour(colours, 2) text_t = self.get_file_name_colour(colours, 3) background = pygame.image.load("template-data/basic/background/" + back_t + ".png") title_box = pygame.image.load("template-data/basic/title-boxes/" + title_t + ".png") text_box = pygame.image.load( "template-data/basic/nonland-textboxes/" + text_t + ".png") # Load the card art card_art_path = Cards.get_card_art_crop(card) if card_art_path == None: return False card_art = pygame.image.load(card_art_path) # By the template, the image should be about 2294x1686 and be placed at (200,420) + base, accounting for an offset # if the image is too big in one direction (to center it) card_art = Cards.dynamically_scale_card(card_art, (2294, 1686)) w_offset = (card_art.get_width() - 2294) // 2 h_offset = (card_art.get_height() - 1686) // 2 # Now create an output canvas of the proper size, draw things to it canvas = pygame.Surface((2682 + 2 * base, 3744 + 2 * base)) canvas.fill((255, 255, 255)) # Fill the canvas with white, before drawing to it canvas.blit(card_art, (200 + base - w_offset, 420 + base - h_offset)) canvas.blit(background, (base, base)) if nyx: canvas.blit( pygame.image.load("template-data/basic/nyx-border.png"), (base, base)) canvas.blit(text_box, (base, base)) canvas.blit(title_box, (base, base)) if creature or "Vehicle" in card_type: pt = self.get_file_name_colour(colours, 2) canvas.blit( pygame.image.load("template-data/basic/pt-boxes/" + pt + ".png"), (base, base)) self.add_mana_cost(canvas, card, base=base) return self.add_text(canvas, card, base=base)
def test_checkAce(self): deck = Cards.deck playerHand = [] playerHand.append(deck[0]) playerHand.append(deck[1]) self.assertEqual(12, Cards.checkAce(playerHand))
p3 = Player("p3", 1000) p4 = Player("p4", 1000) table.addPlayer(p1) table.addPlayer(p2) table.addPlayer(p3) table.addPlayer(p4) table.beginRound() gameStateMapping = ["PREFLOP","FLOP","TURN","RIVER"] gameRunning = True while gameRunning: print "Betting Round: {0}".format(gameStateMapping[table.gameState]) print "Pots: {0}\tCurrent Bet: {1}".format(table.pots, table.currentBet) print "Player: {0}\tHand: {1}".format( table.playerList[table.turn].name, \ Cards.convertNumToCards(table.playerList[table.turn].hand) ) print "Money: {0}\tBet Amount: {1}".format(table.playerList[table.turn].money, table.playerList[table.turn].betAmount) print "Community: {0}".format(Cards.convertNumToCards(table.communityCards)) print "\n1. Call" print "2. Raise" print "3. Fold" print "0. Exit" c = int(raw_input()) if c == 1: table.call(table.playerList[table.turn]) elif c == 2: r = int(raw_input("Raise: ")) table.raiseBet(table.playerList[table.turn], r) elif c == 3: table.fold(table.playerList[table.turn])
class Game: Game(): self.attack = [] self.defend = [] self.hands = [] self.deck = Cards.Deck()
class Game: def __init__(self, num_players): self.Deck = Cards(num_players) self.num_players = num_players self.players = [Player(self.Deck, id_=i) for i in range(1, num_players+1)] # a cosa corrisponde il jolly? self.jolly = 100 self.turn = 0 self.player = 0 self.consec_passes = 0 self.need_to_declare = True self.decl_istr = "Dichiara il tipo di carta che andrà giocata (il numero, non il seme): " self.playc_istr = "Inserire il numero di ogni carta che vuoi buttare, separando ogni carta con spazi o virgole: " self.doubt_istr = "Insert the number of the player who wants to doubt, if any. Otherwise just press enter: " self.play() def first_draw(self): for id_ in range(self.num_players): player = self.players[id_] player.add_to_hand(self.Deck.draw()) def advance_turn(self): self.turn += 1 if self.turn >= self.num_players: self.turn = 0 def reset(self, loser=None): """ Resetta pool, need_to_declare e il num di pass consecutivi. Se specificato il loser, egli pescherà il pozzo. Parameters ---------- loser: istanza del player perdente Returns ---------- """ # reset all relevant variables self.need_to_declare = True self.consecutive_passes = 0 # eventually add pool to hand of loser and reset pool if loser: loser.add_to_hand(self.Deck.pool) self.Deck.reset_pool() return def take_input(self, istrz, min_=0, max_=13, type_=int, none = False, no_self_doubt = False): """ Take an input, while controlling that it is within a numerical range or that it is of the right type, if the relative arguments are specified """ while True: ui = input(istrz) # se None è una risposta ammissibile e viene data, restituisci None if none == True and not ui: return ui # here start checks about type, and min < ui < max, and self doubting if type_ is not None: try: ui = type_(ui) except ValueError: print("Input type must be {0}.".format(type_.__name__)) continue if no_self_doubt == True and ui == self.player.id_: print("One can't doubt his own play! :/") elif max_ is not None and ui > max_: print("Input must be less than or equal to {0}.".format(max_)) elif min_ is not None and ui < min_: print("Input must be greater than or equal to {0}.".format(min_)) else: return ui def play_cards(self): """ ask the user for the cards he wants to play, take only those which he actually has in hand, use the Player class method to play the cards """ # request input cards to play from player x self.player.show_hand() # take input, split based on comma or whitespace, clean resulting empty strings #in the thus formed list (e.g. if one uses two whitespaces), convert to int, cards_played = [int(carta) if int(carta) != self.jolly else self.card_declared \ for carta in \ list(filter(None, re.split(" |,|;", input(self.playc_istr)))) \ ] #cards_played = list(filter(lambda x:x in \ # cards_to_play, \ # self.player.hand)) # actually play the cards cards_played = self.player.play_cards(cards_played) # informative prints if cards_played: print(f"player {self.player.id_} has played {len(cards_played)} {self.card_declared[0]}") else: print(f"player {self.player.id_} has passed its turn") return cards_played def doubt(self, cards_played, who_doubted): # if the player was honest, reset and give the pool to the doubter if cards_played == self.card_declared*len(cards_played): print("E invece il giocatore {} aveva effettivamente giocato {} {}!" \ .format(self.player.id_, len(cards_played), self.card_declared[0])) loser = self.players[who_doubted -1] self.reset(loser) #self.players[who_doubted -1].add_to_hand(self.Deck.pool) #self.Deck.reset_pool() return False # if the player got correctly doubted, give him the first turn and the bluffer takes the cards else: print(f"Il giocatore {who_doubted} ha correttamente dubitato del giocatore {self.player.id_}!") loser = self.player self.reset(loser) #self.player.add_to_hand(self.Deck.pool) #self.Deck.reset_pool() return True def play(self): self.first_draw() while True: """---------------- define player ----------------""" self.player = self.players[self.turn] print("\n----------------------------------------") print(f"è il turno del giocatore {self.player.id_}") """---------------- play card ----------------""" if self.need_to_declare: print("Inizia un nuovo giro! Tagadà!") time.sleep(1) self.player.show_hand() # declare the card which will need to be played self.card_declared = [self.take_input(istrz=self.decl_istr)] self.need_to_declare = False print(f"La carta da giocare è il {self.card_declared[0]}") time.sleep(0.5) # play cards cards_played = self.play_cards() """---------------- doubt ----------------""" time.sleep(1) who_doubted = None # se non è stato passato il turno, apri la fase di dubbio if cards_played: # if someone wants to doubt, insert his player number in this input who_doubted = self.take_input(self.doubt_istr, min_= 0, max_=self.num_players, type_=int, none = True, no_self_doubt = True) if who_doubted: correctness_doubt = self.doubt(cards_played, who_doubted) time.sleep(2.5) else: self.consec_passes += 1 if self.consec_passes >= self.num_players: time.sleep(0.5) print("Tutti i giocatori hanno passato!") self.reset() self.consec_passes = 0 """---------------- check victory ----------------""" if not self.player.hand: print(f"\n Player {self.player._id} has won the game, ggs! \n") return """---------------- manage turns ----------------""" # if there was a doubt, give the turn to the winner of the outcome if who_doubted and correctness_doubt == True: self.turn = who_doubted-1 # else regularly advance the turn elif not who_doubted: self.advance_turn() return
from Cards import * def g_deck(suits,cards): lst = [] for s in suits: for c in cards: lst.append((c,s)) return lst suits = ["Clubs", "Spades", "Hearts", "Diamonds"] cards = ["Ace", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack",\ "Queen", "King"] deck = Cards(g_deck(suits,cards)) deck.shuffle() dealer = [] player = [] def beginning(deck,dealer,player): for x in range(0,2): dealer.append(deck.deck[0]) deck.draw() for x in range(0,2): player.append(deck.deck[0]) deck.draw() return deck,dealer,player beginning(deck,dealer,player) def val(hand): val = 0 for c in hand:
IM_WIDTH = 1280 IM_HEIGHT = 720 FRAME_RATE = 10 frame_rate_calc = 1 freq = cv2.getTickFrequency() font = cv2.FONT_HERSHEY_SIMPLEX # Initialize camera object and video feed from the camera. videostream = PiVideoStream.PiVideoStream((IM_WIDTH,IM_HEIGHT),FRAME_RATE).start() time.sleep(1) # warm up # Load the rank and suit images path = os.path.dirname(os.path.abspath(__file__)) train_ranks = Cards.load_ranks( path + '/Card_Imgs/') train_suits = Cards.load_suits( path + '/Card_Imgs/') cam_quit = 0 # Loop control variable while cam_quit == 0: image = videostream.read() t1 = cv2.getTickCount() # Pre-process pre_proc = Cards.preprocess_image(image) cnts_sort, cnt_is_card = Cards.find_cards(pre_proc) if len(cnts_sort) != 0: cards = [] k = 0 for i in range(len(cnts_sort)): if (cnt_is_card[i] == 1):