Пример #1
0
 def __init__(self):
     pygame.sprite.Group.__init__(self)
     self.middle = WIDTH // 2 # 30 appart
     self.height = 20
     self.score = 0
     self.add(Score(0, ( self.middle - 15, self.height)))
     self.add(Score(0, ( self.middle + 15, self.height)))
Пример #2
0
    def test_set_names(self):
        from score import Score

        sc = Score("6-4 3-6 7-6(5)")
        self.assertEqual(get_names(sc, setnum=1), ("open", "open"))
        self.assertEqual(get_names(sc, setnum=2), ("press", "under"))
        self.assertEqual(get_names(sc, setnum=3), ("decided", "decided"))

        sc = Score("6-4 3-6 7-5 1-6 7-6(5)")
        self.assertEqual(get_names(sc, setnum=1), ("open", "open"))
        self.assertEqual(get_names(sc, setnum=2), ("press", "under"))
        self.assertEqual(get_names(sc, setnum=3), ("open2", "open2"))
        self.assertEqual(get_names(sc, setnum=4), ("press", "under"))
        self.assertEqual(get_names(sc, setnum=5), ("decided", "decided"))

        sc = Score("6-4 6-3 5-7 1-6 7-6(5)")
        self.assertEqual(get_names(sc, setnum=1), ("open", "open"))
        self.assertEqual(get_names(sc, setnum=2), ("press", "under"))
        self.assertEqual(get_names(sc, setnum=3), ("press2", "under2"))
        self.assertEqual(get_names(sc, setnum=4), ("press", "under"))
        self.assertEqual(get_names(sc, setnum=5), ("decided", "decided"))

        sc = Score("4-6 3-6 7-5 6-1 7-6(5)")
        self.assertEqual(get_names(sc, setnum=1), ("open", "open"))
        self.assertEqual(get_names(sc, setnum=2), ("under", "press"))
        self.assertEqual(get_names(sc, setnum=3), ("under2", "press2"))
        self.assertEqual(get_names(sc, setnum=4), ("under", "press"))
        self.assertEqual(get_names(sc, setnum=5), ("decided", "decided"))
Пример #3
0
    def scour(self):
        """Returns a full list of results, categorized in sublists."""

        master_list = [self.scrape_titles(), self.scrape_taglines(), \
            self.scrape_cashflows(), self.scrape_descriptions(), [], \
            self.scrape_urls()]

        # Let's first ensure all vectors are the same length
        # If Taglines too short, it's because basic listings have no TL
        difference = len(master_list[0]) - len(master_list[1])
        if (len(master_list[0]) == len(master_list[2]) and difference):
            master_list[1].extend(["(No Tagline)" for i in range(difference)])

        if self.positive_inputs is None and self.negative_inputs is None:
            for i, desc in enumerate(master_list[3]):
                master_list[4].append(Score(" ".join([master_list[0][i], \
                    master_list[1][i], desc])))
        else:
            for i, desc in enumerate(master_list[3]):
                master_list[4].append(Score(" ".join([master_list[0][i], \
                    master_list[1][i], desc]), \
                    positive_inputs=self.positive_inputs, \
                    negative_inputs=self.negative_inputs))

        return master_list
    def testScorePlayer1Score(self):
        print('Describe: p1 scores a point')
        tests = [
            {
                'x': 740,
                'y': 200,
                'speed': [3, 3],
                'p1': 3,
                'p2': 1,
                'ansP1': 4,
                'ansP2': 1
            },
            {
                'x': 200,
                'y': 200,
                'speed': [3, 3],
                'p1': 3,
                'p2': 1,
                'ansP1': 3,
                'ansP2': 1
            },
        ]

        for t in tests:
            b = Ball(t['x'], t['y'], t['speed'])
            p1 = Score(100, t['p1'])
            p2 = Score(400, t['p2'])
            p1.playerScored(b, p2)

            self.assertEqual(p1.score, t['ansP1'],
                             'player1 score should be ' + str(t['ansP1']))
            self.assertEqual(p2.score, t['ansP2'],
                             'player2 score should be ' + str(t['ansP2']))
    def testScorePlayer2Score(self):
        print('Describe: p2 scores a point')
        tests = [
            {
                'x': -16,
                'y': 200,
                'speed': [-3, 3],
                'p1': 2,
                'p2': 2,
                'ansP1': 2,
                'ansP2': 3
            },
            {
                'x': 200,
                'y': 200,
                'speed': [-3, 3],
                'p1': 2,
                'p2': 2,
                'ansP1': 2,
                'ansP2': 2
            },
        ]

        for t in tests:
            b = Ball(t['x'], t['y'], t['speed'])
            p1 = Score(100, t['p1'])
            p2 = Score(400, t['p2'])
            p2.botScored(b, p1)

            self.assertEqual(p1.score, t['ansP1'],
                             'player1 score should be ' + str(t['ansP1']))
            self.assertEqual(p2.score, t['ansP2'],
                             'player2 score should be ' + str(t['ansP2']))
