예제 #1
0
    def __init__(self, db_type, db_instance):
        """After connecting to the Redis database instance 
           ACK_SCOREBOARD_DB, this redis database is flushed 
           for a clean start. 

           A new row will be added for each TIMED_ACK_ID. This will be
           done as follows:
           1) When a new TIMED_ACK_ID is encountered, row will be added with new ID as string identifier
           2) a list of hashes will be set up for each key/value pair in the message
           3) As new acks with a particular TIMED_ACK_ID are received, the data is added to that row.
           4) After a timer event elapses, the scoreboard is locked and checked  to see which ACKs were received.
        """
        LOGGER.info('Setting up AckScoreboard')
        self.DB_TYPE = db_type
        self.DB_INSTANCE = db_instance
        try:
            Scoreboard.__init__(self)
        except L1RabbitConnectionError as e:
            LOGGER.error('Failed to make connection to Message Broker:  ',
                         e.arg)
            print("No Auditing for YOU")
            raise L1Error('Calling super.init in AckScoreboard init caused: ',
                          e.arg)

        self._redis = self.connect()
        self._redis.flushdb()
예제 #2
0
    def initialize_pygame(self):

        print("Initializing Pong game ...")

        pygame.mixer.pre_init(self.settings.sound_sample_rate, -16,
                              self.settings.sound_channels, 1024)
        pygame.mixer.init()
        pygame.init()

        self.clock = pygame.time.Clock()

        width = int(self.settings.screen_width * self.settings.screen_resize)
        height = int(self.settings.screen_height * self.settings.screen_resize)
        self.screen = pygame.display.set_mode((width, height))
        self.screen_rect = self.screen.get_rect()
        pygame.display.set_caption(self.settings.screen_title)

        self.background = Background(self.settings, self.screen)

        self.welcome_board = WelcomeBoard(self.settings, self.screen, self)

        self.scoreboard = Scoreboard(self.settings, self.screen, self)

        self.victory_board = VictoryBoard(self.settings, self.screen, self)

        self.ball = Ball(self.settings, self.screen)
        self.scoreboard.set_ball(self.ball)

        self.initialize_players()
예제 #3
0
    def __init__(self):
        '''initialize game and resources'''
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))

        self.stats = Game_stats(self)
        self.score = Scoreboard(self)

        pygame.display.set_caption("Alien Invasion")

        # ship
        self.ship = Ship(self)

        # bullets
        self.bullets = pygame.sprite.Group()

        # alien
        self.aliens = pygame.sprite.Group()

        self._create_invasion()

        #control
        self.play_button = Button(self, "Play")
예제 #4
0
    def instantiate_scoreboard(self):
        '''Creates the graphic scene and instantiates the scoreboard object.'''
        self.scene = GraphicsScene()
        self.background = QGraphicsSvgItem('Graphics/EMechBackground.svg')
        self.scene.addItem(self.background)

        scoreboard=Scoreboard(\
        self.model, captionColor=self.captionColor, driverType='LXDriver', \
        serialInputFlag=self.serialInputFlag, parent=None, scene=self.scene, vboseList=self.vboseList)

        scoreboard.setKeypad(self.reverseHomeAndGuest, self.keypad3150,
                             self.MMBasketball, self.WHHBaseball)

        self.sportType = scoreboard.game.gameData['sportType']
        print 'Sport:', scoreboard.game.sport, 'Sport Type:', self.sportType, 'Keypad:', scoreboard.keyMap.keypadName, 'model', self.model

        self.scoreboardDict[self.model]=Board(\
        scoreboard, LEDcolor='AMBER', boardColor=self.boardColor, \
        captionColor=self.captionColor, stripeColor=self.stripeColor, \
        driverType='LXDriver', parent=self.background, scene=self.scene)

        #create all timers
        self.refreshAssets = QTimer()
        self.refreshAssets.timeout.connect(self.updateAssets)
        self.checkClickables = QTimer()
        self.checkClickables.timeout.connect(self.checkClickableEvents)
예제 #5
0
def run_game():
    # initialization pygame module
    pygame.init()

    # initialization all objects and screen
    # Settings
    settings = Settings(1200, 800, "Pong Game")

    # screen
    # set Width and height
    screen = pygame.display.set_mode(
        (settings.screen_height, settings.screen_width))
    screen_rect = screen.get_rect()
    # set name of Window
    pygame.display.set_caption(settings.window_name)

    # Player class
    player_1 = Player(settings, screen, (255, 0, 0),
                      screen_rect.left + 3 * settings.player_width)
    player_2 = Player(
        settings, screen, (0, 0, 255),
        (screen_rect.left + screen_rect.right - 3 * settings.player_width))

    # Ball class
    ball = Ball(settings, screen)

    # Scoreboard for two players
    # For 1st player
    score_for_player_1 = Scoreboard(screen, player_1,
                                    screen_rect.left + player_1.rect.height,
                                    screen_rect.top + player_1.rect.height)
    # For 2st player
    score_for_player_2 = Scoreboard(screen, player_2,
                                    screen_rect.right - player_2.rect.height,
                                    screen_rect.top + player_2.rect.height)

    # Class Buttons
    start_button = Button(screen,
                          100,
                          100,
                          screen_rect.centerx,
                          screen_rect.centery,
                          'Play',
                          48, (107, 209, 52),
                          bold=True)
    while True:
        """main cycle to update screen and key events"""
        if settings.game_active:
            """Functions to game active settings"""
            player_1.update()
            player_2.update()
            ball.update()
            gf.goal(screen, score_for_player_1, score_for_player_2, ball,
                    player_1, player_2)
            gf.check_border_screen(screen, ball, player_1, player_2)

        gf.check_key_event(settings, player_1, player_2, start_button)
        gf.update_screen(settings, screen, score_for_player_1,
                         score_for_player_2, player_1, player_2, ball,
                         start_button)
예제 #6
0
    def addPlayClock(self):
        '''Adds a play clock to the graphic scene.'''
        if not self.playClockAddedFlag:
            self.playClockAddedFlag = True
            if self.sportType == 'football' or self.sportType == 'soccer':
                model = 'LX3018'
            elif self.sportType == 'basketball' or self.sportType == 'hockey':
                model = 'LX2180'
            else:
                model = None

            if model is not None:
                scoreboard=Scoreboard(\
                model, captionColor=self.captionColor, driverType='LXDriver', \
                serialInputFlag=self.serialInputFlag, parent=None, scene=self.scene, vboseList=self.vboseList)

                scoreboard.setKeypad(self.reverseHomeAndGuest, self.keypad3150,
                                     self.MMBasketball, self.WHHBaseball)

                self.sportType = scoreboard.game.gameData['sportType']
                print 'Sport:', scoreboard.game.sport, 'Sport Type:', self.sportType, 'Keypad:', scoreboard.keyMap.keypadName, 'model', self.model

                self.scoreboardDict[model]=Board(\
                scoreboard, LEDcolor='AMBER', boardColor=self.boardColor, \
                captionColor=self.captionColor, stripeColor=self.stripeColor, \
                driverType='LXDriver', parent=self.background, scene=self.scene)

                self.scoreboardDict[model].setPos(self.backgroundWidth/2-\
                self.scoreboardDict[model].boundingRect.width()/2, self.backgroundHeight/2+\
                self.boardFactor*self.boardHeight/2+self.boardFactor*5)
예제 #7
0
 def playGame(self):
     while self.newGame != False:
         self.newGame = False
         print("Welcome to Bender's Totally Legit and Not Rigged at All Blackjack Table.")
         print("You're not a cop, are you?  You have to tell me if you're a cop...")
         self.getPlayers()
         print("Welcome",self.player.name)
         self.player.startingCash()
         print(self.player.name, "has $",self.player.cash,"available")
         deck = Deck()
         dealer = Dealer()
         while self.replayGame != False:
             if len(deck.currentDeck) <= 10:
                 house = deck.newDeck()
             round = Round(self)
             results = Results(self)
             score = Scoreboard(self)
             wager = score.placeBet(self.player.cash)
             if self.newGame == True:
                 break
             round.startingHands(self.player, dealer, deck, house)
             round.takeAction(self.player, dealer, deck, house)
             if self.player.score <= 21 and self.player.score > 0:
                 round.checkDealerHand(self.player, dealer, deck, house)
             results.determineWinner(self.player, dealer)
             self.player.cash = score.updateCash(self.player.cash, wager)
             print(self.player.name, "has $", self.player.cash, "available")
             replay = KeepPlaying()
             replay.replayGame(self.player, dealer)
             self.replayGame = replay.playAgain
         if self.newGame == False:
             print("I don't need you.  I'll build my own casino.  With Blackjack... and hookers... Awww, forget it.")
         elif self.newGame == True:
             print("Oops, you're broke! ¯\_(ツ)_/¯")
             print("Come back when you have some money to lose. (\/)(;,,;)(\/)")
