def test_fork_me(self, current_play, passin_board, log, **kwargs): """ this looks for forks you can play, where you create two connect3's simulatenously""" if not (current_play.player in self.fork_me): return -1 for play_col_i in range(current_play.board.width): temp_play = Play(board = passin_board, \ state = copy.deepcopy(current_play.state), \ player_init = copy.copy(current_play.player)) available_plays = current_play.available_plays() if not (play_col_i in available_plays): continue temp_play.make_play(play_col_i, switch_player=True) blocking_cols = self.test_connect_three_you(temp_play, passin_board, log, ret_multi=True) if blocking_cols == -1: continue if len(blocking_cols) > 1: return play_col_i return -1
def test_set_lives(self): player1 = Player() p = Play() self._prefill_sample_ships(player1, p) self.assertEqual(p.get_lives(player1, "A1"), 2) p.set_lives(player1, "A1", 1) self.assertEqual(p.get_lives(player1, "A1"), 1)
def test_connect_three_you(self, current_play, passin_board, passin_log, **kwargs): if not (current_play.player in self.connect_three_you): return -1 available_plays = current_play.available_plays() current_player = copy.copy(current_play.player) other_player = 1 if current_player == 2 else 2 list_blocking_plays = [] for play_col_i in range(current_play.board.width): temp_play = Play(board = passin_board, \ state = copy.deepcopy(current_play.state), \ player_init = other_player) if not (play_col_i in available_plays): continue temp_play.make_play(play_col_i, switch_player=False) if temp_play.check_win(log=None): list_blocking_plays.append(play_col_i) if len(list_blocking_plays) > 0: if kwargs.get('ret_multi', False): return list_blocking_plays else: return list_blocking_plays[0] return -1
def build_id_to_game_map(): f = open('Play_by_Play.txt', 'r') games = dict() #dict game_id -> [ Play ] i = 0 for line in f: if i == 0: i += 1 else: tokens = line.split() for i in range(len(tokens)): tokens[i] = tokens[i].strip('"') game_id = tokens[0] play = Play(game_id, tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6], tokens[7], tokens[8], tokens[9], tokens[10], tokens[11], tokens[12], tokens[13], tokens[14], tokens[15], tokens[16], tokens[17]) if game_id in games: game = games[game_id] else: game = Game(game_id) games[game_id] = game game.add_play(play) f.close() return games
def main(): """ The primary function of this application that runs the game. Parameters: None Logs: An error if the string url is entered incorrectly. """ parser = argparse.ArgumentParser() parser.add_argument('--numPlayers', default=2) args = parser.parse_args() logging.basicConfig(filename='errors_log/errors.log', level=logging.ERROR, format='%(message)s') logging.getLogger('assignment7') players = args.numPlayers (player_is_int, player_num) = safe_int_checker(players) print_graphics('artwork/PIG-ART.txt') keyed = input('\nHow many games would you like to play?\n') (game_is_int, game_num) = safe_int_checker(keyed) if game_is_int and player_is_int: play = Play(player_num, game_num) play.start() else: print(f'Something went wrong, you entered in games: "{keyed}" & players: "{players}"') logging.error(f'Error processing games key: "{keyed}" & players key: "{players}"') return SystemExit print_graphics('artwork/END.txt') print("\nThank you for playing PIG. Please run the script to play again!\n")
def __init__(self, camera): self.cap = cv.VideoCapture(camera) # run `ffmpeg -f v4l2 -list_formats all -i /dev/video0` to check # list of available video modes resolutions = "1280x720" resolutions = [int(i) for i in "1280x720".split('x')] self.cap.set(cv.CAP_PROP_FRAME_WIDTH, resolutions[0]) self.cap.set(cv.CAP_PROP_FRAME_HEIGHT, resolutions[1]) _, self.frame = self.cap.read() self.processor = Processor(self.frame, "camera.yml") self.player = Play() cv.namedWindow('processed') self.rect_sel = RectSelector('processed', self.onrect) self.the_rect = 0, 0, self.processor.w, self.processor.h self.color = (128, 255, 255) self.start_play = False self.paused = False self.store = False self.end = False self.winner = None self.store_points = [] self.store_radius = [] self.location = tuple()
def switch_button(self): for button in self.all_buttons: if button.action == 3: # bouton pause self.all_buttons.remove(button) self.all_buttons.add(Play(self)) if button.action == 4: # bouton play self.all_buttons.remove(button) self.all_buttons.add(Pause(self))
def __init__(self): self.commans = (Play(), Variable(), Speech(), Info()) #, Sinoptik()) self.db = DBConnector() # Очищаем список команд. Список не актуален. self.db.IUD("delete from core_execute") self.last_processed_ID = -1 self.db.commit() self.run()
def run(self): ''' run all patterns in the playbook ''' plays = [] matched_tags_all = set() unmatched_tags_all = set() # loop through all patterns and run them self.callbacks.on_start() for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): play = Play(self, play_ds, play_basedir, vault_password=self.vault_password) assert play is not None matched_tags, unmatched_tags = play.compare_tags(self.only_tags) matched_tags_all = matched_tags_all | matched_tags unmatched_tags_all = unmatched_tags_all | unmatched_tags # Remove tasks we wish to skip matched_tags = matched_tags - set(self.skip_tags) # if we have matched_tags, the play must be run. # if the play contains no tasks, assume we just want to gather facts # in this case there are actually 3 meta tasks (handler flushes) not 0 # tasks, so that's why there's a check against 3 if (len(matched_tags) > 0 or len(play.tasks()) == 3): plays.append(play) # if the playbook is invoked with --tags or --skip-tags that don't # exist at all in the playbooks then we need to raise an error so that # the user can correct the arguments. unknown_tags = ((set(self.only_tags) | set(self.skip_tags)) - (matched_tags_all | unmatched_tags_all)) for t in RESERVED_TAGS: unknown_tags.discard(t) if len(unknown_tags) > 0: for t in RESERVED_TAGS: unmatched_tags_all.discard(t) msg = 'tag(s) not found in playbook: %s. possible values: %s' unknown = ','.join(sorted(unknown_tags)) unmatched = ','.join(sorted(unmatched_tags_all)) raise errors.AnsibleError(msg % (unknown, unmatched)) for play in plays: ansible.callbacks.set_play(self.callbacks, play) ansible.callbacks.set_play(self.runner_callbacks, play) if not self._run_play(play): break ansible.callbacks.set_play(self.callbacks, None) ansible.callbacks.set_play(self.runner_callbacks, None) # summarize the results results = {} for host in self.stats.processed.keys(): results[host] = self.stats.summarize(host) return results
def do_add(self, name_of_play, short_description, director, list_of_actors): new_play = Play() new_play.name = name_of_play new_play.description = short_description new_play.director = director new_play.actor_list = list_of_actors self.manager.transition = SlideTransition(direction="left") self.manager.current = 'connected' movies.append(new_play)
def play(self, filename): # stop existing player self.stop() # create new player self.player = Play(filename, self.player_cfg) self.player.play() self.response.set("file", filename)
def play(self): from play import Play self.value = self.eurl.get() self.player = Play(self.value, mode='quickplay') # Stop scanning url field. self.after_cancel(self.quickplay_id) # Disable play button while playing. self.bplay.config(state=DISABLED) # Call listener method. self.listen_for_result()
def main(): from play import Play p = Play() print('choose game:') print('1. tic tac toe') print('2. connectfour') print('3. chess') print('4. brasserie (default)') game = int(input() or 4) - 1 getattr(p, ['ttt', 'c4', 'chess', 'brasserie'][game])() print('any key to close') input()
def connect(self): sockets = [] for player in self.game.players: # workers.append (Communicate(self.read, self.write, self.game,self.game.players[i].port)) # workers[i].start() conn = Communicate(self.read, self.write, player.id, player.port, self.queue) sockets.append(conn) conn.start() Play(self.read, self.write, self.game, self.dealer, self.queue) Play.reset() print("exit") sys.exit()
def run(self): ''' run all patterns in the playbook ''' # loop through all patterns and run them self.callbacks.on_start() for play_ds in self.playbook: self.SETUP_CACHE = {} self._run_play(Play(self, play_ds)) # summarize the results results = {} for host in self.stats.processed.keys(): results[host] = self.stats.summarize(host) return results
def __init__(self): self.width = 8 self.heigth = 20 random.seed() pygame.init() self.play = Play(self.width, self.heigth) self.screen = pygame.display.set_mode( ((self.width * 30) + 20, (self.heigth * 30) + 20)) self.clock = pygame.time.Clock() self.pause = True pygame.time.set_timer(pygame.USEREVENT, 500)
def move(): data = PublicGameState(ext_dict=bottle.request.json) pos00 = int(data.publicPlayers[0]['position'][1]) data.publicPlayers[0]['position'][1] = int( data.publicPlayers[0]['position'][0]) data.publicPlayers[0]['position'][0] = pos00 pos10 = int(data.publicPlayers[1]['position'][1]) data.publicPlayers[1]['position'][1] = int( data.publicPlayers[1]['position'][0]) data.publicPlayers[1]['position'][0] = pos10 side = data.agent_id my_player = PublicPlayer(jsonString=data.publicPlayers[side]) enemy = PublicPlayer(jsonString=data.publicPlayers[(side + 1) % 2]) field = data.gameField return Play(side, field, my_player, enemy).take_turn()
def test_get_ship_at_location(self): p = Play() player1 = Player() self._prefill_sample_ships(player1, p) exp = {'ship_type': 'Q', 'lives': 2} self.assertEqual(p.get_ship_at_location(player1, "A1"), exp) self.assertEqual( p.get_ship_at_location(player1, "A1")["ship_type"], "Q") self.assertEqual(p.get_ship_at_location(player1, "A1")["lives"], 2) self.assertEqual(p.get_ship_at_location(player1, "A5"), None) exp = {'ship_type': 'P', 'lives': 1} self.assertEqual(p.get_ship_at_location(player1, "D5"), exp) self.assertEqual( p.get_ship_at_location(player1, "D5")["ship_type"], "P") self.assertEqual(p.get_ship_at_location(player1, "D5")["lives"], 1)
def main(): while True: new_game = Play() while new_game.get_chip_pool() > 0: new_game.reset_hands() new_game.make_bet() new_game.deal_cards() new_game.game_status() new_game.hit() new_game.stand() new_game.game_status() if new_game.restart(): continue
def get_plays(data): plays = [] ball_carriers = [] for row in data: nodes = [] edges = [] label = row[0][0] offense = [] defense = [] num_nodes = 0 for i in range(len(row)): node = [] if row[i][1] in defense_positions: defense.append(num_nodes) else: offense.append(num_nodes) if row[i][2] == "away": node.append(0) else: node.append(1) node.append(float(row[i][3])) # x position node.append(float(row[i][4])) # y position node.append(float(row[i][5])) # speed (yards per second) node.append(float(row[i][6])) # acceleration (yards per second^2) node.append(float(row[i][7])) # distance traveled since snap try: node.append(float(row[i][8])) # orientation except ValueError: node.append(0) try: node.append(float(row[i][9])) # direction except ValueError: node.append(0) node.append(float(row[i][10])) # weight num_nodes += 1 nodes += [node] for o in offense: for d in defense: edges.append([o, d]) label = np.array(label).astype(np.long) plays += [Play(np.array(nodes, dtype=np.float32), edges, label)] return plays, np.array(ball_carriers)
def getPlaysByGame(gameID): session = getSession() try: r = getRequest(gameID) #conn.request("GET", "/mlb/v2/JSON/News?%s" % params, "{body}", # headers) #response = conn.getresponse() if r != None: data = r.json() gameID = data['Game']['GameID'] plays = data['Plays'] for play in plays: theID = play['PlayID'] query = session.query(Play).filter( Play.PlayID == theID).scalar() thisPlay = Play(**{ k: v for k, v in play.items() if k in Play.__table__.columns }) thisPlay.GameID = gameID if query is None: '' session.add(thisPlay) else: query = session.merge( thisPlay ) #session.query(News).filter(News.NewsID == theID).update(newsItem) pitches = play['Pitches'] for pitch in pitches: theID = pitch['PitchID'] query = session.query(Pitch).filter( Pitch.PitchID == theID).scalar() thisPitch = Pitch( **{ k: v for k, v in pitch.items() if k in Pitch.__table__.columns }) if query is None: session.add(thisPitch) else: query = session.merge(thisPitch) session.commit() except Exception as e: print("[Errno {0}] ".format(e)) session.close()
def run(self): ''' run all patterns in the playbook ''' plays = [] matched_tags_all = set() unmatched_tags_all = set() # loop through all patterns and run them self.callbacks.on_start() for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): play = Play(self, play_ds, play_basedir) self.callbacks.play = play self.runner_callbacks.play = play matched_tags, unmatched_tags = play.compare_tags(self.only_tags) matched_tags_all = matched_tags_all | matched_tags unmatched_tags_all = unmatched_tags_all | unmatched_tags # if we have matched_tags, the play must be run. # if the play contains no tasks, assume we just want to gather facts if (len(matched_tags) > 0 or len(play.tasks()) == 0): plays.append(play) # if the playbook is invoked with --tags that don't exist at all in the playbooks # then we need to raise an error so that the user can correct the arguments. unknown_tags = set( self.only_tags) - (matched_tags_all | unmatched_tags_all) unknown_tags.discard('all') if len(unknown_tags) > 0: unmatched_tags_all.discard('all') msg = 'tag(s) not found in playbook: %s. possible values: %s' unknown = ','.join(sorted(unknown_tags)) unmatched = ','.join(sorted(unmatched_tags_all)) raise errors.AnsibleError(msg % (unknown, unmatched)) for play in plays: if not self._run_play(play): break # summarize the results results = {} for host in self.stats.processed.keys(): results[host] = self.stats.summarize(host) return results
def main(): """ The primary function of this application that runs the game. Parameters: None Logs: An error if the string url is entered incorrectly. """ logging.basicConfig(filename='errors_log/errors.log', level=logging.ERROR, format='%(message)s') logging.getLogger('assignment8') parser = argparse.ArgumentParser() parser.add_argument('--player1', default="human", help='choose human or computer') parser.add_argument('--player2', default="human", help='choose human or computer') parser.add_argument('--timed', default=0, const=60, nargs='?', help='pass the --timed flag to play for 1 min.') args = parser.parse_args() player1 = args.player1 player2 = args.player2 timed = args.timed print_graphics('artwork/PIG-ART.txt') print_player_type_selection(player1, player2) play = Play([player1, player2], timed) play.start() print_graphics('artwork/END.txt') print( "\nThank you for playing PIG. Please run the script to play again!\n")
def __init__(self, server, num): self.screen = pygame.display.set_mode([1920, 1080], FULLSCREEN, 32) # 主背景 self.bg = pygame.image.load('./images/bg.jpg').convert() # 服务器ip self.server_ip = server # 用户id self.user_num = num # 初始化几个界面 self.menu_screen = Menu(self.screen) self.play_screen = Play(self, self.screen) self.set_screen = Set(self, self.screen) self.room_screen = Room(self, self.screen) self.record_screen = Record(self, self.screen) # 打开软件时默认在菜单界面 self.now_screen = 'menu' # 弹窗的类型 self.alert_window = None self.alert_mod = '0'
def plays(self): """ All plays (see Play class documentation) in a corpus. """ corpus_content = requests.get(self.url).json() plays = [] for drama in corpus_content['dramas']: printed_year = drama['printYear'] and int(drama['printYear']) written_year = drama['writtenYear'] and int(drama['writtenYear']) normalized_year = drama['yearNormalized'] and int( drama['yearNormalized']) plays.append( Play(self, drama['name'], drama['title'], drama['author']['name'], printed_year, written_year, normalized_year)) return plays
def playRound(self): currentPlay = Play() currentPlayerIndex = self.players.index(self.currentDealer) currentPlayer = self.players[currentPlayerIndex] for player in self.players: player.createPlayHand() lastPlayerToPlay = None while True: # Determine is anyone has cards left someoneHasCards = False for player in self.players: if (len(player.playHand) > 0): someoneHasCards = True if (not someoneHasCards): break # Get the next player if ((currentPlayerIndex + 1) % len(self.players) == 0): currentPlayerIndex = 0 currentPlayer = self.players[0] else: currentPlayerIndex += 1 currentPlayer = self.players[currentPlayerIndex] # If player can play, play if (currentPlayer.canPlay(currentPlay.pointLimit)): cardPlayed = currentPlayer.play(currentPlay.pointLimit) currentPlay.append(cardPlayed) print('{0} plays {1}'.format(currentPlayer.name, cardPlayed)) currentPlayer.score += currentPlay.calculateExtraPoints() lastPlayerToPlay = currentPlayer print(currentPlay.points) else: if (currentPlayer == lastPlayerToPlay): currentPlayer.score += 1 print('{0}: One for last'.format(currentPlayer.name)) currentPlay.reset() else: print('{0} GO'.format(currentPlayer.name)) currentPlayer.score += 1 print('{0}: One for last'.format(currentPlayer.name)) currentPlay.reset()
def play_match(self): player1 = Player("Player-1") player2 = Player("Player-2") p = Play() ba = BattleArea(5, "E") player1.battle_area = ba.battle_area() player2.battle_area = ba.battle_area() s = Ship("Q") p.fill_ship(s, 1, 1, "A1", player1) p.fill_ship(s, 1, 1, "B2", player2) s = Ship("P") p.fill_ship(s, 2, 1, "D4", player1) p.fill_ship(s, 2, 1, "C3", player2) player1.targets = 'A1 B2 B2 B3'.split() player2.targets = 'A1 B2 B3 A1 D1 E1 D4 D4 D5 D5'.split() p.start_match(player1, player2)
def test_connect_three_me(self, current_play, passin_board, passin_log, **kwargs): if not (current_play.player in self.connect_three_me): return -1 available_plays = current_play.available_plays() for play_col_i in range(current_play.board.width): temp_play = Play(board = passin_board, \ state = copy.deepcopy(current_play.state), \ player_init = copy.copy(current_play.player)) if not (play_col_i in available_plays): continue temp_play.make_play(play_col_i, switch_player=False) if temp_play.check_win(log=None): return play_col_i return -1
def player_plays(self, current_player: Player): print(f"Player {current_player}'s turn") cards_played = current_player.read_play("Choose cards by index to play or pass") if cards_played: play = Play(cards_played) if not play.is_legal_play(): print("Illegal play attempted! Stop cheating!!!") current_player.add_cards(cards_played) return self.player_plays(current_player) try: self.last_play = play except IllegalPlayError as e: print(e) current_player.add_cards(cards_played) return self.player_plays(current_player) # Legal if we get here self.player_passed(False) else: if not self.last_play and current_player.cards_in_hand() > 0: print("You can't pass on your lead!") return self.player_plays(current_player) self.player_passed(True)
# scImage(self.window, "launcher/background.jpg", (0,0), SIZE) self.launcher.drawObjects(self.window) pygame.display.update() # Gameloop def loop(self): while self.running: self.update() self.render() # Start project def startProject(self, projectName): self.path = self.pathToProjects + projectName self.end() # Turn off the launcher def end(self): self.running = False # Start launcher main = Main() path = main.path pygame.quit() if path != "": # Start project Play(path) pygame.quit()