Пример #6
0
    def __init__(self, parent, score):
        Location.__init__(self, parent, end_background)

        self.save_score(score)

        pygame.mouse.set_visible(1)
        pygame.key.set_repeat(0)

        self.start_button = PlayAgainButton(240, 250)
        
        self.message1 = Score(240, 350, "Your score: ", 50, (0, 0, 0))
        self.score = Score(240, 400, str(score), 45, (0, 0, 0))

        self.message2 = Score(240, 450, "Your high score: ", 50, (0, 0, 0))
        self.high_score = Score(240, 500, str(self.get_high_score()), 45, (0, 0, 0))

        self.surfaces = []
        self.controls = pygame.sprite.Group()
        self.controls.add(self.start_button)
        
        self.messages = pygame.sprite.Group()
        self.messages.add(self.message1)
        self.messages.add(self.message2)
        self.messages.add(self.score)
        self.messages.add(self.high_score)
        
        self.window.blit(self.background, (0, 0))
Пример #7
0
    def test_tie_loser_result(self):
        scr = Score("6-4 7-6(5)")
        self.assertTrue(scr.tie_loser_result(setnum=2) == 5)

        scr = Score("6-4 3-6 2-6 7-6(12) 22-20")
        self.assertTrue(scr.tie_loser_result(setnum=4) == 12)
        self.assertTrue(scr.tie_loser_result(setnum=1) is None)
    def testScorePlayer1Win(self):
        print('Describe: checkWin Function: p1 wins')
        p1 = Score(100, 11)
        p2 = Score(400, 7)
        p1.checkWin(p2)

        self.assertEqual(p1.score, 0, 'player1 score should be 0')
        self.assertEqual(p2.score, 0, 'player2 score should be 0')
Пример #9
0
def mainLoop(clock, window, sprites, audio):
    run = True
    status = Status.inMenu
    tick = 0

    drawer = Drawer(window)

    hitBoxe = HitBoxe(audio.hitSound, audio.dieSound, audio.pointSound)

    base = Base(sprites.base)
    bird = Bird(sprites.bird, audio.wingSound, hitBoxe)
    pipes = Pipes(sprites.pipe, hitBoxe)
    score = Score(sprites.numbers)

    while run:
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN
                                             and event.key == pygame.K_ESCAPE):
                run = False
            if status == Status.inMenu and event.type == pygame.KEYUP and (
                    event.key == pygame.K_SPACE or event.key == pygame.K_UP):
                status = Status.inGame
            if status == Status.inGame and event.type == pygame.KEYDOWN and (
                    event.key == pygame.K_SPACE or event.key == pygame.K_UP):
                bird.jump()
            if status == Status.inGameOver and event.type == pygame.KEYUP and (
                    event.key == pygame.K_SPACE or event.key == pygame.K_UP):
                status = Status.inMenu
                tick = 0
                base = Base(sprites.base)
                bird = Bird(sprites.bird, audio.wingSound, hitBoxe)
                pipes = Pipes(sprites.pipe, hitBoxe)
                score = Score(sprites.numbers)

        if status == Status.inGame:
            hitBase = hitBoxe.birdHitBase(bird, base)
            hitPipe = hitBoxe.birdHitPipes(bird, pipes)
            hitBoxe.birdPassPipe(bird, pipes.pipes, score)
            if hitBase or hitPipe:
                status = Status.inGameOver
                bird.die()

        if status == Status.inMenu:
            drawer.drawInMenu(sprites.background, sprites.message, base, bird,
                              tick)
        elif status == Status.inGame:
            drawer.drawInGame(sprites.background, base, bird, pipes, score,
                              tick)
        else:
            drawer.drawInGameOver(sprites.background, sprites.gameOver, base,
                                  bird, pipes, score, tick)

        if tick < FPS:
            tick += 1
        else:
            tick = 0