예제 #8
0
파일: demineur.py 프로젝트: ifndev/demineur
def main() -> None:
    """
    Procédure pour le menu
    """
    scoreboard = Scoreboard()
    scoreboard.save_scoreboard(
    )  # Créer le fichier scoreboard s'il n'existe pas

    # Affichage du menu
    print("Bienvenue sur le Démineur 3000")
    print("Réalisé par Patrick CONTI et Florian CUNY")
    print("")
    print("Que souhaitez-vous faire ?")
    print("1: Nouvelle partie")
    print("2: Afficher les scores")
    print("3: Afficher les contrôles")
    print("4: Quitter")

    selection = 0

    while selection != 4:
        if selection == 1:
            curses.wrapper(play)
        elif selection == 2:
            display_score(scoreboard)
        elif selection == 3:
            display_controls()

        print("")
        selection = int(input("Entrez un numéro : "))
        print("")
예제 #9
0
    def __init__(self, db_type, db_instance):
        """After connecting to the Redis database instance 
           JOB_SCOREBOARD_DB, this redis database is flushed 
           for a clean start. A 'charge_database' method is 
           included for testing the module.

           Each job will be tracked in one of these states: 
           NEW 
           BASE_RESOURCES_QUERY
           BASE_INSUFFICIENT_RESOURCES
           NCSA_RESOURCES_QUERY
           NCSA_INSUFFICIENT_RESOURCES
           BASE_EVENT_PARAMS_SENT
           READY_FOR_EVENT
           READOUT
           READOUT_COMPLETE
           DELIVERY_COMPLETE
           SCRUBBED
           COMPLETE

           In addition, each job will have an assigned status:
           ACTIVE
           COMPLETE
           TERMINATED
        """
        LOGGER.info('Setting up JobScoreboard')
        self.DB_TYPE = db_type
        self.DB_INSTANCE = db_instance
        self._session_id = str(1)
        try:
            Scoreboard.__init__(self)
        except Exception as e:
            LOGGER.error(
                'Job SCBD Auditor Failed to make connection to Message Broker:  ',
                e.arg)
            print("No Auditing for YOU")
            raise L1RabbitConnectionError(
                'Calling super.init() in JobScoreboard init caused: ', e.arg)

        try:
            self._redis = self.connect()
        except Exception as e:
            LOGGER.error("Cannot make connection to Redis: %s." % e.arg)
            print("Job SCBD: No Redis for YOU:")
            raise L1RedisError(
                'Calling redis connect in JobScoreboard init caused:  ', e.arg)

        self._redis.flushdb()

        self._redis.set(self.CURRENT_SESSION_ID, "session_100")

        #        weekday = subprocess.check_output('date +"%u"', shell=True)
        #        job_num_seed = str(weekday) + "000"
        #        #set up auto sequence
        #        self._redis.set(self.JOB_SEQUENCE_NUM, job_num_seed)

        LOGGER.info('JobScoreboard initialization is complete')
예제 #10
0
파일: Game.py 프로젝트: soltercom/Football
 def __init__(self):
     self.window = Tk()
     self.window.title('Football')
     self.canvas = Canvas(self.window, width=2*Field.X0+Field.WIDTH, height=2*Field.Y0+Field.HEIGHT)
     self.canvas.pack()
     self.field = Field(self.canvas)
     self.ball = Ball(self.canvas, self.field)
     self.scoreboard = Scoreboard(self.canvas, self.field)
     self.teams = Teams(self.canvas, self.field, self.ball)
     self.state = Game.BEGIN
예제 #11
0
 def __init__(self):
     pygame.init()
     self.settings = Settings()
     self.screen = pygame.display.set_mode((1000, 800), pygame.FULLSCREEN)
     self.settings.screen_height = self.screen.get_rect().height
     self.settings.screen_width = self.screen.get_rect().width
     pygame.display.set_caption("Alien Invasion")
     self.stats = GameStats(self)
     self.sb = Scoreboard(self)
     self.bg_color = self.settings.bg_color
     self.ship = Ship(self)
     self.bullets = pygame.sprite.Group()
     self.aliens = pygame.sprite.Group()
     self._create_fleet()
     self.play_button = Button(self, "Play")
예제 #12
0
def run_game():
    # 初始化pygame、设置和屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # 创建Play按钮
    play_button = Button(ai_settings, screen, "Play")
    # 创建一个用于存储游戏统计信息的实例
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # 创建一艘飞船,一个子弹编组和一个外星人编组
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # 开始游戏主循环
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
 def __init__(self, speed=5):
     self.speed = speed
     point_speed = self.speed
     # points
     self.upLeft = Point(upLeft, 1, posUpLeft, point_speed)
     self.upRight = Point(upRight, 2, posUpRight, point_speed)
     self.downLeft = Point(downLeft, 3, posDownLeft, point_speed)
     self.downRight = Point(downRight, 4, posDownRight, point_speed)
     # score
     self.score = Scoreboard()
     #
     self.perfect = 0
     self.great = 0
     self.bad = 0
     self.miss = 0
     self.performance = ""
예제 #14
0
    def parent_init(self, db_num, prog_name, type):
        custom_print.define_new_name(self.PROGRAM_NAME)

        # Create machine scoreboard
        self._sb_mach = Scoreboard(db_num, prog_name, type)

        # Messaging URL (rabbitmq server IP)
        self._broker_url = "amqp://" + AMQP_BF_USER + ":" + AMQP_BF_PSWD + "@" + AMQP_BROKER_ADDR + ":" + AMQP_BROKER_PORT + "/" + AMQP_BROKER_VHOST

        # Publisher object for sending messages to rabbit
        printc("Creating publisher...")
        self._publisher = SimplePublisher(self._broker_url)

        # Machine messages
        self._msg_actions_mach = {
            'TRANSFER_DONE': self.process_transfer_done,  # Machine done with the current job
            'REGISTER': self.process_register,  # New machine wants to join
            'DEREGISTER': self.process_deregister,  # Machine is leaving
            'STATE_UPDATE': self.process_state_update  # Machine updating us on its state
        }

        # Machines register with us and let us know how they are doing
        printc("Creating machine consumer...")
        self._mach_consumer = Consumer(self._broker_url, self._machine_publish_q)
        try:
            thread.start_new_thread(self.run_mach_consumer, ())
        except:
            printc("Thread run_mach_consumer failed, quitting...")
            sys.exit()

        return
예제 #15
0
def run_game():
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("Alien Invaders")
    ship = Ship(screen, setting)
    bullets = Group()
    aliens = Group()

    play_button = Button(setting, screen, "Play")

    stats = GameStats(setting)

    sb = Scoreboard(setting, screen, stats)

    g_o = GameOver(screen, "Game Over")

    gf.create_fleet(setting, screen, aliens, ship)

    while True:
        gf.check_game(ship, setting, screen, bullets, aliens, stats,
                      play_button, sb)
        gf.screen_update(setting, screen, ship, bullets, aliens, stats,
                         play_button, sb)
        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets, aliens, setting, ship, screen, stats,
                              sb)
            gf.update_aliens(setting, aliens, ship, screen, bullets, stats, sb)
            gf.screen_update(setting, screen, ship, bullets, aliens, stats,
                             play_button, sb)
def run_game():
    pygame.init()

    ai_setting=Settings()
    screen=pygame.display.set_mode((ai_setting.screen_width,ai_setting.screen_height))
    pygame.display.set_caption("Alien Invasion")

    play_button=Button(ai_setting,screen,"Play")

    ship=Ship(ai_setting,screen)
    bullets=Group()
    aliens=Group()

    gf.create_fleet(ai_setting,screen,ship,aliens)
    
    stats=GamesStats(ai_setting)
    score_board=Scoreboard(ai_setting,screen,stats)
    while True:
        gf.check_events(ai_setting,screen,stats,score_board,play_button,ship,aliens,bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_setting,screen,stats,score_board,ship,aliens,bullets)
            gf.update_aliens(ai_setting,stats,score_board,screen,ship,aliens,bullets)
        
        gf.update_screen(ai_setting,screen,stats,score_board,ship,aliens,bullets,play_button)
예제 #17
0
 def start(self):
     self.getPlayers()
     # print(self.player1.name)
     # print(self.player2.name)
     scoreboard = Scoreboard()
     while self.replayGame != False:
         round = Round()
         round.playerTurn(self.player1, self.player2)
         # print(self.player1.move, self.player2.move)
         result = Result()
         result.declareVictor(self.player1, self.player2)
         roundScore = result.score
         scoreboard.updateScore(roundScore)
         replay = Replay()
         replay.replayGame()
         self.replayGame = replay.playAgain
예제 #18
0
    def __init__(self):

        """"Initialize game and settings"""
        pygame.init()
        self.settings = Settings()
        #self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        self.screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption('Alien Invasion')    
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
        self.play_button = Button(self,"Play!!!")