Пример #10
0
 def __init__(self):
     self.game_is_on = False
     self.l_score = Score((-100, 250))
     self.r_score = Score((100, 250))
     self.l_paddle = Paddle((-370, 0))
     self.r_paddle = Paddle((370, 0))
     self.screen = Screen()
     self.ball = Ball()
     self.setup_screen()
Пример #11
0
def enter():
    gfw.world.init([
        'bg', 'enemy', 'boss', 'bullet', 'player', 'boss_bullet', 'effect',
        'ui', 'item'
    ])
    global player, charnum
    player = Player()
    Player.player_type = charnum
    gfw.world.add(gfw.layer.player, player)

    global dis_score, score
    dis_score = Score(canvas_width - 20, canvas_height - 50)
    gfw.world.add(gfw.layer.ui, dis_score)
    score = Score(canvas_width - 20, canvas_height - 100)
    gfw.world.add(gfw.layer.ui, score)

    global font
    font = gfw.font.load(gobj.RES_DIR + '/BM.ttf', 40)

    life_gauge.load()

    bg = VertScrollBackground('/map_01.png')
    bg.speed = 100
    gfw.world.add(gfw.layer.bg, bg)

    global power_item, dual_item
    power_item = gfw.image.load(gobj.RES_DIR + '/powershot.png')
    dual_item = gfw.image.load(gobj.RES_DIR + '/dualshot.png')

    global music_bg, music_bg2, wav_mon_die, player_voice, player_hit_wav, wav_boss_dead, wav_siren, get_money, get_item
    music_bg = load_music(gobj.RES_DIR + '/bg_music.mp3')
    music_bg2 = load_music(gobj.RES_DIR + '/boss_stage_bg.mp3')
    wav_mon_die = load_wav(gobj.RES_DIR + '/enemy_die.wav')
    player_voice = load_wav(gobj.RES_DIR + '/go.wav')
    player_hit_wav = load_wav(gobj.RES_DIR + '/hit.wav')
    wav_siren = load_wav(gobj.RES_DIR + '/siren.wav')
    wav_boss_dead = load_wav(gobj.RES_DIR + '/boss_dead.wav')
    get_money = load_wav(gobj.RES_DIR + '/get_coin.wav')
    get_item = load_wav(gobj.RES_DIR + '/get_item.wav')

    music_bg.repeat_play()
    player_voice.play()

    global state
    state = START_GAME
    enemy_gen.reset()

    global boss_ox, boss_ap
    boss_ox, boss_ap = 0, 1
    boss.Boss().LASER_INTERVAL = 0.5

    global time, boss_die
    time = 0
    boss_die = False
    highscore.load()

    Gameover_state.num = charnum
Пример #12
0
 def __init__(self, filename, text, real_score=0):
     self.text = text
     self.text_list = self.text.replace('\n', " ").split()
     self.tags = nl.pos_tag(self.text_list)
     self.raw_score = Score()
     self.normalized_score = Score()
     self.real_score = real_score
     self.filename = filename
     self.grader_score = 0.0
     self.classification = 1
     self.classification_penalty = 0