예제 #19
0
    def __init__(self, db_type, db_instance, ddict, rdict):
        self.DB_TYPE = db_type
        self.DB_INSTANCE = db_instance
        self._session_id = str(1)
        try:
            Scoreboard.__init__(self)
        except L1RabbitConnectionError as e:
            LOGGER.error('Failed to make connection to Message Broker:  ',
                         e.arg)
            print("No Monitoring for YOU")
            raise L1Error(
                'Calling super.init in StateScoreboard init caused: ', e.arg)

        try:
            self._redis = self.connect()
        except L1RedisError as e:
            LOGGER.error("Cannot make connection to Redis:  ", e)
            print("No Redis for YOU")
            raise L1Error(
                'Calling redis connect in StateScoreboard init caused:  ',
                e.arg)

        self._redis.flushdb()

        weekday = subprocess.check_output('date +"%u"',
                                          shell=True).decode("utf-8")

        job_num_seed = int(weekday) + 1000
        #set up auto sequence
        self._redis.set(self.JOB_SEQUENCE_NUM, int(job_num_seed))
        self._redis.set(self.SESSION_SEQUENCE_NUM, 70000)

        self.init_redis(ddict)

        #self.set_current_raft_configuration(rdict)
        self.set_current_configured_rafts(rdict)

        dd = self.get_current_configured_rafts()
        print(
            "In SSCBD Init - after inserting rafts then pullin it out once again..."
        )
        self.prp.pprint(dd)
        print("Done printing init rafts\n====================\n")
    def __init__(self, db_type, db_instance, ddict):
        LOGGER.info('Setting up DistributorScoreboard')
        self.DB_TYPE = db_type
        self.DB_INSTANCE = db_instance

        try:
            Scoreboard.__init__(self)
        except L1RabbitConnectionError as e:
            LOGGER.error('Failed to make connection to Message Broker: %s',
                         e.arg)
            print("No Monitoring for YOU")
            raise L1Error(
                'Calling super.init in DistScoreboard init caused: %s', e.arg)

        try:
            self._redis = self.connect()
        except L1RedisError as e:
            LOGGER.error('Failed to make connection to Redis: %s', e.arg)
            print("No Redis for YOU")
            raise L1Error(
                'Calling Redis connect in Distributor Scoreboard init caused: %s',
                e.arg)

        self._redis.flushdb()

        distributors = list(ddict.keys())
        for distributor in distributors:
            fields = ddict[distributor]
            name = fields['NAME']
            ip_addr = fields['IP_ADDR']
            target_dir = fields['TARGET_DIR']
            xfer_login = name + "@" + ip_addr
            routing_key = fields['CONSUME_QUEUE']
            publish_queue = "distributor_publish"

            for field in fields:
                self._redis.hset(distributor, field, fields[field])
                self._redis.hset(distributor, 'XFER_LOGIN', xfer_login)
                self._redis.hset(distributor, 'STATUS', 'HEALTHY')
                self._redis.hset(distributor, 'ROUTING_KEY', routing_key)
                self._redis.hset(distributor, 'MATE', 'NONE')

            self._redis.lpush(self.DISTRIBUTOR_ROWS, distributor)
예제 #21
0
    def __init__(self, db_type, db_instance):
        self.DB_TYPE = db_type
        self.DB_INSTANCE = db_instance
        self._session_id = str(1)
        try:
            Scoreboard.__init__(self)
        except L1RabbitConnectionError as e:
            LOGGER.error('Failed to make connection to Message Broker:  ', e.arg)
            print("No Monitoring for YOU")
            raise L1Error('Calling super.init in StateScoreboard init caused: ', e.arg)

        try:
            self._redis = self.connect()
        except L1RedisError as e:
            LOGGER.error("Cannot make connection to Redis:  " , e)  
            print("No Redis for YOU")
            raise L1Error('Calling redis connect in StateScoreboard init caused:  ', e.arg)

        self._redis.flushdb()
예제 #22
0
 def playGame(self):
     while self.newGame != False:
         self.newGame = False
         print(
             "Welcome to Bender's Totally Legit and Not Rigged at All Blackjack Table."
         )
         print(
             "You're not a cop, are you?  You have to tell me if you're a cop..."
         )
         self.getPlayers()
         print("Welcome", self.player.name)
         self.player.startingCash()
         print(self.player.name, "has $", self.player.cash, "available")
         deck = Deck()
         dealer = Dealer()
         while self.replayGame != False:
             if len(deck.currentDeck) <= 10:
                 house = deck.newDeck()
             round = Round(self)
             results = Results(self)
             score = Scoreboard(self)
             wager = score.placeBet(self.player.cash)
             if self.newGame == True:
                 break
             round.startingHands(self.player, dealer, deck, house)
             round.takeAction(self.player, dealer, deck, house)
             if self.player.score <= 21 and self.player.score > 0:
                 round.checkDealerHand(self.player, dealer, deck, house)
             results.determineWinner(self.player, dealer)
             self.player.cash = score.updateCash(self.player.cash, wager)
             print(self.player.name, "has $", self.player.cash, "available")
             replay = KeepPlaying()
             replay.replayGame(self.player, dealer)
             self.replayGame = replay.playAgain
         if self.newGame == False:
             print(
                 "I don't need you.  I'll build my own casino.  With Blackjack... and hookers... Awww, forget it."
             )
         elif self.newGame == True:
             print("Oops, you're broke! ¯\_(ツ)_/¯")
             print(
                 "Come back when you have some money to lose. (\/)(;,,;)(\/)"
             )
예제 #23
0
    def update(self):
        """Updates the players and draw the game."""
        # LEMMINGS
        if self.start and not self.game_over[0]:
            lemmings = self.Lemming.update_player(self.tools)

            for i in range(len(lemmings)):
                if (lemmings[i].x == self.exit_gate.x
                        and lemmings[i].y == self.exit_gate.y
                        and i not in self.saved):
                    # Lemming saved
                    self.saved.append(i)
                    if i in self.alive:
                        self.alive.remove(i)
                elif lemmings[i].alive and i not in self.alive:
                    # Lemming alive
                    self.alive.append(i)
                elif lemmings[i].alive == False and i not in self.dead:
                    # Lemming dead
                    self.dead.append(i)
                    if i in self.alive:
                        self.alive.remove(i)

        if len(self.saved) == self.lemmings_num:
            self.game_over[0] = True
            self.game_over[1] = "win"
        elif len(self.dead) == self.lemmings_num:
            self.game_over[0] = True
            self.game_over[1] = "lose"

        # SCOREBOARD
        total_alive = len(self.alive)
        total_saved = len(self.saved)
        total_dead = len(self.dead)
        total_stairs = len(self.tools["right_s"]) + len(self.tools["left_s"])
        total_umbrellas = len(self.tools["umbrella"])
        total_blockers = len(self.tools["blocker"])
        self.scoreboard = Scoreboard(self.level, total_alive, total_saved,
                                     total_dead, total_stairs, total_umbrellas,
                                     total_blockers)

        # DRAW
        if self.start and self.game_over[0]:
            self.Draw.draw_game(self.scoreboard, self.Lemming.before_start(),
                                self.user_x, self.user_y, self.tools,
                                self.start, self.game_over[1])
        elif self.start:
            self.Draw.draw_game(self.scoreboard, lemmings, self.user_x,
                                self.user_y, self.tools, self.start)
        else:
            self.Draw.draw_game(self.scoreboard, self.Lemming.before_start(),
                                self.user_x, self.user_y, self.tools,
                                self.start)
예제 #24
0
    def __init__(self):
        # GAME: MAIN VARIABLES
        self.initial_time = time()
        self.level = 0
        self.start = False
        self.game_over = [False, ""]

        # GAMEBOARD
        self.Gameboard = Gameboard()
        self.constants = self.Gameboard.Constants
        self.width = self.constants.width
        self.height = self.constants.height
        self.cell_size = self.constants.cell_size
        self.grid = self.Gameboard.grid

        # SCOREBOARD
        self.scoreboard = Scoreboard()

        # PLATFORMS AND GATES
        self.platforms = self.Gameboard.platforms
        self.entry_gate = self.Gameboard.generate_gate(self.platforms)
        self.exit_gate = self.Gameboard.generate_gate(
            self.platforms, self.entry_gate.row_index, exit_gate=True)

        # TOOLS
        self.user_x = 0
        self.user_y = self.scoreboard.height
        self.cursor_displacement = self.cell_size
        self.tools = {
            "umbrella": [],
            "blocker": [],
            "right_s": [],
            "left_s": []
        }

        # LEMMING
        self.alive = []
        self.saved = []
        self.dead = []
        self.Lemming = Lemming(self.entry_gate.x, self.entry_gate.y,
                               self.platforms)
        self.lemmings_num = self.Lemming.lemmings_num

        # DRAW
        self.Draw = Draw(self.platforms, self.entry_gate, self.exit_gate)

        # PYXEL
        self.pyxel_window_title = "Lemmings"
        pyxel.init(self.width, self.height, caption=self.pyxel_window_title)

        pyxel.load("./assets/resources.pyxres")

        pyxel.run(self.interaction, self.update)