Пример #13
0
 def count_flush(self):
     flush = []
     flush_suit = self.cards[0].suit
     # Five card flush if the upcard also matches
     if all(card.suit == flush_suit for card in self.all_cards()):
         flush = [Score(self.all_cards(), 5)]
     # Four card flushes can't include the upcard and can't be scored in a crib
     elif all(card.suit == flush_suit
              for card in self.cards) and not self.is_crib:
         flush = [Score(self.cards, 4)]
     return flush
Пример #14
0
    def test_valid(self):
        self.assertTrue(Score("6-4 7-6(5)").valid())
        self.assertTrue(Score("6-4 5-7 7-6(8)").valid())
        self.assertTrue(Score("6-4 3-6 2-6 7-6(12) 22-20").valid())

        self.assertFalse(Score("6-4 3-6 2-6 7-6(12) 2-6 22-20").valid())
        self.assertFalse(Score("6-4 6-7(4) 3-6 6-4").valid())
        self.assertFalse(Score("6-4 6-7(4) 3-6").valid())
        self.assertFalse(Score("6-4 6-7(3)").valid())
        self.assertFalse(Score("6-4").valid())
        self.assertFalse(Score("7-5 3-6 10-4").valid())
        self.assertFalse(Score("").valid())
Пример #15
0
 def count_flush(self):
     flush = []
     flush_suit = self.cards[0].suit
     # If any card is a different suit than the first one, there can't be a flush
     for card in self.cards:
         if card.suit != flush_suit:
             return flush
     # Five card flush if the upcard also matches
     if self.upcard.suit == flush_suit:
         flush = [Score(self.allCards(), 5)]
     # Four card flushes can't be scored in a crib
     if not self.is_crib:
         flush = [Score(self.cards, 4)]
     return flush
Пример #16
0
def init():
    #Initialize all the constants:
    screen = constants.initialize()


    #Making the FPS clock:
    clock = pygame.time.Clock()
    FPS = 60

    #Creating paddle 1 score:
    paddle1Score = Score(screen)
    paddle1Score.x = 100


    #Creating paddle 2 score:
    paddle2Score = Score(screen)
    paddle2Score.color = constants.colors["RED"]


    #Making 2 paddles:
    paddle1 = Paddle()
    paddle1.x = 10
    paddle1.color = constants.colors["BLUE"]

    paddle2 = Paddle()
    paddle2.x = 780
    paddle2.color = constants.colors["RED"]


    # Making the ball:
    ball = Ball()
    ball.dx = ball.speed
    ball.dy = ball.speed    
    #The ball starts at the center:           
    ball.x = constants.cx
    ball.y = constants.cy
    #The ball's intital color is blue
    ball.color = constants.colors["PURPLE"]

    #Creating the title screen's text:
    title_text = Text(screen)
    title_text.text = "Welcome to Saabit Pong Game. Difficulty keys: Easy: 1, Medium: 2, Hard: 3"

    #Creating the end game screen's text
    endScreen_text = Text(screen)
    endScreen_text.text = "Game Over. Press 'P' to play again"


    return ScreenState(screen, title_text, endScreen_text, paddle1, paddle2, ball, paddle1Score, paddle2Score, clock, FPS)
Пример #17
0
    def scour(self, soup):
        """Pulls out information from a single page soup."""

        title_bin = soup.find("title").text
        title = title_bin[:title_bin.find(" |")]

        reason_bin = soup.find("input", attrs={"name": "reason"})
        category_bin = soup.find("input", attrs={"name": "category"})

        if reason_bin and category_bin:
            reason = reason_bin["value"]
            category = category_bin["value"]
            tagline = category + " firm, selling due to " + reason
        elif reason_bin:
            tagline = "Firm selling due to " + reason_bin["value"]
        elif category_bin:
            category = category_bin["value"]
            tagline = category + " firm, selling for undisclosed reason"
        else:
            tagline = "(No Tagline)"

        price_bin = soup.find("input", attrs={"name": "listing_price"})
        price = "$" + price_bin["value"]

        de_tag = "seller_discretionary_earnings"
        de_bin = soup.find("input", attrs={"name": de_tag})
        discretionary_earnings = "$" + de_bin["value"]

        loc_bin = soup.find("input", attrs={"name": "Location"})
        location = loc_bin["value"]
        if location[0] == ",":
            location = location[2:]

        tags = soup.find("meta", attrs={"name": "description"})
        description = tags["content"]

        contact_bin = soup.find("input", attrs={"name": "to_email"})
        contact = contact_bin["value"]

        if self.positive_inputs is None and self.negative_inputs is None:
            score = Score(" ".join([title, tagline, description]))
        else:
            score = Score(" ".join([title, tagline, description]), \
                positive_inputs=self.positive_inputs, \
                negative_inputs=self.negative_inputs)

        return [title, tagline, price, discretionary_earnings, \
            location, description, contact, score]