예제 #25
0
    def addLockerClock(self):
        '''Adds a locker room clock to the graphic scene.'''
        if not self.lockerClockAddedFlag:
            self.lockerClockAddedFlag = True
            model = 'LX7406'
            scoreboard=Scoreboard(\
            model, captionColor=self.captionColor, driverType='LXDriver', \
            serialInputFlag=self.serialInputFlag, parent=None, scene=self.scene, vboseList=self.vboseList)

            scoreboard.setKeypad(self.reverseHomeAndGuest, self.keypad3150,
                                 self.MMBasketball, self.WHHBaseball)

            self.sportType = scoreboard.game.gameData['sportType']
            print 'Sport:', scoreboard.game.sport, 'Sport Type:', self.sportType, 'Keypad:', scoreboard.keyMap.keypadName, 'model', self.model

            self.scoreboardDict[model]=Board(\
            scoreboard, LEDcolor='AMBER', boardColor=self.boardColor, \
            captionColor=self.captionColor, stripeColor=self.stripeColor, \
            driverType='LXDriver', parent=self.background, scene=self.scene)

            width = 0
            if self.sportType == 'linescore' or self.sportType == 'soccer':
                width = self.scoreboardDict[
                    self.model].boundingRect.width() / 2
            elif self.sportType == 'football':
                width = self.scoreboardDict[
                    self.model].boundingRect.width() / 4

            if self.scoreboardDict[self.model].scoreboard.partsDict[
                    self.model]['qtyOfCabinets'] == 2:
                if self.sportType == 'stat':
                    height = self.boardHeight / 2
                else:
                    height = self.boardHeight
            else:
                height = self.boardHeight / 2

            self.scoreboardDict[model].setPos(self.boardFactor*(self.backgroundWidth/2-\
            self.scoreboardDict[self.model].boundingRect.width()/2+width), self.backgroundHeight/2+\
            self.boardFactor*height+self.boardFactor*5)
예제 #26
0
def run_game():
    # 创建游戏窗口
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height)  # 加括号传入一个参数
    )  # display.set_mode(resolution=(0, 0))第一个参数为一个二元组,表示宽和高
    pygame.display.set_caption("Alien Invasion")
    screen.fill(ai_settings.bg_color)

    # 创建按钮
    play_button = Button(ai_settings, screen, "Play")
    play_button.draw_button()
    pygame.display.flip()

    # 存储游戏统计信息的实例
    starts = GameStarts(ai_settings)
    sb = Scoreboard(ai_settings, screen, starts)

    # 失败后显示
    string = "You lost a ship!"
    sl = ShowLose(ai_settings, screen, string)

    # 导入飞船
    ship = Ship(ai_settings, screen)

    # 创建编组
    bullets = Group()
    aliens = Group()

    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # 开始主循环:
    while True:
        # 响应玩家指令
        gf.check_events(ai_settings, screen, ship, aliens, bullets, starts,
                        play_button)  # 代替上面语句

        if starts.game_active:
            # 根据指令更新飞船位置
            ship.update()

            # 根据指令更新子弹
            gf.update_bullets(ai_settings, screen, starts, sb, bullets, ship,
                              aliens)
            gf.update_aliens(ai_settings, starts, screen, aliens, ship,
                             bullets, sl)

        gf.update_screen(ai_settings, screen, sb, ship, bullets, aliens,
                         play_button, starts)  # 重新绘制屏幕
예제 #27
0
def main():
    print "-----CURRENT SCOREBOARD-----"
    scoreboard = Scoreboard()
    scoreboard.importscores()
    # first log the player in or create them if they don't exist
    prompt_name = raw_input(str("What is your name? "))
    prompt_name_lower = prompt_name.lower()

    for root, dirs, files in os.walk(
        "/Users/teacher/Desktop/LPTHW/Second_Half/class_practice/math_class_with_snakes/logs"
    ):
        if (prompt_name_lower + "_log.bin") in files:
            print "Hello, %s, welcome back - you are logged in!\n" % prompt_name_lower.capitalize()
            f = open(
                "/Users/teacher/Desktop/LPTHW/Second_Half/class_practice/math_class_with_snakes/logs/"
                + prompt_name_lower
                + "_log.bin",
                "rb",
            )
            saved_score = int(f.read())
            f.close()
            prompt_name_lower = Player(prompt_name_lower)
            prompt_name_lower.setscore(saved_score)
            print "Your current score is %s.\n" % saved_score
            problem_loop(prompt_name_lower)
        else:
            print "We'll set you up a new user!\n"
            prompt_name_lower = Player(prompt_name_lower)
        while True:
            print "'any key' for new problem 'q' for quit\n"
            choice = str(raw_input())
            if choice == "q":
                # print "Bye, your score is %s" % prompt_name_lower.getscore()
                sys.exit(0)
            else:
                problem_loop(prompt_name_lower)
예제 #28
0
def run_game():
    # Initialize pygame
    pygame.mixer.pre_init(44100, 16, 2, 4096)
    pygame.init()

    # Initialize settings, scoreboard, and stats
    ai_settings = Settings()

    # Initialize game song
    space_invaders_wav = pygame.mixer.Sound('Sounds/spaceinvaders.wav')
    space_invaders_wav.play(-1)

    # Set up the screen to display to user
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Create a play button
    play_button = Button(screen, "Play")

    # Initialize the scoreboard and stats
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Create the objects in game
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # Create the fleet of aliens
    Functionality.create_fleet(ai_settings, screen, ship, aliens)

    # While Loop - controls updates of the game until user exits screen (or presses q)
    while True:
        Functionality.check_events(ai_settings, screen, stats, sb, play_button,
                                   ship, aliens, bullets)

        if stats.game_active:
            ship.update()
            Functionality.update_bullets(ai_settings, screen, stats, sb, ship,
                                         aliens, bullets)
            Functionality.update_aliens(ai_settings, screen, stats, sb, ship,
                                        aliens, bullets)

        Functionality.update_screen(ai_settings, screen, stats, sb, ship,
                                    aliens, bullets, play_button)
예제 #29
0
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    # 设置游戏题目
    pygame.display.set_caption("1")

    # 创建一个用于存储游戏统计信息的实例, 并创建计分板
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # 创建一艘飞船、一个子弹编组和一个外星人编组
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # 设置游戏主循环

    bg_color = (230, 230, 230)

    # 创建play按钮
    play_button = Button(ai_settings, screen, "Play")

    # 开始游戏的主循环
    while True:
        """响应按键和鼠标事件"""
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            """更新子弹的位置,并删除已消失的子弹"""
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            """更新外星人的位置"""
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        """更新屏幕上的图像, 并切换到新屏幕"""
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
예제 #30
0
def runGame():
    pygame.init()
    pongSettings = Settings()
    screen = pygame.display.set_mode(
        (pongSettings.screenWidth, pongSettings.screenHeight))
    pygame.display.set_caption("Pong 2")

    paddleTopBottom = Group()
    paddleLeftRight = Group()

    paddle = Paddle(pongSettings, screen, "player", "bottom")
    paddle3 = Paddle2(pongSettings, screen, "right")
    paddle5 = Paddle(pongSettings, screen, "player", "top")

    paddle2 = Paddle2(pongSettings, screen, "left")
    paddle4 = Paddle(pongSettings, screen, "AI", "top")
    paddle6 = Paddle(pongSettings, screen, "AI", "bottom")

    paddleTopBottom.add(paddle, paddle4, paddle5, paddle6)
    paddleLeftRight.add(paddle2, paddle3)
    ball = Ball(pongSettings, screen)
    divide = Divider(pongSettings, screen)

    play_button = Button(pongSettings, screen, "Play")
    sb = Scoreboard(pongSettings, screen)
    startScreen = Start(pongSettings, screen)

    while True:
        gf.checkEvents(pongSettings, paddle, paddle3, paddle5, play_button, sb)
        if pongSettings.gameActive:
            gf.checkPaddleBallCollision(ball, paddleTopBottom, paddleLeftRight,
                                        pongSettings)
            gf.checkOutOfBounds(ball, pongSettings, screen, sb)
            paddle.update(ball)
            paddle2.update(ball)
            paddle3.update(ball)
            paddle4.update(ball)
            paddle5.update(ball)
            paddle6.update(ball)
            ball.update()
            gf.updateScreen(pongSettings, screen, paddle, paddle2, paddle3,
                            paddle4, paddle5, paddle6, ball, divide, sb)
        else:
            gf.startGame(play_button, startScreen)
예제 #31
0
def run_game():
    # Initialize game and create a screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("Alien Invasion")

    # Set the background
    background = Background('Models/Space/Space1.png', [0, 0])

    # Make a ship
    ship = Ship(screen, ai_settings)

    # Make the play button
    play_button = Button(ai_settings, screen, "Play")

    # Create an instance to store game statistics.
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats, background)

    # Make a bullet group
    bullets = Group()

    # Make an alien group
    aliens = Group()

    # make a Explosion group
    explosions = Group()

    # create an alien fleet
    gf.create_fleet(ai_settings, screen, aliens, ship)

    # Start the main loop for the game
    while True:

        gf.check_events(ship, screen, bullets, stats, play_button, aliens,
                        ai_settings)
        gf.update_screen(background, screen, ship, bullets, aliens, explosions,
                         stats, play_button, sb)
        if stats.game_Active:
            ship.update()
            gf.update_bullets(bullets, aliens, explosions, screen, ship,
                              ai_settings, stats, sb)
            gf.update_aliens(aliens, ai_settings, ship, stats, screen, bullets)
예제 #32
0
    def __init__(self):
        super(Simulation_Window, self).__init__()
        palette = QPalette()
        palette.setColor(QPalette.Background, self.backgroundGrayColor)
        self.setPalette(palette)
        self.setWindowTitle('Scoreboard Simulation')

        c = Config()
        self.sport = c.configDict['sport']
        self.model = c.configDict['model']
        self.boardColor = c.configDict['boardColor']
        self.captionColor = c.configDict['captionColor']
        self.activeCaption = 0
        self.stripeColor = c.configDict['stripeColor']
        self.LEDcolor = c.configDict['LEDcolor']
        self.vboseList = [
            1, 0, 0
        ]  # controls verbosity for console, scoreboard, and lcd
        self.refreshAssets_frequency = 10  #milliseconds
        self.checkClickables_frequency = 10  #milliseconds
        self.scoreboardDict = {}
        self.reverseHomeAndGuest = False
        self.keypad3150 = False
        self.MMBasketball = False
        self.WHHBaseball = False
        self.simFlag = False
        self.captionBlankFlag = True
        self.serialInputFlag = False

        self.setOptionJumpers()

        models = Scoreboard('modelList',
                            vboseList=[0, 0, 0],
                            checkEventsFlag=False)
        self.modelList = models.modelList
        self.modelList.sort()
        board = Board()
        self.colorList = board.colorDict.keys()
        self.colorList.sort()

        self.modelDefaults = readModelDefaults()

        self.create_central_widget()
예제 #33
0
def run_game():
    """Инициализирует pygame, setting и объект экрана."""
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height)
        #,pygame.FULLSCREEN
    )
    pygame.display.set_caption("Alien Invasion")

    # Создание объектов.
    ship = Ship(ai_settings, screen)

    # Создание группы хранения пуль.
    bullets = Group()
    #hero = Character(screen)

    # Создание пришельца.
    #alien = Alien(ai_settings, screen)
    aliens = Group()

    # Создание экземпляра игровой статистики и счета.
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Создание кнопки Play.
    play_button = Button(ai_settings, screen, "PLAY")

    # Создание флота пришельцев.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Запуск основного цикла игры.
    while True:
        gf.check_events(ai_settings, stats, sb, screen, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, stats, sb, screen, ship, bullets, aliens,
                         play_button)
예제 #34
0
def main():
    level = Scoreboard()
    cars = []
    game_is_on = True
    while game_is_on:
        if random.randint(0, 30) == 15 and len(cars) < MAX_NUMBER_OF_CARS:
            cars.append(Car())
        for car in cars:
            if player.hit_car(car):
                game_is_on = False
                break
            car.move_left()
            if car.xcor() < -300:
                car.hideturtle()
                cars.remove(car)
        screen.update()
        player.crossed_street(level=level)
        time.sleep(0.01)
    screen.exitonclick()
예제 #35
0
      elif o in ("-v", "--verbose"):
         globalvars.verbose = True
      elif o in ("-q", "--quick"):
         globalvars.quick = True
      elif o in ("-q", "--quick"):
         globalvars.quick = True
      elif o in ("-n", "--nomovie"):
         globalvars.nomovie = True
      else:
         assert False, "unhandled option"
   flag_queue_obj = Queue.Queue()
   message_queue_obj = Queue.Queue()
   logger_obj = Logger("scorebot")
   flag_store = FlagStore(logger_obj, flag_queue_obj)
   message_store = MessageStore(logger_obj, message_queue_obj)
   flag_server = FlagServer(logger_obj, flag_queue_obj, message_queue_obj)
   t = threading.Thread(target=flag_server.serve_forever)
   t.start()
   blue_teams = read_config(cfg_file, flag_store)      
   myscoreboard = Scoreboard(blue_teams, flag_store, message_store)
   myscoreboard.start()
   for team in blue_teams.keys():
      blue_teams[team].add_queue(flag_queue_obj)
      blue_teams[team].start()
   flag_store.start()
   message_store.start()
   injects.start()   

if __name__ == "__main__":
   main()
예제 #36
0
    def __init__(self):
        printc("Starting...")

        # Job Scoreboard
        self._sb_job = Scoreboard(SCOREBOARD_DB_JOB, PROGRAM_NAME, 'NONE')
        # ACK Scoreboard
        self._sb_ack = Scoreboard(SCOREBOARD_DB_ACK, PROGRAM_NAME, 'NONE')

        # Clean redis job and ack database, done only by BaseForeman right at the start
        self._sb_job.flush_db()

        # Start internal job number at 0
        self._sb_job.reset_internal_job()

        self._machine_prefix = 'F:'
        self._machine_publish_q = Q_FORW_PUBLISH
        self._machine_consume_q = Q_FORW_CONSUME

        # Types of messages we expect to recieve from each kind of queue
        # DMCS messages
        self._msg_actions_dmcs = {
            'JOB': self.process_dmcs_job,
            'STANDBY': self.process_dmcs_standby,
            'READOUT': self.process_dmcs_readout,
            'CANCEL': self.process_dmcs_cancel
        }
        # NCSA messages
        self._msg_actions_ncsa = {
            'None'
        }
        # ACK messages
        self._msg_actions_ack = {
            'ACK_RECEIVED': self.process_ack_received
        }

        # Run parent init, starts forwarder scoreboard and consumer
        self.parent_init(SCOREBOARD_DB_FORW, PROGRAM_NAME, REGISTER_FORWARDER)

        # DMCS consumer gets messages about new jobs and changing job states
        printc("Creating DMCS consumer...")
        self._dmcs_consumer = Consumer(self._broker_url, Q_DMCS_PUBLISH)
        try:
            thread.start_new_thread(self.run_dmcs_consumer, ())
        except:
            printc("Thread run_dmcs_consumer failed, quitting...")
            sys.exit()

        # NCSA Foreman is monitoring the distributors and reports pairings
        printc("Creating NCSA consumer...")
        self._ncsa_consumer = Consumer(self._broker_url, Q_NCSA_PUBLISH)
        try:
            thread.start_new_thread(self.run_ncsa_consumer, ())
        except:
            printc("Thread run_ncsa_consumer failed, quitting...")
            sys.exit()

        # ACK consumer gets messages from the forwarders and NCSA confirming
        # if the orginial message was received
        printc("Creating ACK consumer...")
        self._ack_consumer = Consumer(self._broker_url, Q_ACK_PUBLISH)
        try:
            thread.start_new_thread(self.run_ack_consumer, ())
        except:
            printc("Thread run_ack_consumer failed, quitting...")
            sys.exit()
        return
예제 #37
0
 def test_updateScore_win(self):
     scoreboard = Scoreboard()
     value = 0
     scoreboard.updateScore(value)
     self.assertEqual(scoreboard.score, [1, 0, 0])
예제 #38
0
 def test_updateScore_tie(self):
     scoreboard = Scoreboard()
     value = 2
     scoreboard.updateScore(value)
     self.assertEqual(scoreboard.score, [0, 0, 1])
def run_game():
    # Get access to our game settings
    settings = Settings()
    engine = Engine()
 
    # initialize game
    pygame.init()
    screen = pygame.display.set_mode( (settings.screen_width, settings.screen_height), 0, 32)
    clock = pygame.time.Clock()
    scoreboard = Scoreboard(screen, settings)
    play_button = Button(screen, settings.screen_width/2-settings.button_width/2,
                            settings.screen_height/2-settings.button_height/2, settings, "Play Balloon Ninja")
    game_over_button = Button(screen, play_button.x_position, play_button.y_position-2*settings.button_height,
                            settings, "Game Over")
    instructions = Instructions(screen, settings)
 
    # Create a list to hold our balloons, and our kittens
    balloons = []
    kittens = []
 
    # Create our dagger
    sword = Sword(screen, settings.scoreboard_height)
 
    # main event loop
    while True:
        # Advance our game clock, get the current mouse position, and check for new events
        time_passed = clock.tick(50)
        mouse_x, mouse_y = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]
        engine.check_events(settings, scoreboard, sword, play_button, mouse_x, mouse_y, balloons)
 
        # Redraw the empty screen before redrawing any game objects
        screen.fill(settings.bg_color)
 
        if settings.game_active:
            # Update the sword's position and check for popped or disappeared balloons
            engine.update_sword(sword, mouse_x, mouse_y, settings)
            engine.check_balloons(balloons, kittens, sword, scoreboard, screen, settings, time_passed)
            engine.check_kittens(kittens, sword, scoreboard, screen, settings, time_passed)
 
            # If all balloons have disappeared, either through popping or rising,
            #  release a new batch of balloons.
            if len(balloons) == 0:
                # If we are not just starting a game, increase the balloon speed and points per balloon,
                #  and increment batches_finished
                if scoreboard.balloons_popped > 0:
                    #  Increase the balloon speed, and other factors, for each new batch of balloons.
                    settings.balloon_speed *= settings.speed_increase_factor
                    settings.kitten_ratio *= settings.speed_increase_factor
                    settings.points_per_balloon = int(round(settings.points_per_balloon * settings.speed_increase_factor))
                    scoreboard.batches_finished += 1
                # If player has completed required batches, increase batch_size
                if scoreboard.batches_finished % settings.batches_needed == 0 and scoreboard.batches_finished > 0:
                    settings.batch_size += 1
                engine.release_batch(screen, settings, balloons, kittens)
        else:
            # Game is not active, so...
            #  Show play button
            play_button.blitme()
            #  Show instructions for first few games.
            if settings.games_played < 3:
                instructions.blitme()
            #  If a game has just ended, show Game Over button
            if settings.games_played > 0:
                game_over_button.blitme()
 
        # Display updated scoreboard
        scoreboard.blitme()
 
        # Show the redrawn screen
        pygame.display.flip()