Пример #18
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("Alien Invasion")
    play_button = Button(ai_settings, screen, "Play")
    ship = Ship(ai_settings, screen)
    stats = GameStats(ai_settings)
    score = Score(ai_settings, screen, stats)
    stats.score = 0
    aliens = Group()
    bullets = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    screen.fill(ai_settings.bg_color)
    ship.blitme()
    pygame.display.update()

    while True:
        gf.check_events(ai_settings, screen, stats, score, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, score, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
            for bullet in bullets.copy():
                if bullet.rect.bottom <= 0:
                    bullet.remove(bullets)
                    print(len(bullets))
        gf.update_screen(ai_settings, screen, stats, score, ship, aliens,
                         bullets, play_button)
Пример #19
0
    def __init__(self, cellsize, off_setX, off_setYtop, off_setYbottom,
                 rowsbycols, row, column):
        self.cellsize = cellsize
        self.off_setX = off_setX
        self.off_setYtop = off_setYtop
        self.off_setYbottom = off_setYbottom
        self.rowsbycols = rowsbycols
        self.cell_off_set = 10

        self.player_img = pyglet.image.load('images/player.png')
        self.player = self.player_img.get_texture()

        # columns for left to right
        # rows from bottom to top
        self.column = column
        self.row = row
        self.playerXcordinate = (self.off_setX +
                                 self.cell_off_set / 2) + (self.cellsize *
                                                           (self.column - 1))
        self.playerYcordinate = (self.off_setYbottom +
                                 self.cell_off_set / 2) + (self.cellsize *
                                                           (self.row - 1))

        # length for both width and height
        self.player_length = self.cellsize - self.cell_off_set

        # player moving direction will be updated in onkeypress function
        self.player_direction = None

        # make game score
        self.score = Score(properties.score_initial_value)
Пример #20
0
class SoldierClient(Client):
    # 预先实例 score 对象,防止重复建立,节省资源
    score = Score()

    def deal(self):
        # 告诉服务端新的一轮可以开始
        self.report(b'start')

        # 图片接收
        person_image = b''
        while True:
            recv = self.s.recv(1024)
            if recv.endswith(b'image_stream_end'):
                recv = recv.replace(b'image_stream_end', b'')
                person_image += recv
                break
            person_image += recv

        # 获取分数,并发送给服务端
        score_text = self.score.score(person_image)
        self.report(bytes('score: {0}'.format(score_text).encode('utf-8')))

    def start(self):
        while True:
            recv_done = self.s.recv(1024)

            # 只有在接收到服务器返回的 done 字段才会开始
            if recv_done == b'done':
                self.deal()
Пример #21
0
    def __init__(self):
        super(MenuManager, self).__init__()

        self.contentsDoc = None
        self.assistantProcess = QtCore.QProcess()
        self.helpRootUrl = ''
        self.docDir = QtCore.QDir()
        self.imgDir = QtCore.QDir()

        self.info = {}
        self.window = None

        self.ticker = None
        self.tickerInAnim = None
        self.upButton = None
        self.downButton = None
        self.helpEngine = None
        self.score = Score()
        self.currentMenu = "[no menu visible]"
        self.currentCategory = "[no category visible]"
        self.currentMenuButtons = "[no menu buttons visible]"
        self.currentInfo = "[no info visible]"
        self.currentMenuCode = -1
        self.readXmlDocument()
        self.initHelpEngine()
Пример #22
0
 def get_solution(self, rides_list, rows, columns, vehicles, rides, bonus,
                  steps, args):
     cars = [Car() for _ in range(vehicles)]
     score = Score()
     rides_instance_list = [
         Ride(rid, *data) for rid, data in enumerate(rides_list)
     ]
     rides_earliest_departure = sorted(rides_instance_list,
                                       key=lambda ride: ride.step_min)
     rides_earliest_departure = tqdm(
         rides_earliest_departure
     ) if args.progress else rides_earliest_departure
     for r in rides_earliest_departure:
         candidates = [c for c in cars if c.can_finish_in_time(r, steps)]
         cars_with_bonus = [c for c in candidates if c.can_start_on_time(r)]
         if cars_with_bonus:
             best_car = min(cars_with_bonus, key=lambda c: c.wait_time(r))
             score.bonus_score += bonus
             score.raw_score += r.distance()
             score.wait_time += best_car.wait_time(r)
             score.assigned += 1
             best_car.assign(r)
         elif candidates:
             best_car = min(candidates,
                            key=lambda c: c.distance_to_ride_start(r))
             score.raw_score += r.distance()
             score.assigned += 1
             best_car.assign(r)
         else:
             score.unassigned += 1
     rides_solution = [c.assigned_rides for c in cars]
     return rides_solution, score
Пример #23
0
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("My Pong Game")
        self.screen = pygame.display.set_mode((800, 600))
        self.running = True
        self.clock = pygame.time.Clock()
        self.walls = [Wall((10, 10), 780, 10),
                      Wall((10, 580), 780,
                           10)]  # Position and dimensions of walls
        self.background = pygame.Surface((800, 600))
        self.background.fill(pygame.Color("#000000"))
        self.ball = Ball((400, 300))
        self.font = pygame.font.Font(None, 50)

        control_scheme_1 = ControlScheme()
        control_scheme_1.up = pygame.K_w
        control_scheme_1.down = pygame.K_s

        control_scheme_2 = ControlScheme()
        control_scheme_2.up = pygame.K_UP
        control_scheme_2.down = pygame.K_DOWN

        self.bats = [
            Bat((10, 200), 10, 100, control_scheme_1),
            Bat((780, 200), 10, 100, control_scheme_2)
        ]  # Position and dimensions of paddles, their respective control schemes
        self.score = Score(self.font)
Пример #24
0
def game():
    pygame.init()       #Initialize Pygame
    pygame.mixer.pre_init(44100, -16, 2, 2048)  # Reduce Lagging for the Music
    pygame.mixer.init()     #Initialize Mixer for Background Music
    pygame.mixer.music.load('bgm.wav')      #Load the BGM File
    pygame.mixer.music.play(-1)     #Play the BGM Infinitely
    screen=pygame.display.set_mode((500,650))       #Set the Pygame Window
    pygame.display.set_caption("STARHEAD EXTERMINATOR")     #Set the Window Caption

    #Call All the Classes
    txt = "DONT SHOOT THE GREEN ONE"
    button = Button(screen,txt)
    stats = Stats()
    gun = Gun(screen)
    enemy = Enemy(screen,stats)
    host = Hostage(screen,stats)
    score = Score(screen, stats)
    enemies = Group()
    hostage = Group()
    #Start the Game Loop
    while True:
        gf.firstscreen(screen,button,stats,gun,enemies,hostage,score)      #First Display of the Game 
        if stats.game_active:       #Start when the Player Click the Button
            gf.gametrue(screen,stats,gun,enemies,hostage,score)     #Update and Behaviour of Objects in the Game
        gf.update_screen(screen,gun,enemies,hostage,button,stats)       #Update the Screen and Flip
Пример #25
0
def run():
    pygame.init()

    # load the game settings
    settings = Settings()

    # create the screen and add a title
    screen = pygame.display.set_mode(settings.screen_dimension)
    pygame.display.set_caption('BreakOut - Python')

    # create the game elements
    bar = Bar(screen, settings)
    chances = Chances(screen, settings)
    score = Score(screen, settings)
    ball = Ball(screen, bar, settings, chances, score)
    btn_start = Button(screen, 'press space to start')
    btn_game_over = Button(screen, 'Game Over')

    object_group = []
    function.dispose_objects(screen, object_group, score)

    while True:
        function.check_events(bar, settings, chances, score)
        function.update_screen(bar, screen, ball, settings, object_group,
                               btn_start, btn_game_over, chances, score)
Пример #26
0
def run_game():
    #init游戏并创建一个窗口对象
    pygame.init()
    ai_settings=Settings()#创建Settings类的实例
    screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("地球保卫战 v1.0")

    #创建实例
    sscol=Group()
    stone=Stone(screen)
    stats=GameStats(ai_settings)
    bullets=Group()
    ship=Ship(ai_settings,screen)
    sscol.add(ship)
    aliens=Group()
    button=Button(ai_settings,screen,"Play")
    score=Score(ai_settings,screen,stats)

    
    while True:

        #帧数
        pygame.time.Clock().tick(120)
        #监视键盘和鼠标事件
        func.check_events(ai_settings,screen,ship,aliens,bullets,button,stats,score)

        #决定游戏是否开始
        if stats.game_status:
            ship.update()
            func.release_bullet(ai_settings,bullets,screen,aliens,stats,score)
            func.update_alien(ai_settings,screen,aliens,ship,stats,bullets,score,stone,sscol)
        
        
            #每次循环都重绘屏幕
        func.update_screen(ai_settings,screen,ship,bullets,aliens,stats,button,score,stone)
Пример #27
0
    def __init__(self):
        # pygame.init is used to deploy the background
        pygame.init()
        # self.screen will display a window with 1200 by 700 screen size
        self.settings = Settings(self)
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        self.screen_rect = self.screen.get_rect()
        # bg_colour will give a background colour
        self.bg_colour = self.settings.bg_colour
        # self.captions will create a title at the top of the window
        pygame.display.set_caption('Blue Sky')

        self.fish = Fish(self)
        self.seaweeds = pygame.sprite.Group()
        self.worms = pygame.sprite.Group()
        self.hook = Hook(self)
        self.line = Line(self)

        self.stats = GameStats(self)

        self._create_fleet()
        self._create_worms()

        self.clock = pygame.time.Clock()
        self.counter = 0
        pygame.time.set_timer(pygame.USEREVENT, 1000)

        self.play = Button(self, 'Play')
        self.sb = Score(self)
Пример #28
0
    def __init__(self, data):
        self._data = data
        self._score = Score()

        self._category = None
        self._iter_category = None
        self._word = Word()
Пример #29
0
 def __init__(self, WIDTH, HEIGHT):
     self.WIDTH = WIDTH
     self.HEIGHT = HEIGHT
     self.black_wins = False
     self.white_wins = False
     self.tie = False
     self.scores = Score('scores.txt')
Пример #30
0
def train():
    feature_mapper = FeatureMapper()
    score = Score()
    segmentation = Segmentation()

    feature_mapper.load_weights("./immutable_weights/feature_mapper")
    # score.load_weights("./weights/score")
    # segmentation.load_weights("./weights/segmentation")

    opt = Adam(learning_rate=5e-5)
    with open("../data/data_classification_train.json") as json_file:
        data = json.load(json_file)
    data_index = 0
    while str(data_index) in data:
        img = get_img(
            "../pictures/pictures_classification_train/{}.png".format(
                data_index))
        true_masks = get_true_mask(data[str(data_index)])

        features = feature_mapper(img)

        def get_loss():
            segmentation_prediction = segmentation(features)
            score_prediction = score(features)
            show_evaluation(segmentation_prediction, true_masks, data_index)
            return calculate_loss(segmentation_prediction, score_prediction,
                                  true_masks)

        opt.minimize(get_loss,
                     [score.trainable_weights, segmentation.trainable_weights])

        if (data_index % 100 == 99):
            score.save_weights("./weights/score")
            segmentation.save_weights("./weights/segmentation")
        data_index += 1