예제 #40
0
class Foreman:
    # Parent class for Base and NCSA Foremen.
    # Contains set up for forwarder and distributor machines
    # along with code that was common between them.
    def parent_init(self, db_num, prog_name, type):
        custom_print.define_new_name(self.PROGRAM_NAME)

        # Create machine scoreboard
        self._sb_mach = Scoreboard(db_num, prog_name, type)

        # Messaging URL (rabbitmq server IP)
        self._broker_url = "amqp://" + AMQP_BF_USER + ":" + AMQP_BF_PSWD + "@" + AMQP_BROKER_ADDR + ":" + AMQP_BROKER_PORT + "/" + AMQP_BROKER_VHOST

        # Publisher object for sending messages to rabbit
        printc("Creating publisher...")
        self._publisher = SimplePublisher(self._broker_url)

        # Machine messages
        self._msg_actions_mach = {
            'TRANSFER_DONE': self.process_transfer_done,  # Machine done with the current job
            'REGISTER': self.process_register,  # New machine wants to join
            'DEREGISTER': self.process_deregister,  # Machine is leaving
            'STATE_UPDATE': self.process_state_update  # Machine updating us on its state
        }

        # Machines register with us and let us know how they are doing
        printc("Creating machine consumer...")
        self._mach_consumer = Consumer(self._broker_url, self._machine_publish_q)
        try:
            thread.start_new_thread(self.run_mach_consumer, ())
        except:
            printc("Thread run_mach_consumer failed, quitting...")
            sys.exit()

        return

    def run_mach_consumer(self):
        # Consume messages continuously
        printc("Machine message consumer is running...")
        self._mach_consumer.run(self.on_mach_message)
        return

    def on_mach_message(self, ch, method, properties, body):
        # Callback from consumer to process machine messages
        # Load the message which came in yaml format
        msg_dict = yaml.load(body)
        # Determine which function needs to be called for this message type
        try:
            af_handler = self._msg_actions_mach.get(msg_dict[MSG_TYPE])
        except:
            printc("Bad machine message received...")
            ch.basic_ack(delivery_tag=method.delivery_tag)
            return
        # Call that function and provide it with the message
        af_handler(msg_dict)
        # Acknowledge that we processed the message so rabbit can remove it from the queue
        ch.basic_ack(delivery_tag=method.delivery_tag)
        return

    def process_register(self, msg_params):
        # Process a request for a machine that is registering with us
        printc("Processing name request...")
        tmp_name = self.pick_name()
        while False == self._sb_mach.register_machine(tmp_name):
            tmp_name = self.pick_name()
        self._sb_mach._redis.hset(tmp_name, 'IP_ADDR', msg_params['IP_ADDR'])
        printc("%s has registered. (%s)" % (tmp_name, msg_params['IP_ADDR']))
        msg = {}
        msg[MSG_TYPE] = 'REGISTRATION'
        msg[NAME] = tmp_name
        self._publisher.publish_message(self._machine_consume_q, yaml.dump(msg))
        return

    def pick_name(self):
        # Name creation
        tmp_name = ''.join(random.choice(string.ascii_letters) for x in range(NAME_LENGTH))
        return self._machine_prefix + tmp_name

    def process_deregister(self, msg_params):
        # Machine is deregistering with us
        printc("%s has deregistered." % msg_params[NAME])
        self._sb_mach.machine_deregister(msg_params[NAME])
        return

    def process_state_update(self, msg_params):
        # Machine is updating us on something, report it in the Scoreboard
        self._sb_mach.machine_update(msg_params['KEY'], msg_params['FIELD'], msg_params['VALUE'])
        return

    def process_transfer_done(self, msg_params):
        return
예제 #41
0
 def test_updateScore_lose(self):
     scoreboard = Scoreboard()
     value = 1
     scoreboard.updateScore(value)
     self.assertEqual(scoreboard.score, [0, 1, 0])
예제 #42
0
class BaseForeman(Foreman):
    # BaseForeman receives messages from DMCS
    # and coordinates with forwarders and NCSAForeman.
    PROGRAM_NAME = "BASE"

    def __init__(self):
        printc("Starting...")

        # Job Scoreboard
        self._sb_job = Scoreboard(SCOREBOARD_DB_JOB, PROGRAM_NAME, 'NONE')
        # ACK Scoreboard
        self._sb_ack = Scoreboard(SCOREBOARD_DB_ACK, PROGRAM_NAME, 'NONE')

        # Clean redis job and ack database, done only by BaseForeman right at the start
        self._sb_job.flush_db()

        # Start internal job number at 0
        self._sb_job.reset_internal_job()

        self._machine_prefix = 'F:'
        self._machine_publish_q = Q_FORW_PUBLISH
        self._machine_consume_q = Q_FORW_CONSUME

        # Types of messages we expect to recieve from each kind of queue
        # DMCS messages
        self._msg_actions_dmcs = {
            'JOB': self.process_dmcs_job,
            'STANDBY': self.process_dmcs_standby,
            'READOUT': self.process_dmcs_readout,
            'CANCEL': self.process_dmcs_cancel
        }
        # NCSA messages
        self._msg_actions_ncsa = {
            'None'
        }
        # ACK messages
        self._msg_actions_ack = {
            'ACK_RECEIVED': self.process_ack_received
        }

        # Run parent init, starts forwarder scoreboard and consumer
        self.parent_init(SCOREBOARD_DB_FORW, PROGRAM_NAME, REGISTER_FORWARDER)

        # DMCS consumer gets messages about new jobs and changing job states
        printc("Creating DMCS consumer...")
        self._dmcs_consumer = Consumer(self._broker_url, Q_DMCS_PUBLISH)
        try:
            thread.start_new_thread(self.run_dmcs_consumer, ())
        except:
            printc("Thread run_dmcs_consumer failed, quitting...")
            sys.exit()

        # NCSA Foreman is monitoring the distributors and reports pairings
        printc("Creating NCSA consumer...")
        self._ncsa_consumer = Consumer(self._broker_url, Q_NCSA_PUBLISH)
        try:
            thread.start_new_thread(self.run_ncsa_consumer, ())
        except:
            printc("Thread run_ncsa_consumer failed, quitting...")
            sys.exit()

        # ACK consumer gets messages from the forwarders and NCSA confirming
        # if the orginial message was received
        printc("Creating ACK consumer...")
        self._ack_consumer = Consumer(self._broker_url, Q_ACK_PUBLISH)
        try:
            thread.start_new_thread(self.run_ack_consumer, ())
        except:
            printc("Thread run_ack_consumer failed, quitting...")
            sys.exit()
        return

    # Message consumer functions, each blocks while waiting for a new message

    def run_dmcs_consumer(self):
        printc("DMCS message consumer is running...")
        self._dmcs_consumer.run(self.on_dmcs_message)
        printc("Exiting dmcs consumer")
        return

    def run_ncsa_consumer(self):
        printc("NCSA message consumer is running...")
        self._ncsa_consumer.run(self.on_ncsa_message)
        return

    def run_ack_consumer(self):
        printc("ACK message consumer is running...")
        self._ack_consumer.run(self.on_ack_message)
        return

    # Forwarder-specific messaging

    def process_transfer_done(self, msg_params):
        # Forwarder is finished with its current job
        forw_finished = msg_params[NAME]
        # Only continue if the forw reported finish on the job it is on
        if (msg_params[JOB_NUM] ==
                self._sb_mach.get_machine_job_num(forw_finished)):
            self._sb_mach.change_machine_status_to_idle(forw_finished)
            cur_workers = int(self._sb_job.get_job_value(msg_params[JOB_NUM],
                                                         'ASSIGNED_WORKERS')) - 1
            self._sb_job.add_job_value(msg_params[JOB_NUM], 'ASSIGNED_WORKERS',
                                       cur_workers)
            # If this was the last working, the just is finished
            if 0 == cur_workers:
                self._sb_job.add_job_value(msg_params[JOB_NUM], 'TIME_FINISHED',
                                           self._sb_job._redis.time()[0])
                self._sb_job.add_job_value(msg_params[JOB_NUM], 'STATUS',
                                           'INACTIVE')
                self._sb_job.set_job_state(msg_params[JOB_NUM], FINISHED)
        return

    # DMCS messaging

    def on_dmcs_message(self, ch, method, properties, body):
        # Consumer callback function
        msg_dict = yaml.load(body)
        try:
            af_handler = self._msg_actions_dmcs.get(msg_dict[MSG_TYPE])
        except:
            printc("Bad DMCS message received...")
            ch.basic_ack(delivery_tag=method.delivery_tag)
            return
        af_handler(msg_dict)
        ch.basic_ack(delivery_tag=method.delivery_tag)
        return

    def process_dmcs_job(self, msg_params):
        # DMCS is sending a new job
        # DMCS's job number
        external_job_val = str(msg_params[JOB_NUM])
        # BaseForeman's internal job value
        current_job = self._sb_job.new_job()
        current_raft = int(msg_params[RAFT_NUM])

        # Add the current job to the Job Scoreboard
        self._sb_job.add_job_value(current_job, 'TIME_STARTED',
                                   self._sb_job._redis.time()[0])
        self._sb_job.add_job_value(current_job, RAFTS, current_raft)
        self._sb_job.add_job_value(current_job, 'EXT_JOB_NUM', external_job_val)
        self._sb_job.add_job_value(current_job, 'STATUS', 'ACTIVE')
        self._sb_job.set_job_state(current_job, CHECKING_RESOURCES)
        self._sb_job.add_job(current_job)

        # Check if the forwarders needed are available
        # Number of rafts is number of forwarders we need
        forwarders_needed = current_raft
        # Get the total amount of idle forwarders
        num_healthy_forwarders = self._sb_mach.count_idle(LIST_FORWARDERS)
        printc("DMCS is requesting %d pairs, have %d pairs available."
               % (forwarders_needed, num_healthy_forwarders))
        # If there are not enough forwarders then
        # tell DMCS we cannot accept this job right now
        if forwarders_needed > num_healthy_forwarders:
            self._sb_job.set_job_state(current_job, 'JOB_FAILED_INSUF_FORWDRS')
            self._sb_job.add_job_value(current_job, 'TIME_FAILED',
                                       self._sb_job._redis.time()[0])
            # Send message to DMCS that we cannot do this job yet.
            failed_msg = {}
            failed_msg[MSG_TYPE] = INSUFFICIENT_FORWARDERS
            failed_msg[JOB_NUM] = msg_params[JOB_NUM]
            failed_msg[NEEDED_WORKERS] = str(forwarders_needed)
            failed_msg[AVAILABLE_FORWARDERS] = str(num_healthy_forwarders)
            self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
            return
        # Otherwise, we have the needed forwarders.
        # Now we need to ask NCSA if they have the needed distributors
        else:
            # Get number of forwarders we need and set them to BUSY from IDLE
            forw_list = self._sb_mach.get_idle_list(LIST_FORWARDERS, forwarders_needed, current_job)
            # Update the Job Scoreboard
            self._sb_job.add_job_value(current_job, 'AVAIL_FORW', num_healthy_forwarders)
            self._sb_job.add_job_value(current_job, 'FORW_NEEDED', forwarders_needed)
            self._sb_job.set_job_state(current_job, 'WAITING_FOR_NCSA_RESP')
            # Send NCSA a Job Request
            # This is a heads up, we do not check for a response to this
            job_request = {}
            job_request[MSG_TYPE] = JOB_REQUEST
            printc("Sending Job Request to NCSA...")
            self._publisher.publish_message(Q_NCSA_CONSUME, yaml.dump(job_request))

            # Send forwarders New Job message (i.e. Health Check)
            # This is a timed event
            timer_id = 'ACK:1_Health:' + current_job
            new_job = {}
            new_job[MSG_TYPE] = JOB
            new_job[ACK_ID] = timer_id
            new_job[ACK_TYPE] = HEALTH
            new_job[JOB_NUM] = current_job
            printc("Sending New Job Request to the Forwarders...")
            for forw in forw_list:
                routing_key = forw + "_consume"
                self._publisher.publish_message(routing_key, yaml.dump(new_job))
            printc("Starting the New Job Request Timer")
            if not self.timer(3, timer_id, forw_list):
                printc("Timer Expired without all Forwarders reporting...")
                # Check Ack SB to see which ones did not report
                # Tell DMCS we cannot do this job
                failed_msg = {}
                failed_msg[MSG_TYPE] = INSUFFICIENT_FORWARDERS
                failed_msg[JOB_NUM] = msg_params[JOB_NUM]
                failed_msg[NEEDED_WORKERS] = str(forwarders_needed)
                failed_msg[AVAILABLE_FORWARDERS] = str(self._sb_ack.count_ack(timer_id, forw_list))
                self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
                return
            # Send NCSA a distributor request message
            # This is a timed event
            # Must reset the global dict
            timer_id = 'ACK:2_Dist_req:' + current_job
            global glb_pair_list
            glb_pair_list = None
            ncsa_dist_request = {}
            ncsa_dist_request[MSG_TYPE] = DISTRIBUTOR_REQUEST
            ncsa_dist_request[DIST_NEEDED] = forwarders_needed
            ncsa_dist_request['FORW_LIST'] = forw_list
            ncsa_dist_request[JOB_NUM] = msg_params[JOB_NUM]
            ncsa_dist_request[ACK_ID] = timer_id
            ncsa_dist_request[ACK_TYPE] = 'PAIR'
            self._publisher.publish_message(Q_NCSA_CONSUME, yaml.dump(ncsa_dist_request))
            printc("Starting Timer for NCSA Reporting...")
            if not self.timer(2, timer_id, {'PAIRING'}):
                printc("Timer Expired without NCSA reporting")
                # Tell DMCS we reject the job
                failed_msg = {}
                failed_msg[MSG_TYPE] = 'NO_NCSA_RESP_TO_DIST_REQ'
                failed_msg[JOB_NUM] = msg_params[JOB_NUM]
                self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
                return
            # Check if pair list is still set to None
            # This means NCSA responded with ACK_BOOL as FALSE
            if glb_pair_list is None:
                printc("No pair list, NCSA didn't have enough distributors.")
                # NCSA did not have enough distributors available, reject this job for now
                current_job = msg_params[JOB_NUM]
                forw_list = self._sb_mach.machine_find_all_m(LIST_FORWARDERS, current_job)
                # Set forwarders we reserved for this job from BUSY back to IDLE
                self._sb_mach.set_list_to_idle(forw_list)
                self._sb_job.set_job_state(current_job, 'STANDBY_JOB_DENIED_INSUF_DIST')
                self._sb_job.add_job_value(current_job, 'TIME_FAILED',
                                   self._sb_job._redis.time()[0])
                self._sb_job.add_job_value(current_job, 'STATUS', 'INACTIVE')
                # Tell DMCS we reject the job
                failed_msg = {}
                failed_msg[MSG_TYPE] = 'INSUFFICIENT_DISTRIBUTORS'
                failed_msg[JOB_NUM] = msg_params[JOB_NUM]
                self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
                return
            # Quick sanity check to make sure we
            # got back the number we asked for
            if len(glb_pair_list) != forwarders_needed:
                printc("Invalid pair list, failed to accept job.")
                # Tell DMCS we reject the job
                failed_msg = {}
                failed_msg[MSG_TYPE] = 'INVALID_PAIR_LIST'
                failed_msg[JOB_NUM] = msg_params[JOB_NUM]
                self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
                return
            printc("Pair list is %r" % glb_pair_list)
            # Update Job scoreboard
            self._sb_job.add_job_value(current_job, 'ASSIGNED_WORKERS', len(glb_pair_list))
            self._sb_job.add_job_value(current_job, 'PAIRS', glb_pair_list)
            # Report to DMCS that we accept the job
            accept_job_msg = {}
            accept_job_msg[MSG_TYPE] = 'JOB_ACCEPTED'
            accept_job_msg[JOB_NUM] = msg_params[JOB_NUM]
            self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(accept_job_msg) )
            self._sb_job.set_job_state(current_job, 'JOB_ACCEPTED')
            return

    def process_dmcs_standby(self, msg_params):
        # A job has been moved to the STANDBY step.
        # Forwarders need to start pulling header data and
        # distributors need to be ready to catch.
        external_job_val = str(msg_params[JOB_NUM])
        # Get the internal job value that correlates with this external job
        current_job = self._sb_job.find_ext_job(external_job_val)
        if "NOT_FOUND" == current_job:
            printc("External job %s is not on the job scoreboard." % external_job_val)
            printc("STANDBY failed.")
            return

        # Generate a file name (for testing only)
        xfer_file_main = ("%04d%02d%02d-%02d%02d%02d-%06d"
                          % (datetime.datetime.today().year,
                             datetime.datetime.today().month,
                             datetime.datetime.today().day,
                             datetime.datetime.today().hour,
                             datetime.datetime.today().minute,
                             datetime.datetime.today().second,
                             datetime.datetime.today().microsecond))

        # Update job scoreboard
        self._sb_job.add_job_value(current_job, XFER_FILE, xfer_file_main)
        self._sb_job.set_job_state(current_job, 'STANDBY_FORW_DIST_ALERTING')

        # Alert NCSA Foreman this job is entering STANDBY
        # This is a timed event
        timer_id = 'ACK:3_Standby:' + current_job
        ncsa_standby_alert = {}
        ncsa_standby_alert[MSG_TYPE] = STANDBY
        ncsa_standby_alert[JOB_NUM] = current_job
        ncsa_standby_alert[XFER_FILE] = xfer_file_main
        ncsa_standby_alert[ACK_ID] = timer_id
        ncsa_standby_alert[ACK_NAME] = 'STANDBY'
        printc("Telling NCSA we are moving to STANDBY")
        self._publisher.publish_message(Q_NCSA_CONSUME, yaml.dump(ncsa_standby_alert))

        # Send STANDBY to all the forwarders in this job
        global glb_pair_list
        # pairs = self._sb_mach.machine_find_all_pairs(current_job)
        pairs = glb_pair_list
        forwarders = pairs.keys()
        for forwarder in forwarders:
            printc("Sending %s standby..." % forwarder)
            fw_msg = {}
            fw_msg[MSG_TYPE] = STANDBY
            fw_msg[MATE] = pairs[forwarder]
            fw_msg[JOB_NUM] = current_job
            fw_msg[XFER_FILE] = string.replace(xfer_file_main + '_' + pairs[forwarder] + '.raw', "D:", "")
            fw_msg[ACK_ID] = timer_id
            fw_msg[ACK_TYPE] = STANDBY
            routing_key = forwarder + "_consume"
            self._publisher.publish_message(routing_key, yaml.dump(fw_msg))
        # Append STANDBY to the expected acks list
        forwarders.append('NCSA_STANDBY')
        printc("Starting the STANDBY timer")
        if not self.timer(4, timer_id, forwarders):
            printc("Timer Expired without NCSA and FORWARDERS reporting in STANDBY")
            # Check ACK SB to see who did not report
            if not self._sb_ack.check_ack(timer_id, 'NCSA_STANDBY'):
                failed_msg = {}
                failed_msg[MSG_TYPE] = 'NO_NCSA_RESP_TO_STANDBY'
                failed_msg[JOB_NUM] = msg_params[JOB_NUM]
                self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
                return
            else:
                failed_msg = {}
                failed_msg[MSG_TYPE] = 'MISSING_FORW_STANDBY'
                failed_msg[JOB_NUM] = msg_params[JOB_NUM]
                failed_msg['MISSING'] = str(self._sb_ack.missing_acks(timer_id, forwarders))
                self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
                return
        # Report to DMCS that the job is still good to go
        standby_job_msg = {}
        standby_job_msg[MSG_TYPE] = 'STANDBY_COMPLETE'
        standby_job_msg[JOB_NUM] = msg_params[JOB_NUM]
        self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(standby_job_msg) )
        self._sb_job.set_job_state(current_job, 'STANDBY')
        return

    def process_dmcs_readout(self, msg_params):
        # A job has been moved to the READOUT step.
        # Forwarders need to pull images from the camera buffer,
        # append the data and send the image files to the distributors
        external_job_val = str(msg_params[JOB_NUM])
        # Get the internal job value that correlates with this external job
        current_job = self._sb_job.find_ext_job(external_job_val)
        if "NOT_FOUND" == current_job:
            printc("External job %s is not on the job scoreboard." % external_job_val)
            printc("READOUT failed.")
            return
        # If job was not in STANDBY, recover by calling that function first
        if 'STANDBY' != self._sb_job.get_job_state(current_job):
            printc("READOUT without STANDBY for Job ID %s, calling STANDBY first." % current_job)
            self.process_dmcs_standby(msg_params)
        printc("READOUT processing for Job ID %s." % current_job)
        self._sb_job.set_job_state(current_job, 'READOUT')

        # Alert NCSA Foreman we are entering READOUT
        # This is a timed event
        timer_id = 'ACK:4_Readout:' + current_job
        ncsa_readout_alert = {}
        ncsa_readout_alert[MSG_TYPE] = READOUT
        ncsa_readout_alert[JOB_NUM] = current_job
        ncsa_readout_alert[ACK_ID] = timer_id
        ncsa_readout_alert[ACK_TYPE] = READOUT
        self._publisher.publish_message(Q_NCSA_CONSUME, yaml.dump(ncsa_readout_alert))
        printc("Starting the NCSA READOUT timer...")
        if not self.timer(4, timer_id, {'READOUT'} ):
            printc("Timer expired without NCSA reporting in READOUT")
            failed_msg = {}
            failed_msg[MSG_TYPE] = 'NO_NCSA_RESP_TO_READOUT'
            failed_msg[JOB_NUM] = msg_params[JOB_NUM]
            self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
            return
        # Send READOUT to forwarders
        # This is a timed event
        # In this prototype, we will wait for forwarders acks
        # instead of Condor, since we do not have that created
        timer_id = 'ACK:5_Condor:' + current_job
        pairs = self._sb_mach.machine_find_all_pairs(current_job)
        printc("%r" % pairs)
        forwarders = pairs.keys()
        for forwarder in forwarders:
            printc("Sending %s  readout..." % forwarder)
            fw_msg = {}
            fw_msg[MSG_TYPE] = READOUT
            fw_msg[JOB_NUM] = msg_params[JOB_NUM]
            fw_msg[ACK_ID] = timer_id
            fw_msg[ACK_TYPE] = READOUT
            routing_key = forwarder + "_consume"
            self._publisher.publish_message(routing_key, yaml.dump(fw_msg))

        printc("Starting the timer for Condor ACK... ")
        # For now it is just waiting for the acks from the forwarders
        if not self.timer(4, timer_id, forwarders):
            printc("Timer Expired without Condor reporting in READOUT")
            # Can check ACK_SB to see who did not report
            failed_msg = {}
            failed_msg[MSG_TYPE] = 'MISSING_CONDOR_RESP'
            failed_msg[JOB_NUM] = msg_params[JOB_NUM]
            failed_msg[NEEDED_WORKERS] = str(forwarders_needed)
            failed_msg['MISSING'] = str(self._sb_ack.missing_acks(timer_id, forwarders))
            self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(failed_msg))
            return
        # Report to DMCS that the job was completed
        completed_job_msg = {}
        completed_job_msg[MSG_TYPE] = 'JOB_COMPLETE'
        completed_job_msg[JOB_NUM] = msg_params[JOB_NUM]
        self._publisher.publish_message(Q_DMCS_CONSUME, yaml.dump(completed_job_msg) )
        self._sb_job.set_job_state(current_job, 'JOB_COMPLETE')
        return

    def process_dmcs_cancel(self, msg_params):
        # Job was canceled, attempt to stop it.
        job_to_stop = self._sb_job.find_ext_job(msg_params[JOB_NUM])
        if "NOT_FOUND" == job_to_stop:
            printc("External job %s is not on the job scoreboard." % external_job_val)
            printc("CANCEL failed.")
            return
        cur_state = self._sb_job.get_job_value(job_to_stop, 'STATE')
        if FINISHED == cur_state:
            printc("Can't cancel this job, it is already done.")
            return
        printc("Canceling external job %s (internal job %s)..." % (msg_params[JOB_NUM], job_to_stop))
        self._sb_job.set_job_state(job_to_stop, 'JOB_CANCELED')
        self._sb_job.add_job_value(job_to_stop, 'TIME_CANCELED', self._sb_job._redis.time()[0])
        self._sb_job.add_job_value(job_to_stop, 'STATUS', 'INACTIVE')

        # Tell NCSA Foreman we are canceling this job
        stop_msg = {}
        stop_msg[MSG_TYPE] = 'CANCEL'
        stop_msg[JOB_NUM] = str(job_to_stop)
        self._publisher.publish_message(Q_NCSA_CONSUME, yaml.dump(stop_msg))

        # Tell forwarders we are canceling this job
        list_of_q = self._sb_mach.machine_find_job(LIST_FORWARDERS, job_to_stop)
        for q in list_of_q:
            self._publisher.publish_message(q, yaml.dump(stop_msg))
        printc("Job canceled. (Hopefully)")
        return

    # NCSA messaging

    def on_ncsa_message(self, ch, method, properties, body):
        # Consumer callback Function
        msg_dict = yaml.load(body)
        af_handler = self._msg_actions_ncsa.get(msg_dict[MSG_TYPE])
        af_handler(msg_dict)
        ch.basic_ack(delivery_tag=method.delivery_tag)
        return

    # Acknowledgment messaging

    def on_ack_message(self, ch, method, properties, body):
        msg_dict = yaml.load(body)
        af_handler = self._msg_actions_ack.get(msg_dict.get(MSG_TYPE))
        if af_handler is not None:
            af_handler(msg_dict)
        ch.basic_ack(delivery_tag = method.delivery_tag)
        return

    def process_ack_received(self, msg_params):
        ack_id = msg_params.get(ACK_ID)
        ack_type = msg_params.get(ACK_TYPE)
        ack_name = msg_params.get(ACK_NAME)
        ack_bool = msg_params.get(ACK_BOOL)
        printc("Received ACK with name %s with ID %s" % (ack_name, ack_id))
        # Update ACK Scoreboard
        if not self._sb_ack.update_ack(ack_id, ack_name):
            printc("Unable to add the ack...")
        if PAIRS in msg_params and ack_bool:
            printc("Updating the pair list")
            global glb_pair_list
            glb_pair_list = msg_params.get(PAIRS)
        return

    def timer(self, delay, ack_id, ack_expected):
        count = delay * TIMER_PRECISION
        while (count and not self._sb_ack.check_ack(ack_id, ack_expected) ):
            time.sleep(1/float(TIMER_PRECISION))
            count = count - 1
        return self._sb_ack.check_ack(ack_id, ack_expected)