Ejemplo n.º 1
0
	def __init__(self, players=[IPlayer()]*4, playing_to=500):
		self.players = players
		self.playing_to = playing_to
		self.score = Score()  # Players 0 and 2 form team 0, players 1 and 3 are team 1
		self.hands = {}
		self.dealer = 0
		self.bids = Bids()
Ejemplo n.º 2
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')
Ejemplo n.º 3
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('Goodle Jump')
    graffiti = Graffiti(screen, ai_settings)
    # 创建一个保存所有踏板的编组
    pedals = Group()
    gf.update_pedal(pedals, ai_settings, screen)
    # 创建一个结束状态
    stats = GameStats()
    # 创建一个结束界面
    gameOver = GameOver(screen, "Game Over")
    # 创建一个得分
    score = Score(screen, stats, ai_settings)
    # 开始游戏主循环
    while True:
        # 监视键盘和鼠标事件
        gf.check_events(graffiti)
        if stats.game_active:
            gf.update_pedals(pedals, ai_settings, screen)
            graffiti.update(ai_settings, pedals, stats)
            score.prep_scroe()
        # 更新屏幕
        gf.update_screen(ai_settings, screen, graffiti, pedals, stats,
                         gameOver, score)
Ejemplo n.º 4
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"))
def test_list_to_file():
    # After writing to the file, test to make sure
    # score_flag is False
    sc = Score('test.txt')
    assert sc.score_flag
    sc.list_to_file()
    assert not sc.score_flag
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
    def __init__(self, screen, settings, id, turn=False):
        # Initiate score to 0
        self.score = Score(screen, settings, id + 1)

        self.settings = settings
        self.id = id

        # Used for scoring
        self.static_list = [[215, 0], [385, 0], [565, 0], [740, 0]]
        self.moving_list = [[125, 0], [300, 0], [475, 0], [650, 0], [830, 0]]

        # Convert to negative so as to make checking easy for player 2
        if id == 1:
            self.static_list = list(map(lambda x: [-x[0], 0],
                                        self.static_list))
            self.moving_list = list(map(lambda x: [-x[0], 0],
                                        self.moving_list))

        # Make a sheep object
        self.sheep = Sheep(screen, settings, id + 1)

        # Set if turn is true or false
        self.turn = turn

        self.alive = True

        # True if player has currently completed the level
        self.level_complete = False

        self.consider_time = True
Ejemplo n.º 8
0
 def new_game(cls, player):
     """Creates and returns a new game"""
     # 'player' is actually a user.key value for the
     # relationship (KeyProperty) to the user entity
     # pacific=timezone('US/Pacific')
     now = datetime.datetime.now()
     game = Game(player=player)
     # print ('\nNew game object is :' + str(game) + '\n')
     # set up the score record
     game_key = game.put()
     score = Score(
         game_key=game_key,
         player=player,
         start_date=now,
         end_date=now,
         move_count=0,
         parent=game.key)
     score_key = score.put()
     game.score_key = score_key
     # set up the move records
     move_record = (Move(game_key=game_key))
     move_record_key = move_record.put()
     # print move_record_key
     move_record_keys = []
     move_record_keys.append(move_record_key)
     game.move_record_keys = move_record_keys
     # set the game number
     game.game_number = game.get_max_game_number(player) + 1
     game.put()
     return game
Ejemplo n.º 9
0
class TestScore(unittest.TestCase):
    def setUp(self):
        self.score = Score()

    def test_initial_score(self):
        self.assertEqual(0, self.score.player1)
        self.assertEqual(0, self.score.player2)

    def test_inc_play2(self):
        ball = Ball()
        ball.position['x'] = -1
        self.score.check_score(ball)
        self.assertEqual(0, self.score.player1)
        self.assertEqual(1, self.score.player2)
        self.checkFinalPosition(ball)

    def checkFinalPosition(self, ball):
        final_position = constants.SCREEN_WIDTH / 2 - ball.dimension['width'] / 2
        self.assertEqual(final_position, ball.position['x'])

    def test_inc_play1(self):
        ball = Ball()
        ball.position['x'] = constants.SCREEN_WIDTH + 1
        self.score.check_score(ball)
        self.assertEqual(1, self.score.player1)
        self.assertEqual(0, self.score.player2)
        self.checkFinalPosition(ball)
Ejemplo n.º 10
0
    def __init__(self, screen, filename, data, continue_num=0):
        """screenは描画対象。filenameはステージ内容を記述したテキストファイル"""
        self.screen = screen  # 描画対象
        self.speed = 1  # 背景の移動速度
        self.continue_num = continue_num
        self.data = data

        CpuMachine.killed_count = self.data["kill"]
        Boss.killed_count = 0
        PlayerMachine.killed_count = self.data["death"]

        self.initGroup()  # グループを初期化する

        self.readStage(filename)  # ステージ情報を読み込む

        self.creatRange()  #範囲を設定する
        self.creatRange2()  #

        font = pygame.font.Font("font/freesansbold.ttf", 60)
        menu_font = pygame.font.Font("font/freesansbold.ttf", 25)
        self.pause_text = font.render("PAUSE", True, (255, 255, 255))
        self.retire_text = menu_font.render("- Retire : Q", True,
                                            (255, 255, 255))
        self.restart_text = menu_font.render("- Restart : Space", True,
                                             (255, 255, 255))

        self.score = Score(10, 10)
        self.money = Money(10, 30)
        self.clock = pygame.time.Clock()  # 時間管理用
        R_time.restart()

        self.process = self.stage_process
        self.draw = self.stage_draw

        self.player_init()
Ejemplo n.º 11
0
def evaluate_engine_scores():
    concat_cross_validation_folds()
    ref_scores = {}
    avg_scores = {}

    print 'Average scores:'
    for dataset in EVAL_DATASETS:
        print '\t {0} dataset:'.format(dataset)
        ref_scores[dataset] = {}
        avg_scores[dataset] = {}
        path = os.path.join(EVAL_IN_DIR, dataset)
        s = Score(path)
        test_list = [
            "{0}-{1}.txt".format(path, engine) for engine in EVAL_ENGINES
        ]
        ref_file = path + "-ref.txt"

        (file1, file2, line_counts) = s.BatchFiles(test_list, [ref_file])
        output_file = s.ComputeMeteorScores(file1, file2, n_refs=4)
        results = s.UnbatchResults(output_file, test_list, [ref_file],
                                   line_counts)
        for i, r in enumerate(results):
            len(r) == 1 or Die("Multiple results for only 1 reference")
            engine_name = EVAL_ENGINES[i]
            ref_scores[dataset][engine_name] = r[0]
            avg_scores[dataset][engine_name] = float(sum(r[0])) / len(r[0])
            print '\t\t {0} engine: {1}'.format(
                engine_name, avg_scores[dataset][engine_name])

    out_dir = os.path.join(score.OUTPUT_DIR, "results")
    pickle.dump(ref_scores, open(os.path.join(out_dir, 'ref_scores.pkl'), 'w'))
    pickle.dump(avg_scores, open(os.path.join(out_dir, 'avg_scores.pkl'), 'w'))
    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']))
Ejemplo n.º 14
0
    def __init__(self, screen):
        """ 初始化 """
        self._screen = screen  # 屏幕画面
        self._gameState = GameState.start  # 游戏状态 0:开始画面; 1:游戏中; 2:游戏结束
        self._frameCount = 0  # 每个游戏状态的帧数计数
        self._score = Score(self)  # 分数系统

        # 游戏元素
        self._startScene = StartScene()
        self._gameoverScene = GameoverScene(self)
        self._dinosaur = Dinosaur(self)
        self._cactusGroup = pygame.sprite.RenderPlain()
        self._birdGroup = pygame.sprite.RenderPlain()
        self._terrian = Terrian(self)
        self._cloudGroup = pygame.sprite.RenderPlain()
        self._moon = Moon(self)
        self._starGroup = pygame.sprite.RenderPlain()

        # 控制难度的变量
        self._lastEnemyFrameCount = 0  # 上一次出现敌人的帧数计数
        self._curEnemeyProbability = Settings.enemyInitProbability  # x,当前每帧敌人出现的概率为1/x
        self._curEnemyMinFrameInterval = Settings.enemyInitMinFrameInterval  # 当前敌人最小帧数间隔
        self._curTerrianSpeed = Settings.terrianInitSpeed  # 当前地形移动速度

        # 控制环境的变量
        self._lastCloudFrameCount = Settings.cloudFrameInterval  # 上一次出现云的帧数计数
        self._isDay = True  # 是否白天
        self._dayNightFrame = Settings.dayNightChangeFrame  # 自从白天/黑夜开始的帧数,初始值不为0,因为开始无需昼夜交替
Ejemplo n.º 15
0
    def __init__(self, data):
        self._data = data
        self._score = Score()

        self._category = None
        self._iter_category = None
        self._word = Word()
 def __init__(self, name=None, screen_width=500, screen_height=500):
     self.name = name
     self.screen_width = screen_width
     self.screen_height = screen_height
     self.screen = pygame.display.set_mode(
         [self.screen_width, self.screen_height])
     pygame.init()
     self.player = Player(self.screen_width, self.screen_height)
     self.clock = pygame.time.Clock()
     self.score = Score()
     # - Hold enemies, clouds in Sprite Groups
     # - All sprites group used for rendering
     self.enemy = pygame.sprite.Group()
     self.cloud = pygame.sprite.Group()
     self.all_sprites = pygame.sprite.Group()
     self.all_sprites.add(self.player)
     self.all_sprites.add(self.score)
     #defining new user event for the game - enemy generation
     self.game_event = pygame.USEREVENT + 1
     # setting the timer after which this event triggers
     pygame.time.set_timer(self.game_event, 250)
     # event for cloud creation
     self.cloud_event = pygame.USEREVENT + 2
     pygame.time.set_timer(self.cloud_event, 1000)
     self.counter = 0
     self.color_palette = [[135, 206, 250], [135, 200,
                                             200], [135, 200, 100],
                           [125, 200, 100], [100, 100, 200]]
     self.high_score = HighScore()
Ejemplo n.º 17
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
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
 def model_score(self):
     print("\n#5 模型评估")
     predict_y = self.model_.predict(self.test_data_[X_])
     matrix_ = confusion_matrix(y_pred=predict_y, y_true=self.test_data_[y_])
     print("混淆矩阵:\n", matrix_)
     print("模型评估:\n", classification_report(y_true=self.test_data_[y_], y_pred=predict_y))
     Score.print_confusion_matrix(confusion_matrix=matrix_, y_true=self.test_data_[y_], y_score=predict_y, output_to_java=True,model_name=self.model)
Ejemplo n.º 20
0
def run_game():
    pygame.init()
    settings = game_settings.Settings()
    screen = pygame.display.set_mode(settings.resolution)
    snake = Snake(screen, settings)
    pygame.display.set_caption("Snake")
    my_tail = []
    x, y = gf.generate_randoms()
    food = GroupSingle(Food(snake, screen, x, y))
    tails = OrderedUpdates()
    gf.initialise_snake(snake, screen, my_tail, tails, settings)
    button = Play_button(screen, settings, "Play")
    end_game_screen = EndGameScreen(screen, settings, "Game Over")
    score = Score(screen, settings)
    clock = pygame.time.Clock()
    gametime = GTime(clock)

    while True:
        screen.fill(settings.bg_color)
        score.draw_me()
        gf.check_events(snake, food, screen, my_tail, tails, settings, button,
                        gf, end_game_screen, score, gametime)
        if settings.game_active == False:
            if gf.lose_condition_met(snake, settings, tails,
                                     gametime) == False:
                button.draw_me()
        if settings.game_active == True:
            snake.update()
            tails.update()
            snake.draw_me()
            food.update()
            clock.tick(10)
            gametime.update()
            print(gametime.time)
        pygame.display.flip()
Ejemplo n.º 21
0
    def model_verify(self):
        print("\n#6 模型验证(按月份划分验证集)")

        begin_date = self.verify_data_.iloc[0, self.index_dict_['date']]
        end_date = self.verify_data_.iloc[-1, self.index_dict_['date']]
        print("--- 数据时间跨度[%s, %s):" % (begin_date, end_date))
        print(" features:", self.feature_)
        print(" params:")
        print(pd.Series(self.model_.get_params()))

        while begin_date < end_date:
            cur_date = Traditional_Train.add_one_mounth("%Y-%m-%d", begin_date)
            
            cur_data = self.verify_data_[(self.verify_data_.iloc[:, self.index_dict_['date']] >= begin_date) & \
                                        (self.verify_data_.iloc[:, self.index_dict_['date']] < cur_date)]
            cur_data_y = cur_data.iloc[:, self.index_dict_['failure']]
            if len(cur_data_y.value_counts()) < 2:
                break
            cur_data_X = cur_data.iloc[:, self.index_dict_['data']:]
            cur_data_X = pd.DataFrame(self.scale_.transform(cur_data_X))  # 对当前测试数据进行归一化
            cur_data_X = cur_data_X.iloc[:, self.feature_]  # 对当前测试数据提取特征

            predict_y = self.model_.predict(cur_data_X)  # 使用当前模型进行预测
            matrix = confusion_matrix(cur_data_y, predict_y)

            print("\n--- 当前测试结果[%s, %s):" % (begin_date, cur_date))
            Score.print_confusion_matrix(confusion_matrix=matrix, y_true=cur_data_y, y_score=predict_y, output_to_java=False,model_name=self.model)
            begin_date = cur_date
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
 def __init__(self, pos_x, pos_y, structure_lab, list_macgyver):
     self.position_perso = (pos_x, pos_y)
     self.pos_x = pos_x
     self.pos_y = pos_y
     self.labyrinth = structure_lab
     self.score = Score()
     self.list_macgyver = list_macgyver
Ejemplo n.º 24
0
def main():
    pygame.init()
    screen = Screen(1200, 800, (255, 255, 255))
    screen.display()
    jumpman = Jumpman(screen, 50, 200)
    pygame.display.update()
    block = Block(screen, 50, 50)
    jumpman_x = 50
    jumpman_y = 200
    score = Score(0, screen)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                if jumpman_y < 800 - jumpman.height():
                    jumpman_y = jumpman_y + 10
            if event.key == pygame.K_UP:
                if jumpman_y > 0:
                    jumpman_y = jumpman_y - 10

        screen.screen.fill((255, 255, 255))
        score.render()
        load_jumpman(screen, jumpman, jumpman_x, jumpman_y)
        handle_block(screen, block, score)
        pygame.display.update()
Ejemplo n.º 25
0
class MainScreen(Surface):
    def __init__(self, main_screen: Surface, color='black'):
        super().__init__(main_screen.get_size())
        self.main_screen = main_screen
        self.background_color = color
        self.score = Score(self, color=score_color, alpha=score_alpha)
        self.block1 = Block(self,
                            player=1,
                            color=block1_color,
                            size=block_size,
                            margin=margin,
                            speed=block_speed)
        self.block2 = Block(self,
                            player=2,
                            color=block2_color,
                            size=block_size,
                            margin=margin,
                            speed=block_speed)
        self.ball = Ball(self,
                         color=ball_color,
                         radius=ball_radius,
                         speed=ball_speed)

    def redraw(self):
        self.fill(self.background_color)
        self.score.redraw()
        self.block1.redraw()
        self.block2.redraw()
        self.ball.redraw(self.block1, self.block2)

        self.main_screen.blit(self, (0, 0))
        update_screen()
Ejemplo n.º 26
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
Ejemplo n.º 27
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)))
Ejemplo n.º 28
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")

    hscore = Score()
    stats = GameStats(ai_settings, hscore.score_get())
    sb = Scoreboard(ai_settings, screen, stats)

    bg_color = (230, 230, 230)
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

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

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

    #alien = Alien(ai_settings, screen)

    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        bullets.update()
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, hscore)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Ejemplo n.º 29
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))
Ejemplo n.º 30
0
def renderHeader(score: Score, helpText: str):
    batch = pyglet.graphics.Batch()
    pyglet.text.Label('Score: ' + str(score.getScore()),
                      font_name='Times New Roman',
                      font_size=28,
                      x=10,
                      y=WINDOW_HEIGHT + HEADER_HEIGHT // 2,
                      anchor_y='center',
                      batch=batch)
    pyglet.text.Label(helpText,
                      font_name='Times New Roman',
                      font_size=12,
                      x=WINDOW_WIDTH // 2,
                      y=WINDOW_HEIGHT + HEADER_HEIGHT // 2,
                      anchor_x='center',
                      anchor_y='center',
                      align='center',
                      multiline=True,
                      width=WINDOW_WIDTH,
                      batch=batch)
    pyglet.text.Label('Max: ' + str(score.getHighScore()),
                      font_name='Times New Roman',
                      font_size=28,
                      x=WINDOW_WIDTH - 10,
                      y=WINDOW_HEIGHT + HEADER_HEIGHT // 2,
                      anchor_x='right',
                      anchor_y='center',
                      batch=batch)
    batch.draw()
Ejemplo n.º 31
0
 def mark(self, score: Score) -> None:
     '''
     Mark the pixel for the target score
     '''
     losing = score.losing() if score.losing() < self.max_score else self.max_score
     winning = score.winning() if score.winning() < self.max_score else self.max_score
     self.pixels[losing, winning] = FOUND
Ejemplo n.º 32
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()
Ejemplo n.º 33
0
 def testgetTimeScore(self):
   'Test if getTimeScore will return the correct time score for 3 instances'
   get1 = Score()
   finish1 = True
   time1 = 1000
   self.assertEqual(get1.getTimeScore(time1,finish1),0)
   get2 = Score()
   time2 = 290
   self.failIf(get2.getTimeScore(time2,finish1) == 0)
Ejemplo n.º 34
0
def get_score_for_patient(p):
    total = 0
    count = 0
    for m in Medicine.objects.filter(treatments__patient=p).distinct():
        r = RecurringTreatment.objects.get(patient = p, medicine = m)
        pt = PillTaken.objects.filter(patient = p, medicine = m)
        s = Score()
        total = total + s.translate(r, pt)
        count = count + 1
    total = ceil(total / count)if count > 0 else 0
    return total
Ejemplo n.º 35
0
def main():
    WINDOW_WIDTH = 640
    WINDOW_HEIGHT = 480
    bulletArray = []
    enemyArray = []

    pygame.init()
    screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption('CARNAPITON')
    pygame.mouse.set_visible(1)
    clock = pygame.time.Clock()
    clock.tick(60)

    grass = pygame.image.load("images/FONDO2.png")

    s = Score()
    p = Player(WINDOW_WIDTH, WINDOW_HEIGHT)
    ec = Controller(s)

    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                return
            p.manageEvent(event, bulletArray)

        screen.blit(grass, (0, 0))

        s.draw(screen)
        p.update(clock.get_time())

        for bullet in bulletArray:
            if bullet.isDestroyed:
                bulletArray.remove(bullet)
                continue
            bullet.update()

        for bullet in bulletArray:
            bullet.draw(screen)

        for e in enemyArray:
            e.update(p, clock.get_time())

        for e in enemyArray:
            e.draw(screen)

        ec.execute(WINDOW_WIDTH, WINDOW_HEIGHT, enemyArray, bulletArray, clock.get_time())

        p.draw(screen)

        pygame.display.flip()
Ejemplo n.º 36
0
    def _setup_score(self):
        """
        Sets up the score object

        """
        from score import Score
        self.score = Score(self.background)
Ejemplo n.º 37
0
    def record_score(self, aggregate_data):
        score = Score.query().filter(Score.user == self.user).get()
        if score:
            score.score += aggregate_data[0]
            score.num_correct += aggregate_data[1]
            score.num_incorrect += aggregate_data[2]
            score.clues_used += aggregate_data[3]
        else:
            score = Score(user=self.user,
                          score=aggregate_data[0],
                          num_correct=aggregate_data[1],
                          num_incorrect=aggregate_data[2],
                          clues_used=aggregate_data[3])

        score.put()
        return score
Ejemplo n.º 38
0
    def finish_game(self):
        """Finish the game - user successfully finished the game."""
        self.finished = True
        self.put()

        # Update user score
        user = self.user.get()
        user.finished_game(self.score)

        # Add the game to the score 'board'
        score = Score(user=self.user,
                      date=date.today(),
                      attempts_done=self.attempts_done,
                      card_cnt=self.card_cnt,
                      score=self.score)
        score.put()
Ejemplo n.º 39
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.qmlRoot = None
        self.declarativeEngine = 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()
Ejemplo n.º 40
0
 def __init__(self, **kwargs):
     """Game class initializer. Initializes the temporary grid.
     """
     super(Game, self).__init__()
     self.grid = [[None for i in range(GRID_SIZE)] for j in range(GRID_SIZE)]
     self.letter_grid = LetterGrid(GRID_SIZE)
     self.score = Score()
     self.level = Level()
     self.io = MeowDatabase()
Ejemplo n.º 41
0
 def __init__(self):
     pygame.mixer.pre_init(48000,-16,2, 1024) #Sound Settings
     pygame.init()
     
     #sets the screen resolution for the game and sets a rect for the game screen
     self.screen = pygame.display.set_mode((1024,768))
     self.screen_rect = self.screen.get_rect()
     
     #initializes a clock for the game
     self.clock = pygame.time.Clock()
     
     #initializes a menu object and HUD object and Score object
     self.menu = Menu()
     self.hud = Hud()
     self.score = Score()
     #sets a boolean for whether you are still in the menu or not
     self.inMenu = True
     #sets a camera for the world
     self.camBorder = 32
     self.cam = Camera(pygame.Rect(100, 100, 1024, 768), pygame.Rect(self.camBorder, self.camBorder, 2048 - self.camBorder, 1536 - self.camBorder))
     self.camShakeFactor = 0 #Magnitude of shake
     self.camShakeDecayFactor = 0.08 #Lerp Amount
     
     #Timing
     self.timer = pygame.time.get_ticks()
     self.elapsed = 0
     
     #Sound Controller
     self.soundCon = SoundCon()
     
     #Game Values
     self.backgroundImg = pygame.image.load("Images/Arena/Arena2.png").convert_alpha()
     self.backgroundImgRect = self.backgroundImg.get_rect()
     self.player = Player( self.hud )
     
     #Effects
     self.effectInstances = []
     self.spawnSound = pygame.mixer.Sound("Sounds/ShipRev.wav")
     self.deathSound = pygame.mixer.Sound("Sounds/shipExplo.wav")
     self.enemyExplo = pygame.mixer.Sound("Sounds/enemyExplo.wav")
     self.clashSound = pygame.mixer.Sound("Sounds/clash.wav")
     self.boostSound = pygame.mixer.Sound("Sounds/boostLow.wav")
     
     #Game over fade out
     self.fadeImage = pygame.image.load("Images/HUD/CrackedGlass.png").convert_alpha()
     self.fadeRect = self.fadeImage.get_rect()
     self.fadeSurface = pygame.Surface((1024, 768), pygame.SRCALPHA)
     self.fadeSurfaceAlpha = 0
     self.fadeSurfaceRate = 1
     self.doFade = False
     self.restartGame = False
     
     #Enemies
     self.enemyList = []
     self.baseNumEnemies = 2
     self.spawnTime = 10
     self.currentSpawnTime = 30
Ejemplo n.º 42
0
	def delete_duplicates( self, control, location ):
		scores = Score.all().filter( "control =", control )
		
		if not location in ( config.LOCATION_WORLD, config.LOCATION_WEEK ):
			scores = scores.filter( "location =", location )
		
		elif location == config.LOCATION_WEEK:
			scores = scores.filter( "new_week =", True )
		elif location != config.LOCATION_WORLD:
			logging.error( "CronJob.delete_duplicates: Got an invalid " \
				+ "location \"%s\".", location )
			return
		
		fetched = scores.order( "-points" ).fetch( config.TOP_LIST_LENGTH )
		fetched = sorted( fetched, key=lambda score: score.date )
		
		to_remove = []
		i = 0
		while i < len( fetched ):
			scorei = fetched[i]
			j = i+1
			while j < len( fetched ):
				scorej = fetched[j]
				if not scorei is scorej and scorei.equals( scorej ) \
						and not scorej in to_remove:
					to_remove.append( scorej )
				j += 1
			i += 1
		
		have = [ score.to_dict() for score in fetched ]
		logging.info( "Location: \"%s\" Have %d scores: %s", location,
			len( have ), have )
		
		would = [ score.to_dict() for score in to_remove ]
		logging.info( "Location: \"%s\"Would remove %d scores: %s", location,
			len( would ), would )
		
		count1 = 0
		for score in to_remove:
			if score in fetched:
				count1 += 1
		
		count2 = 0
		for score in fetched:
			if score in to_remove:
				count2 += 1
		
		logging.info( "count1: %d, count2: %d", count1, count2 )
		
		try:
			db.delete( to_remove )
			self.response.out.write(
				"<br />all entities deleted successfully." )
		except Exception, msg:
			self.response.out.write( "<br />Got exception: '%s'." % msg \
				+ "<br />Some or all deletes might have failed." )
Ejemplo n.º 43
0
def ponderateFrequencyMatrix(groups):
    """
    Return the weighted matrix for the groups
    """
    matrix = Score()
    length = len(groups[0][0])
    for i in range(length):
        for iGroup, group in enumerate(groups):
            for seq in group:
                aa1 = seq[i]
                for iOtherGroup, otherGroup in enumerate(groups):
                    if iGroup != iOtherGroup:
                        for otherSeq in otherGroup:
                            aa2 = otherSeq[i]
                            freq = (1 / len(group)) * (1 / len(otherGroup))
                            if aa1 == aa2:
                                freq = freq / 2
                            matrix[aa1, aa2] = matrix.get((aa1, aa2), 0) + freq
    return matrix
Ejemplo n.º 44
0
    def score_game(self, winner, penalty_winner, penalty_loser):
        """ Set up Score for Game """
        if winner == self.player_one:
            loser = self.player_two
        else:
            loser = self.player_one
        # Add the game to the score 'board'
        score = Score(date=date.today(),
                      game=self.key,
                      winner=winner,
                      loser=loser,
                      penalty_winner=penalty_winner,
                      penalty_loser=penalty_loser)
        score.put()

        # Update the user models
        winner.get().add_win()
        loser.get().add_loss()
        return
Ejemplo n.º 45
0
    def create_evaluation(self, reading_system):
        "Create and return a new evaluation, along with an initialized set of result objects."
        from test import Test
        from score import Score
        from result import Result
        from category import Category
        from testsuite import TestSuite

        testsuite = TestSuite.objects.get_most_recent_testsuite()
        print "Creating evaluation for testsuite {0}".format(testsuite.version_date)
        tests = Test.objects.filter(testsuite = testsuite)

        evaluation = self.create(
            testsuite = testsuite,
            last_updated = generate_timestamp(),
            percent_complete = 0.00,
            reading_system = reading_system
        )
        evaluation.save()
        
        total_score = Score(category = None, evaluation = evaluation)
        total_score.save()

        # create results for this evaluation
        for t in tests:
            result = Result(test = t, evaluation = evaluation, result = RESULT_NOT_ANSWERED)
            result.save()

        # update the score once results have been created
        total_score.update(evaluation.get_all_results())

        # create category score entries for this evaluation
        categories = Category.objects.filter(testsuite = evaluation.testsuite)
        for cat in categories:
            score = Score(
                category = cat,
                evaluation = evaluation
            )
            score.update(evaluation.get_category_results(cat))
            score.save()

        return evaluation
Ejemplo n.º 46
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
Ejemplo n.º 47
0
 def evaluate(self):
     test_input = pd.read_csv('../input/local_test_input.csv')
     test_output_true = pd.read_csv('../input/local_test_output.csv')
     test_output_predict = self.predict(test_input)
     if test_output_true.shape != test_output_predict.shape:
         raise RuntimeError('Size of predict is not equal size of true')
     merge_output = pd.merge(test_output_true, test_output_predict, on='device_id', suffixes=['_true', '_predict'])
     true = map(lambda x: x.split(' '), merge_output['cookie_id_true'].values)
     predict = map(lambda x: x.split(' '), merge_output['cookie_id_predict'].values)
     score = Score.mean_f_measure(true, predict, 0.5)
     print "Evaluate:", score
Ejemplo n.º 48
0
 def __init__(self, configuration):
     self.config = configuration
     self.score = Score()
     self.score_drawer = ScoreDrawer(self.config.background)
     self.ball = Ball(*self._init_sounds())
     racket_x_position = 60
     self.racket1 = Racket(racket_x_position, constants.SCREEN_WIDTH/2 - 35)
     self.racket2 = Racket(
             constants.SCREEN_WIDTH - racket_x_position - 10,
             constants.SCREEN_WIDTH/2 - 35
             )
     self.net = Net()
     self.the_winner_is = ''
Ejemplo n.º 49
0
def main():

    open_canvas()

    global background, score, timer, burger, character_list
    global running
    global current_time, frame_time
    background = Background()
    score = Score()
    timer = Timer()
    character_list = [Character() for i in range(nCharacter)]
    burger.draw()

    running = True
    current_time = get_time()

    while running:
        frame_time = get_frame_time()
        handle_events()
        for character in character_list:
            character.update(frame_time)

        clear_canvas()
        background.draw()
        score.draw()
        score.update(value)
        timer.draw()
        timer.update(time_value)
        for character in character_list:
            character.draw()
            character.draw_bb()
        burger.draw()

        update_canvas()




    close_canvas()
Ejemplo n.º 50
0
 def __init__(self):
     self.moving_balls = deque([])
     self.hitted_balls = deque([])
     self.potted = []
     pygame.display.set_caption('Cool Snooker')
     self.table = pygame.image.load('Snooker_table3.png')
     self.white_ball = balls.WhiteBall(coords=POS_WHITE)
     self.redball1 = balls.RedBall(coords=POS_RED1)
     self.redball2 = balls.RedBall(coords=POS_RED2)
     self.redball3 = balls.RedBall(coords=POS_RED3)
     self.redball4 = balls.RedBall(coords=POS_RED4)
     self.redball5 = balls.RedBall(coords=POS_RED5)
     self.redball6 = balls.RedBall(coords=POS_RED6)
     self.redball7 = balls.RedBall(coords=POS_RED7)
     self.redball8 = balls.RedBall(coords=POS_RED8)
     self.redball9 = balls.RedBall(coords=POS_RED9)
     self.redball10 = balls.RedBall(coords=POS_RED10)
     self.redball11 = balls.RedBall(coords=POS_RED11)
     self.redball12 = balls.RedBall(coords=POS_RED12)
     self.redball13 = balls.RedBall(coords=POS_RED13)
     self.redball14 = balls.RedBall(coords=POS_RED14)
     self.redball15 = balls.RedBall(coords=POS_RED15)
     self.black = balls.ColorBall(coords=POS_BLACK, COLOR=BLACK, points=7)
     self.pink = balls.ColorBall(coords=POS_PINK, COLOR=PINK, points=6)
     self.blue = balls.ColorBall(coords=POS_BLUE, COLOR=BLUE, points=5)
     self.brown = balls.ColorBall(coords=POS_BROWN, COLOR=BROWN, points=4)
     self.green = balls.ColorBall(coords=POS_GREEN, COLOR=GREEN, points=3)
     self.yellow = balls.ColorBall(coords=POS_YELLOW,
                                   COLOR=YELLOW, points=2)
     self.first_player = Player("Selby")
     self.second_player = Player("O'Sullivan")
     self.all_balls = deque([
                            self.redball1, self.redball2, self.redball3,
                            self.redball4, self.redball5, self.redball6,
                            self.redball7, self.redball8, self.redball9,
                            self.redball10, self.redball11, self.redball12,
                            self.redball13, self.redball14, self.redball15,
                            self.white_ball, self.black, self.pink,
                            self.blue, self.brown, self.green, self.yellow
                            ])
     self.cue = Cue()
     self.turn = self.first_player
     self.board_status = STATICK
     self.colol_order = iter([x for x in range(2, 8)])
     self.next_target_ball = next(self.colol_order)
     self.condition = STILL_RED
     self.score = Score()
     self.foul = False
     self.hit = False
     self.painter = Draw()
Ejemplo n.º 51
0
 def __init__(self, screen_height, screen_width):
     pygame.init()
     self.screen_height = screen_height
     self.screen_width = screen_width
     self.level_maps = ("./data/level1.map", "./data/level2.map", "./data/level3.map")
     self.current_level_map_index = 0
     self.pause = False
     self.won_grow_rate = 10
     height_width = (self.screen_height, self.screen_width)
     self.screen = pygame.display.set_mode(height_width)
     pygame.display.set_caption("PySnake")
     self.score = Score((0, 500))
     self.reload_game = False
     self.speed = 5
Ejemplo n.º 52
0
	def score_me(self, iowait_threshold=20):
		old_score = Score.get_score()
		iowait_pct = self.iowait/(self.uptime+0.0) * 100
		idle_pct = self.idle/(self.uptime+0.0) * 100
		busy_pct = (self.user+self.nice+self.system)/(self.uptime+0.0) * 100

		if iowait_pct >= busy_pct:
			Score.update_score(20)

		elif busy_pct >= idle_pct:
			Score.update_score(10)

		if iowait_pct >= (iowait_threshold/100.0) * self.uptime:
			Score.update_score(10)

		self.score_deducted = old_score - Score.get_score()
Ejemplo n.º 53
0
    def get(self):
        # 本とは異なり、main.htmlにuser関連の情報を持たせていないので、ここで取得する
        user, nickname = user_filter.do_filter()

        # ログインしていなければ登録しない
        if user == None:
            return


        # Over Runしていたら登録しない
        # leftLengthの算出方法は、main.jsの82行目に合わせる:小数点以下は切り捨てで計算、6での除算はトライ・アンド・エラーによるものらしい
        decimalLength = decimal.Decimal(self.request.get('leftLength'))
        leftLength = int((decimalLength / 6).to_integral_exact(rounding=decimal.ROUND_DOWN))
        if leftLength < 0:
            return


        # スコアエンティティを登録する
        accountId = user.federated_identity()
        if accountId == None:
            accountId = user.user_id()

        if nickname == None:
            nickname = 'Unknown nickname'

        jst = Utility.get_jst_now()
        offset = Score.get_date_offset(jst)
        rankValue = offset + leftLength

        q = Score(
                  key_name=accountId,
                  nickname=nickname,
                  registerDate=jst,
                  rankValue=rankValue,
                 )
        q.put()
Ejemplo n.º 54
0
	def clean_country( self, control, location, lowest_score ):
		scores = Score.all() \
			.filter( "control =", control ) \
			.filter( "location =", location ) \
			.filter( "points <", lowest_score ) \
			.filter( "new_week =", False ) \
			.fetch( 400 )
		
		high = 0
		for s in scores:
			if s.points > high:
				high = s.points
		
		try:
			db.delete( scores )
		except Exception, msg:
			logging.error( "Got exception: '%s'. Some or all deletes might " \
				+ "have failed.", msg )
Ejemplo n.º 55
0
    def __init__(self,args):

        # create logger
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        
        # create console handler and set level to debug
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        
        # create formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        
        # add formatter to ch
        ch.setFormatter(formatter)
        
        # add ch to logger
        self.logger.addHandler(ch)        
        self.logger.debug( "Starting Collector process in %s"%os.getcwd())
        self.logger.debug( "Gevent Version %s"%gevent.__version__)
        
        #TODO: move output file name to config
        #fname = "./NetFlow.%s.bin"%str(time.time()*100000)
        
        #WARN: might want to remove this after testing
        #self.out = open(fname,"wb")
        
        #create tool instances
        self.interface = Interface()
        self.parse = Parse()
        self.describe = Describe()
        self.standardize = Standardize()
        self.transform = Transform()
        self.partition = Partition()
        
        self.q = Queue()
        self.inWindow = False
        
        self.score = Score()
        #TODO: move csv name to config
        self.csv = CSV("output.csv")
        
        return super(Collector,self).__init__(args)
Ejemplo n.º 56
0
class ScoreTest(unittest.TestCase):

    def setUp(self):
        self.score = Score(0)

    def testAddingWorks(self):
        self.score.add_from([5, 5, 4])
        self.assertEqual(self.score.total, 29)
        self.score.add(3)
        self.assertEqual(self.score.total, 87)

    def testKeepsTrackOfScoreString(self):
        self.score.add_from([1, 2, 3, 4, 5])
        self.assertEqual(self.score.string, [0, 1, 2, 3, 4, 5])
Ejemplo n.º 57
0
 def increase_score(self):
     if len(self.scores) == 0:
         # Cache the score icon
         score_label = Score(self.fill_color, self.stroke_color)
         score_pixbuf_unsel = score_label.get_pixbuf()
         score_pixbuf_sel = score_label.get_pixbuf_sel()
     else:
         score_pixbuf_unsel = None
         score_pixbuf_sel = None
     
     new_score = Score(self.fill_color, self.stroke_color,
                       score_pixbuf_sel, score_pixbuf_unsel, self.status)
     self.scores.append(new_score)
     new_score.show()
     self.score_table.attach(new_score, self.current_x , self.current_x + 1,
             self.current_y, self.current_y + 1, gtk.SHRINK, gtk.SHRINK)
     self.current_x += 1
     if self.current_x == self._score_cols:
         self.current_x = 0
         self.current_y += 1
     self.queue_draw()
Ejemplo n.º 58
0
    def main(self):
        self.music.play()

        # Screen base
        self.screen.fill((0,0,0))
        self.screen.blit(self.img_background,self.img_background_rect)

        highscores = Highscores()

        # Main instances
        pavement = Pavement(self.unit)
        snake = Snake(self.unit)
        foods = Foods(self.unit)
        walls = Walls(self.unit)
        score = Score(self.unit,self.surface_rect)

        nextgold = random.randint(*Constants.TIMERANGE_GOLD) * Constants.FPS # first gold between 30 & 60 seconds
        makegold = False
        nextwall = random.randint(*Constants.TIMERANGE_WALL) * Constants.FPS # first gold between 30 & 60 seconds
        makewall = False

        updatestats = True

        counter = 0

        flag_music = True
        flag_pause = False
        #MAIN LOOP
        while self.running:
            time = pygame.time.get_ticks()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.running = False

                    elif event.key == pygame.K_m:
                        flag_music = not flag_music
                        if flag_music:
                            self.music.play()
                        else:
                            self.music.stop()

                    elif event.key == pygame.K_1:
                        pygame.image.save(self.screen, "screenshot.jpg")

                    elif event.key == pygame.K_SPACE or event.key == pygame.K_p:
                        flag_pause = True
                        self.print_text("PAUSE")
                        while flag_pause:
                            for event in pygame.event.get():
                                if event.type==pygame.KEYDOWN:
                                    if event.key==pygame.K_p or event.key == pygame.K_SPACE:
                                        flag_pause = False

                    else:
                        # Time to change direction
                        action = 0
                        if event.key == pygame.K_UP or event.key == pygame.K_w: action = 1
                        elif event.key == pygame.K_DOWN or event.key == pygame.K_s: action = 2
                        elif event.key == pygame.K_LEFT or event.key == pygame.K_a: action = 3
                        elif event.key == pygame.K_RIGHT or event.key == pygame.K_d: action = 4
                        if action:
                            self.sounds.play("move")
                            snake.action(action)

            # Snake movements and pavement reactions
            snake.move()
            pavement.passage(snake.head)
            pavement.make_regrow(snake.tail)

            # Snake has eaten?
            if foods.check(snake.head):
                updatestats = True
                snake.grow(Constants.GROW)
                score.add_score(foods.score)
                self.sounds.play("eat")

            # Snake
            if walls.check(snake.head):
                snake.alive = False

            # Snake is dead?
            if not snake.alive:
                #blood splash (bin on head, little on body)
                pavement.bloodsplat(snake.head)
                [pavement.bloodsplat(x,1) for x in snake.body if random.randint(0,2)==0]
                #redraw all the snake
                snake.set_dirty(1)
                self.sounds.play("splat")
                self.running = False

            # Gold generator (After pseudo-random time a golden apple will appear)
            nextgold-=1
            if nextgold<0:
                makegold = True
                nextgold = random.randint(*Constants.TIMERANGE_GOLD)*Constants.FPS

            # Wall generator (After pseudo-random time a wall will appear)
            nextwall-=1
            if nextwall<0:
                makewall = True
                nextwall = random.randint(*Constants.TIMERANGE_WALL)*Constants.FPS

            # Foods request to create an apple
            # Game has to provide to Foods the list of forbidden blocks
            if foods.needapple or makegold or makewall:
                forbidden = [[-1,-1]]
                forbidden.extend(foods.get_forbidden())
                forbidden.extend(snake.get_forbidden())
                forbidden.extend(walls.get_forbidden())

                # Creates the apples and make the pavement Grass
                if foods.needapple:
                    newpos = foods.make_apple(forbidden)
                    pavement.make_grass(newpos)
                    forbidden.extend(newpos)
                if makegold:
                    self.sounds.play('ding')
                    newpos = foods.make_gold(forbidden)
                    pavement.make_grass(newpos)
                    forbidden.extend(newpos)
                    makegold = False
                if makewall:
                    self.sounds.play('fall')
                    newpos = walls.make_solid(forbidden)
                    pavement.make_none(newpos)
                    forbidden.extend(newpos)
                    makewall = False

            # Foods request pavement update
            for pos in foods.refresh:
                pavement.passage(pos)
                foods.refresh.remove(pos)
                del pos

            # Updates and draws
            pavement.update()
            pavement.draw(self.surface)
            walls.update()
            walls.draw(self.surface)
            snake.update()
            snake.draw(self.surface)
            foods.update()
            foods.draw(self.surface)

            if updatestats or not counter % Constants.FPS:
                score.set_length(snake.length)
                score.update()
                score.draw(self.screen)
                updatestats = False

            if not counter % Constants.FPS:
                score.add_second()
                counter = 0

            # Surface on surface... weeee!
            self.screen.blit(self.surface,self.surface_rect)

            pygame.display.update()
            self.clock.tick(self.tick)
            counter+=1
            #END OF MAIN LOOP

        if not snake.alive:

            self.print_text("GAME OVER")

            if highscores.check(score.score,score.elapse):
                current_string = ''
                complete = False

                inputbox = InputBox(self.unit)
                inputbox.rect.centerx = self.screen.get_rect().centerx
                inputbox.rect.centery = self.screen.get_rect().centery
                inputbox.draw(self.screen)

                pygame.display.update()
                pygame.event.clear()
                redraw = False
                while not complete:
                    event = pygame.event.wait()
                    if event.type == pygame.QUIT:
                        return
                    if event.type != pygame.KEYDOWN:
                        continue
                    if event.key == pygame.K_BACKSPACE:
                        current_string = current_string[:-1]
                        redraw = True
                    elif event.key == pygame.K_RETURN:
                        if len(current_string) == 0:
                            current_string = 'Mysterious player'
                        complete = True
                    elif event.unicode:
                        if len(current_string) <= 15:
                            c = ord(event.unicode)
                            if c >= 32 and c <= 126 or c==8:
                                current_string += event.unicode
                                redraw = True
                    if redraw:
                        redraw = False
                        inputbox.set_text(current_string)
                        inputbox.update()
                        inputbox.draw(self.screen)
                        pygame.display.update()
                position = highscores.insert(current_string,score.score,score.elapse)
                highscores.save()
                scored = {'index':position,'scored':True}
            else:
                counter = Constants.FPS*3 # 3 seconds
                pygame.display.update()
                while counter > 0:
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
                            counter = 0
                    self.clock.tick(self.tick)
                    pygame.display.update()
                    counter-=1

                scored = {'elapse':score.elapse,'score':score.score,'scored':False}

            ts = TitleScreen(self.screen,self.unit,self.preferences)
            ts.highscores(scored)
            del ts

        self.music.stop()
        return
Ejemplo n.º 59
0
class MenuManager(QtCore.QObject):
    ROOT, MENU1, MENU2, LAUNCH, DOCUMENTATION, QUIT, FULLSCREEN, UP, DOWN, \
            BACK, LAUNCH_QML = range(11)

    pInstance = None

    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.qmlRoot = None
        self.declarativeEngine = 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()

    @classmethod
    def instance(cls):
        if cls.pInstance is None:
            cls.pInstance = cls()

        return cls.pInstance

    def getResource(self, name):
        ba = self.helpEngine.fileData(QtCore.QUrl(name))

        if ba.isEmpty():
            Colors.debug(" - WARNING: Could not get", name)

        return ba

    def readXmlDocument(self):
        self.contentsDoc = QtXml.QDomDocument()

        xml_file = QtCore.QFile(':/xml/examples.xml')
        statusOK, errorStr, errorLine, errorColumn = \
                self.contentsDoc.setContent(xml_file, True)

        if not statusOK:
            QtGui.QMessageBox.critical(None, "DOM Parser",
                    "Could not read or find the contents document. Error at "
                    "line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr))
            sys.exit(-1)

    def initHelpEngine(self):
        self.helpRootUrl = 'qthelp://com.trolltech.qt.%d%d%d/qdoc/' % (QtCore.QT_VERSION >> 16, (QtCore.QT_VERSION >> 8) & 0xff, QtCore.QT_VERSION & 0xff)

        # Store help collection file in cache dir of assistant.
        cacheDir = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.DataLocation) + '/Trolltech/Assistant/'
        helpDataFile = 'qtdemo_%s.qhc' % QtCore.QT_VERSION_STR

        dir = QtCore.QDir()
        if not dir.exists(cacheDir):
            dir.mkpath(cacheDir)

        # Create help engine (and new helpDataFile if it does not exist).
        self.helpEngine = QtHelp.QHelpEngineCore(cacheDir + helpDataFile)
        self.helpEngine.setupData()

        qtDocRoot = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.DocumentationPath) + '/qch'
        qtDocRoot = QtCore.QDir(qtDocRoot).absolutePath()

        qchFiles = ['/qt.qch', '/designer.qch', '/linguist.qch']

        oldDir = self.helpEngine.customValue('docDir', '')
        if oldDir != qtDocRoot:
            for qchFile in qchFiles:
                self.helpEngine.unregisterDocumentation(QtHelp.QHelpEngineCore.namespaceName(qtDocRoot + qchFile))

        # If the data that the engine will work on is not yet registered, do it
        # now.
        for qchFile in qchFiles:
            self.helpEngine.registerDocumentation(qtDocRoot + qchFile)

        self.helpEngine.setCustomValue('docDir', qtDocRoot)

    def itemSelected(self, userCode, menuName):
        if userCode == MenuManager.LAUNCH:
            self.launchExample(self.currentInfo)
        elif userCode == MenuManager.LAUNCH_QML:
            self.launchQmlExample(self.currentInfo)
        elif userCode == MenuManager.DOCUMENTATION:
            self.showDocInAssistant(self.currentInfo)
        elif userCode == MenuManager.QUIT:
            self.window.quit()
        elif userCode == MenuManager.FULLSCREEN:
            self.window.toggleFullscreen()
        elif userCode == MenuManager.ROOT:
            # Out.
            self.score.queueMovie(self.currentMenu + ' -out', Score.FROM_START,
                    Score.LOCK_ITEMS)
            self.score.queueMovie(self.currentMenuButtons + ' -out',
                    Score.FROM_START, Score.LOCK_ITEMS)
            self.score.queueMovie(self.currentInfo + ' -out')
            self.score.queueMovie(self.currentInfo + ' -buttons -out',
                    Score.NEW_ANIMATION_ONLY)
            self.score.queueMovie('back -out', Score.ONLY_IF_VISIBLE)

            if self.qmlRoot is not None:
                self.qmlRoot.setProperty('show', False)

            # Book-keeping.
            self.currentMenuCode = MenuManager.ROOT
            self.currentMenu = menuName + ' -menu1'
            self.currentMenuButtons = menuName + ' -buttons'
            self.currentInfo = menuName + ' -info'

            # In.
            self.score.queueMovie('upndown -shake')
            self.score.queueMovie(self.currentMenu, Score.FROM_START,
                    Score.UNLOCK_ITEMS)
            self.score.queueMovie(self.currentMenuButtons, Score.FROM_START,
                    Score.UNLOCK_ITEMS)
            self.score.queueMovie(self.currentInfo)

            if not Colors.noTicker:
                self.ticker.doIntroTransitions = True
                self.tickerInAnim.startDelay = 2000
                self.ticker.useGuideQt()
                self.score.queueMovie('ticker', Score.NEW_ANIMATION_ONLY)
        elif userCode == MenuManager.MENU1:
            # Out.
            self.score.queueMovie(self.currentMenu + ' -out', Score.FROM_START,
                    Score.LOCK_ITEMS)
            self.score.queueMovie(self.currentMenuButtons + ' -out',
                    Score.FROM_START, Score.LOCK_ITEMS)
            self.score.queueMovie(self.currentInfo + ' -out')

            if self.qmlRoot is not None:
                self.qmlRoot.setProperty('show', False)

            # Book-keeping.
            self.currentMenuCode = MenuManager.MENU1
            self.currentCategory = menuName
            self.currentMenu = menuName + ' -menu1'
            self.currentInfo = menuName + ' -info'

            # In.
            self.score.queueMovie('upndown -shake')
            self.score.queueMovie('back -in')
            self.score.queueMovie(self.currentMenu, Score.FROM_START,
                    Score.UNLOCK_ITEMS)
            self.score.queueMovie(self.currentInfo)

            if not Colors.noTicker:
                self.ticker.useGuideTt()
        elif userCode == MenuManager.MENU2:
            # Out.
            self.score.queueMovie(self.currentInfo + ' -out',
                    Score.NEW_ANIMATION_ONLY)
            self.score.queueMovie(self.currentInfo + ' -buttons -out',
                    Score.NEW_ANIMATION_ONLY)

            if self.qmlRoot is not None:
                self.qmlRoot.setProperty('show', False)

            # Book-keeping.
            self.currentMenuCode = MenuManager.MENU2
            self.currentInfo = menuName

            # In/shake.
            self.score.queueMovie('upndown -shake')
            self.score.queueMovie('back -shake')
            self.score.queueMovie(self.currentMenu + ' -shake')
            self.score.queueMovie(self.currentInfo, Score.NEW_ANIMATION_ONLY)
            self.score.queueMovie(self.currentInfo + ' -buttons',
                    Score.NEW_ANIMATION_ONLY)

            if not Colors.noTicker:
                self.score.queueMovie('ticker -out', Score.NEW_ANIMATION_ONLY)
        elif userCode == MenuManager.UP:
            backMenu = self.info[self.currentMenu]['back']
            if backMenu:
                self.score.queueMovie(self.currentMenu + ' -top_out',
                        Score.FROM_START, Score.LOCK_ITEMS)
                self.score.queueMovie(backMenu + ' -bottom_in',
                        Score.FROM_START, Score.UNLOCK_ITEMS)
                self.currentMenu = backMenu
        elif userCode == MenuManager.DOWN:
            moreMenu = self.info[self.currentMenu]['more']
            if moreMenu:
                self.score.queueMovie(self.currentMenu + ' -bottom_out',
                        Score.FROM_START, Score.LOCK_ITEMS)
                self.score.queueMovie(moreMenu + ' -top_in', Score.FROM_START,
                        Score.UNLOCK_ITEMS)
                self.currentMenu = moreMenu
        elif userCode == MenuManager.BACK:
            if self.currentMenuCode == MenuManager.MENU2:
                # Out.
                self.score.queueMovie(self.currentInfo + ' -out',
                        Score.NEW_ANIMATION_ONLY)
                self.score.queueMovie(self.currentInfo + ' -buttons -out',
                        Score.NEW_ANIMATION_ONLY)

                if self.qmlRoot is not None:
                    self.qmlRoot.setProperty('show', False)

                # Book-keeping.
                self.currentMenuCode = MenuManager.MENU1
                self.currentMenuButtons = self.currentCategory + ' -buttons'
                self.currentInfo = self.currentCategory + ' -info'

                # In/shake.
                self.score.queueMovie('upndown -shake')
                self.score.queueMovie(self.currentMenu + ' -shake')
                self.score.queueMovie(self.currentInfo,
                        Score.NEW_ANIMATION_ONLY)
                self.score.queueMovie(self.currentInfo + ' -buttons',
                        Score.NEW_ANIMATION_ONLY)

                if not Colors.noTicker:
                    self.ticker.doIntroTransitions = False
                    self.tickerInAnim.startDelay = 500
                    self.score.queueMovie('ticker', Score.NEW_ANIMATION_ONLY)
            elif self.currentMenuCode != MenuManager.ROOT:
                self.itemSelected(MenuManager.ROOT, Colors.rootMenuName)

        # Update back and more buttons.
        if self.info.setdefault(self.currentMenu, {}).get('back'):
            back_state = TextButton.OFF
        else:
            back_state = TextButton.DISABLED

        if self.info[self.currentMenu].get('more'):
            more_state = TextButton.OFF
        else:
            more_state = TextButton.DISABLED

        self.upButton.setState(back_state)
        self.downButton.setState(more_state)

        if self.score.hasQueuedMovies():
            self.score.playQue()
            # Playing new movies might include loading etc., so ignore the FPS
            # at this point.
            self.window.fpsHistory = []

    def showDocInAssistant(self, name):
        url = self.resolveDocUrl(name)
        Colors.debug("Sending URL to Assistant:", url)

        # Start assistant if it's not already running.
        if self.assistantProcess.state() != QtCore.QProcess.Running:
            app = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath) + QtCore.QDir.separator()

            if sys.platform == 'darwin':
                app += 'Assistant.app/Contents/MacOS/Assistant'
            else:
                app += 'assistant'

            args = ['-enableRemoteControl']
            self.assistantProcess.start(app, args)
            if not self.assistantProcess.waitForStarted():
                QtGui.QMessageBox.critical(None, "PyQt Demo",
                        "Could not start %s." % app)
                return

        # Send command through remote control even if the process was just
        # started to activate assistant and bring it to the front.
        cmd_str = QtCore.QTextStream(self.assistantProcess)
        cmd_str << 'SetSource ' << url << '\n'

    def launchExample(self, name):
        executable = self.resolveExeFile(name)

        process = QtCore.QProcess(self)
        process.finished.connect(self.exampleFinished)
        process.error.connect(self.exampleError)

        if sys.platform == 'win32':
            # Make sure it finds the DLLs on Windows.
            curpath = os.getenv('PATH')
            newpath = 'PATH=%s;%s' % (QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath), curpath)
            process.setEnvironment([newpath])

        if self.info[name]['changedirectory'] != 'false':
            workingDirectory = self.resolveDataDir(name)
            process.setWorkingDirectory(workingDirectory)
            Colors.debug("Setting working directory:", workingDirectory)

        Colors.debug("Launching:", executable)
        process.start(sys.executable, [executable])

    def launchQmlExample(self, name):
        if self.declarativeEngine is None:
            QtGui.QMessageBox.critical(None, "QtDeclarative unsupported",
                    "The QtDeclarative module is not supported by this "
                    "installation of PyQt.",
                    QtGui.QMessageBox.Cancel)
            return

        if self.qmlRoot is None:
            self.exampleError(QtCore.QProcess.UnknownError)
            return

        qml_dir = self.resolveDataDir(name)
        qml_file = QtCore.QFile(qml_dir + '/main.qml')

        if not qml_file.exists():
            qml_file.setFileName(qml_dir + '/' + qml_dir.split('/')[-1] + '.qml')
            if not qml_file.exists():
                self.exampleError(QtCore.QProcess.UnknownError)
                return

        # Unload any existing component.
        self.qmlRoot.setProperty('qmlFile', '')
        self.qmlRoot.setProperty('show', True)
        self.qmlRoot.setProperty('qmlFile', QtCore.QUrl.fromLocalFile(qml_file.fileName()))

    def exampleFinished(self):
        pass

    def exampleError(self, error):
        if error != QtCore.QProcess.Crashed:
            QtGui.QMessageBox.critical(None, "Failed to launch the example",
                    "Could not launch the example. Ensure that it has been "
                    "built.",
                    QtGui.QMessageBox.Cancel)

    def init(self, window):
        self.window = window

        # Create div.
        self.createTicker()
        self.createUpnDownButtons()
        self.createBackButton()

        # Create first level menu.
        rootElement = self.contentsDoc.documentElement()
        self.createRootMenu(rootElement)

        # Create second level menus.
        level2MenuNode = rootElement.firstChild()
        while not level2MenuNode.isNull():
            level2MenuElement = level2MenuNode.toElement()
            self.createSubMenu(level2MenuElement)

            # Create leaf menu and example info.
            exampleNode = level2MenuElement.firstChild()
            while not exampleNode.isNull():
                exampleElement = exampleNode.toElement()
                self.readInfoAboutExample(exampleElement)
                self.createLeafMenu(exampleElement)
                exampleNode = exampleNode.nextSibling()

            level2MenuNode = level2MenuNode.nextSibling()

        # Support QML if possible.
        try:
            from PyQt4 import QtDeclarative
        except ImportError:
            return

        self.declarativeEngine = QtDeclarative.QDeclarativeEngine(self)

        component = QtDeclarative.QDeclarativeComponent(self.declarativeEngine,
                QtCore.QUrl('qrc:/qml/qmlShell.qml'), self)
        if component.isReady():
            self.qmlRoot = component.create()

        if self.qmlRoot is not None:
            self.qmlRoot.setHeight(window.scene.sceneRect().height())
            self.qmlRoot.setWidth(window.scene.sceneRect().width())
            self.qmlRoot.setZValue(101)
            self.qmlRoot.setCursor(QtCore.Qt.ArrowCursor)
            window.scene.addItem(self.qmlRoot)

            window.viewport().setFocusPolicy(QtCore.Qt.NoFocus)
            window.setFocusPolicy(QtCore.Qt.StrongFocus)
            window.scene.setStickyFocus(True)
            window.setFocus()
        else:
            Colors.debug("Error initializing QML subsystem, Declarative examples will not work")

    def readInfoAboutExample(self, example):
        name = str(example.attribute('name'))
        if name in self.info:
            Colors.debug("__WARNING: MenuManager.readInfoAboutExample: "
                         "Demo/example with name", name, "appears twice in "
                         "the xml-file!__")

        self.info.setdefault(name, {})['filename'] = str(example.attribute('filename'))
        self.info[name]['category'] = str(example.parentNode().toElement().tagName())
        self.info[name]['dirname'] = str(example.parentNode().toElement().attribute('dirname'))
        self.info[name]['changedirectory'] = str(example.attribute('changedirectory'))
        self.info[name]['image'] = str(example.attribute('image'))
        self.info[name]['qml'] = str(example.attribute('qml'))

    def resolveDir(self, name):
        dirName = self.info[name]['dirname']
        category = self.info[name]['category']
        fileName = self.info[name]['filename'].split('/')

        dir = QtCore.QFileInfo(__file__).dir()
        # To the 'demos' directory.
        dir.cdUp()
        # To the 'examples' directory.
        dir.cdUp()

        dir.cd(dirName)

        if len(fileName) > 1:
            dir.cd('/'.join(fileName[:-1]))

        # This may legitimately fail if the example is just a simple .py file.
        dir.cd(fileName[-1])

        return dir

    def resolveDataDir(self, name):
        return self.resolveDir(name).absolutePath()

    def resolveExeFile(self, name):
        dir = self.resolveDir(name)

        fileName = self.info[name]['filename'].split('/')[-1]

        pyFile = QtCore.QFile(dir.path() + '/' + fileName + '.py')
        if pyFile.exists():
            return pyFile.fileName()

        pywFile = QtCore.QFile(dir.path() + '/' + fileName + '.pyw')
        if pywFile.exists():
            return pywFile.fileName()

        Colors.debug("- WARNING: Could not resolve executable:", dir.path(),
                fileName)
        return '__executable not found__'

    def resolveDocUrl(self, name):
        dirName = self.info[name]['dirname']
        category = self.info[name]['category']
        fileName = self.info[name]['filename']

        if category == 'demos':
            return self.helpRootUrl + 'demos-' + fileName + '.html'
        else:
            return self.helpRootUrl + dirName.replace('/', '-') + '-' + fileName + '.html'

    def resolveImageUrl(self, name):
        return self.helpRootUrl + 'images/' + name

    def getHtml(self, name):
        return self.getResource(self.resolveDocUrl(name))

    def getImage(self, name):
        imageName = self.info[name]['image']
        category = self.info[name]['category']
        fileName = self.info[name]['filename']

        if self.info[name]['qml'] == 'true':
            fileName = 'qml-' + fileName.split('/')[-1]

        if not imageName:
            if category == 'demos':
                imageName = fileName + '-demo.png'
            else:
                imageName = fileName + '-example.png'

            if self.getResource(self.resolveImageUrl(imageName)).isEmpty():
                imageName = fileName + '.png'

            if self.getResource(self.resolveImageUrl(imageName)).isEmpty():
                imageName = fileName + 'example.png'

        return self.getResource(self.resolveImageUrl(imageName))

    def createRootMenu(self, el):
        name = str(el.attribute('name'))
        self.createMenu(el, MenuManager.MENU1)
        self.createInfo(
                MenuContentItem(el, self.window.scene,
                        self.window.mainSceneRoot),
                name + ' -info')

        menuButtonsIn = self.score.insertMovie(name + ' -buttons')
        menuButtonsOut = self.score.insertMovie(name + ' -buttons -out')
        self.createLowLeftButton("Quit", MenuManager.QUIT, menuButtonsIn,
                menuButtonsOut, None)
        self.createLowRightButton("Toggle fullscreen", MenuManager.FULLSCREEN,
                menuButtonsIn, menuButtonsOut, None)

    def createSubMenu(self, el):
        name = str(el.attribute('name'))
        self.createMenu(el, MenuManager.MENU2)
        self.createInfo(
                MenuContentItem(el, self.window.scene,
                        self.window.mainSceneRoot),
                name + ' -info')

    def createLeafMenu(self, el):
        name = str(el.attribute('name'))
        self.createInfo(
                ExampleContent(name, self.window.scene,
                        self.window.mainSceneRoot),
                name)

        infoButtonsIn = self.score.insertMovie(name + ' -buttons')
        infoButtonsOut = self.score.insertMovie(name + ' -buttons -out')
        self.createLowRightLeafButton("Documentation", 600,
                MenuManager.DOCUMENTATION, infoButtonsIn, infoButtonsOut, None)
        if str(el.attribute('executable')) != 'false':
            self.createLowRightLeafButton("Launch", 405, MenuManager.LAUNCH,
                    infoButtonsIn, infoButtonsOut, None)
        elif str(el.attribute('qml')) == 'true':
            self.createLowRightLeafButton("Display", 405,
                    MenuManager.LAUNCH_QML, infoButtonsIn, infoButtonsOut,
                    None)

    def createMenu(self, category, type):
        sw = self.window.scene.sceneRect().width()
        xOffset = 15
        yOffset = 10
        maxExamples = Colors.menuCount
        menuIndex = 1
        name = str(category.attribute('name'))
        currentNode = category.firstChild()
        currentMenu = '%s -menu%d' % (name, menuIndex)

        while not currentNode.isNull():
            movieIn = self.score.insertMovie(currentMenu)
            movieOut = self.score.insertMovie(currentMenu + ' -out')
            movieNextTopOut = self.score.insertMovie(currentMenu + ' -top_out')
            movieNextBottomOut = self.score.insertMovie(currentMenu + ' -bottom_out')
            movieNextTopIn = self.score.insertMovie(currentMenu + ' -top_in')
            movieNextBottomIn = self.score.insertMovie(currentMenu + ' -bottom_in')
            movieShake = self.score.insertMovie(currentMenu + ' -shake')

            i = 0
            while not currentNode.isNull() and i < maxExamples:
                # Create a normal menu button.
                label = str(currentNode.toElement().attribute('name'))
                item = TextButton(label, TextButton.LEFT, type,
                        self.window.scene, self.window.mainSceneRoot)
                currentNode = currentNode.nextSibling()

                # Skip the OpenGL examples if they can't run.
                if str(currentNode.toElement().attribute('dirname')) == 'opengl':
                    if not Colors.openGlAvailable:
                        currentNode = currentNode.nextSibling()

                item.setRecursiveVisible(False)
                item.setZValue(10)
                ih = item.sceneBoundingRect().height()
                iw = item.sceneBoundingRect().width()
                ihp = ih + 3

                # Create in-animation.
                anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_IN)
                anim.setDuration(float(1000 + (i * 20)) * Colors.animSpeedButtons)
                anim.setStartPos(QtCore.QPointF(xOffset, -ih))
                anim.setPosAt(0.20, QtCore.QPointF(xOffset, -ih))
                anim.setPosAt(0.50, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY + (10 * float(i / 4.0))))
                anim.setPosAt(0.60, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(0.70, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY + (5 * float(i / 4.0))))
                anim.setPosAt(0.80, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(0.90, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY + (2 * float(i / 4.0))))
                anim.setPosAt(1.00, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                movieIn.append(anim)

                # Create out-animation.
                anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_OUT)
                anim.hideOnFinished = True
                anim.setDuration((700 + (30 * i)) * Colors.animSpeedButtons)
                anim.setStartPos(QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(0.60, QtCore.QPointF(xOffset, 600 - ih - ih))
                anim.setPosAt(0.65, QtCore.QPointF(xOffset + 20, 600 - ih))
                anim.setPosAt(1.00, QtCore.QPointF(sw + iw, 600 - ih))
                movieOut.append(anim)

                # Create shake-animation.
                anim = DemoItemAnimation(item)
                anim.setDuration(700 * Colors.animSpeedButtons)
                anim.setStartPos(QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(0.55, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY - i*2.0))
                anim.setPosAt(0.70, QtCore.QPointF(xOffset - 10, (i * ihp) + yOffset + Colors.contentStartY - i*1.5))
                anim.setPosAt(0.80, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY - i*1.0))
                anim.setPosAt(0.90, QtCore.QPointF(xOffset - 2, (i * ihp) + yOffset + Colors.contentStartY - i*0.5))
                anim.setPosAt(1.00, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                movieShake.append(anim)

                # Create next-menu top-out-animation.
                anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_OUT)
                anim.hideOnFinished = True
                anim.setDuration((200 + (30 * i)) * Colors.animSpeedButtons)
                anim.setStartPos(QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(0.70, QtCore.QPointF(xOffset, yOffset + Colors.contentStartY))
                anim.setPosAt(1.00, QtCore.QPointF(-iw, yOffset + Colors.contentStartY))
                movieNextTopOut.append(anim)

                # Create next-menu bottom-out-animation.
                anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_OUT)
                anim.hideOnFinished = True
                anim.setDuration((200 + (30 * i)) * Colors.animSpeedButtons)
                anim.setStartPos(QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(0.70, QtCore.QPointF(xOffset, (maxExamples * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(1.00, QtCore.QPointF(-iw, (maxExamples * ihp) + yOffset + Colors.contentStartY))
                movieNextBottomOut.append(anim)

                # Create next-menu top-in-animation.
                anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_IN)
                anim.setDuration((700 - (30 * i)) * Colors.animSpeedButtons)
                anim.setStartPos(QtCore.QPointF(-iw, yOffset + Colors.contentStartY))
                anim.setPosAt(0.30, QtCore.QPointF(xOffset, yOffset + Colors.contentStartY))
                anim.setPosAt(1.00, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                movieNextTopIn.append(anim)

                # Create next-menu bottom-in-animation.
                reverse = maxExamples - i
                anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_IN)
                anim.setDuration((1000 - (30 * reverse)) * Colors.animSpeedButtons)
                anim.setStartPos(QtCore.QPointF(-iw, (maxExamples * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(0.30, QtCore.QPointF(xOffset, (maxExamples * ihp) + yOffset + Colors.contentStartY))
                anim.setPosAt(1.00, QtCore.QPointF(xOffset, (i * ihp) + yOffset + Colors.contentStartY))
                movieNextBottomIn.append(anim)

                i += 1

            if not currentNode.isNull() and i == maxExamples:
                # We need another menu, so register for 'more' and 'back'
                # buttons.
                menuIndex += 1
                self.info.setdefault(currentMenu, {})['more'] = '%s -menu%d' % (name, menuIndex)
                currentMenu = '%s -menu%d' % (name, menuIndex)
                self.info.setdefault(currentMenu, {})['back'] = '%s -menu%d' % (name, menuIndex - 1)

    def createLowLeftButton(self, label, type, movieIn, movieOut, movieShake, menuString=""):
        button = TextButton(label, TextButton.RIGHT, type, self.window.scene,
                self.window.mainSceneRoot, TextButton.PANEL)
        if menuString:
            button.setMenuString(menuString)
        button.setRecursiveVisible(False)
        button.setZValue(10)

        iw = button.sceneBoundingRect().width()
        xOffset = 15

        # Create in-animation.
        buttonIn = DemoItemAnimation(button, DemoItemAnimation.ANIM_IN)
        buttonIn.setDuration(1800 * Colors.animSpeedButtons)
        buttonIn.setStartPos(QtCore.QPointF(-iw, Colors.contentStartY + Colors.contentHeight - 35))
        buttonIn.setPosAt(0.5, QtCore.QPointF(-iw, Colors.contentStartY + Colors.contentHeight - 35))
        buttonIn.setPosAt(0.7, QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 35))
        buttonIn.setPosAt(1.0, QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 26))
        movieIn.append(buttonIn)

        # Create out-animation.
        buttonOut = DemoItemAnimation(button, DemoItemAnimation.ANIM_OUT)
        buttonOut.hideOnFinished = True
        buttonOut.setDuration(400 * Colors.animSpeedButtons)
        buttonOut.setStartPos(QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 26))
        buttonOut.setPosAt(1.0, QtCore.QPointF(-iw, Colors.contentStartY + Colors.contentHeight - 26))
        movieOut.append(buttonOut)

        if movieShake is not None:
            shakeAnim = DemoItemAnimation(button, DemoItemAnimation.ANIM_UNSPECIFIED)
            shakeAnim.timeline.setCurveShape(QtCore.QTimeLine.LinearCurve)
            shakeAnim.setDuration(650)
            shakeAnim.setStartPos(buttonIn.posAt(1.0))
            shakeAnim.setPosAt(0.60, buttonIn.posAt(1.0))
            shakeAnim.setPosAt(0.70, buttonIn.posAt(1.0) + QtCore.QPointF(-3, 0))
            shakeAnim.setPosAt(0.80, buttonIn.posAt(1.0) + QtCore.QPointF(2, 0))
            shakeAnim.setPosAt(0.90, buttonIn.posAt(1.0) + QtCore.QPointF(-1, 0))
            shakeAnim.setPosAt(1.00, buttonIn.posAt(1.0))
            movieShake.append(shakeAnim)

    def createLowRightButton(self, label, type, movieIn, movieOut, movieShake):
        item = TextButton(label, TextButton.RIGHT, type, self.window.scene,
                self.window.mainSceneRoot, TextButton.PANEL)
        item.setRecursiveVisible(False)
        item.setZValue(10)

        sw = self.window.scene.sceneRect().width()
        xOffset = 70

        # Create in-animation.
        anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_IN)
        anim.setDuration(1800 * Colors.animSpeedButtons)
        anim.setStartPos(QtCore.QPointF(sw, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.5, QtCore.QPointF(sw, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.7, QtCore.QPointF(xOffset + 535, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(1.0, QtCore.QPointF(xOffset + 535, Colors.contentStartY + Colors.contentHeight - 26))
        movieIn.append(anim)

        # Create out-animation.
        anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_OUT)
        anim.hideOnFinished = True
        anim.setDuration(400 * Colors.animSpeedButtons)
        anim.setStartPos(QtCore.QPointF(xOffset + 535, Colors.contentStartY + Colors.contentHeight - 26))
        anim.setPosAt(1.0, QtCore.QPointF(sw, Colors.contentStartY + Colors.contentHeight - 26))
        movieOut.append(anim)

    def createLowRightLeafButton(self, label, xOffset, type, movieIn, movieOut, movieShake):
        item = TextButton(label, TextButton.RIGHT, type, self.window.scene,
                self.window.mainSceneRoot, TextButton.PANEL)
        item.setRecursiveVisible(False)
        item.setZValue(10)

        sw = self.window.scene.sceneRect().width()
        sh = self.window.scene.sceneRect().height()

        # Create in-animation.
        anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_IN)
        anim.setDuration(1050 * Colors.animSpeedButtons)
        anim.setStartPos(QtCore.QPointF(sw, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.10, QtCore.QPointF(sw, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.30, QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.35, QtCore.QPointF(xOffset + 30, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.40, QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.45, QtCore.QPointF(xOffset + 5, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(0.50, QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 35))
        anim.setPosAt(1.00, QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 26))
        movieIn.append(anim)

        # Create out-animation.
        anim = DemoItemAnimation(item, DemoItemAnimation.ANIM_OUT)
        anim.hideOnFinished = True
        anim.setDuration(300 * Colors.animSpeedButtons)
        anim.setStartPos(QtCore.QPointF(xOffset, Colors.contentStartY + Colors.contentHeight - 26))
        anim.setPosAt(1.0, QtCore.QPointF(xOffset, sh))
        movieOut.append(anim)

    def createInfo(self, item, name):
        movie_in = self.score.insertMovie(name)
        movie_out = self.score.insertMovie(name + ' -out')
        item.setZValue(8)
        item.setRecursiveVisible(False)

        xOffset = 230.0
        infoIn = DemoItemAnimation(item, DemoItemAnimation.ANIM_IN)
        infoIn.timeline.setCurveShape(QtCore.QTimeLine.LinearCurve)
        infoIn.setDuration(650)
        infoIn.setStartPos(QtCore.QPointF(self.window.scene.sceneRect().width(), Colors.contentStartY))
        infoIn.setPosAt(0.60, QtCore.QPointF(xOffset, Colors.contentStartY))
        infoIn.setPosAt(0.70, QtCore.QPointF(xOffset + 20, Colors.contentStartY))
        infoIn.setPosAt(0.80, QtCore.QPointF(xOffset, Colors.contentStartY))
        infoIn.setPosAt(0.90, QtCore.QPointF(xOffset + 7, Colors.contentStartY))
        infoIn.setPosAt(1.00, QtCore.QPointF(xOffset, Colors.contentStartY))
        movie_in.append(infoIn)

        infoOut = DemoItemAnimation(item, DemoItemAnimation.ANIM_OUT)
        infoOut.timeline.setCurveShape(QtCore.QTimeLine.EaseInCurve)
        infoOut.setDuration(300)
        infoOut.hideOnFinished = True
        infoOut.setStartPos(QtCore.QPointF(xOffset, Colors.contentStartY))
        infoOut.setPosAt(1.0, QtCore.QPointF(-600, Colors.contentStartY))
        movie_out.append(infoOut)

    def createTicker(self):
        if Colors.noTicker:
            return

        movie_in = self.score.insertMovie('ticker')
        movie_out = self.score.insertMovie('ticker -out')
        movie_activate = self.score.insertMovie('ticker -activate')
        movie_deactivate = self.score.insertMovie('ticker -deactivate')

        self.ticker = ItemCircleAnimation(self.window.scene)
        self.ticker.setZValue(50)
        self.ticker.hide()

        # Move ticker in.
        qtendpos = 485
        qtPosY = 120
        self.tickerInAnim = DemoItemAnimation(self.ticker,
                DemoItemAnimation.ANIM_IN)
        self.tickerInAnim.setDuration(500)
        self.tickerInAnim.setStartPos(QtCore.QPointF(self.window.scene.sceneRect().width(), Colors.contentStartY + qtPosY))
        self.tickerInAnim.setPosAt(0.60, QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        self.tickerInAnim.setPosAt(0.70, QtCore.QPointF(qtendpos + 30, Colors.contentStartY + qtPosY))
        self.tickerInAnim.setPosAt(0.80, QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        self.tickerInAnim.setPosAt(0.90, QtCore.QPointF(qtendpos + 5, Colors.contentStartY + qtPosY))
        self.tickerInAnim.setPosAt(1.00, QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        movie_in.append(self.tickerInAnim)

        # Move ticker out.
        qtOut = DemoItemAnimation(self.ticker, DemoItemAnimation.ANIM_OUT)
        qtOut.hideOnFinished = True
        qtOut.setDuration(500)
        qtOut.setStartPos(QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        qtOut.setPosAt(1.00, QtCore.QPointF(self.window.scene.sceneRect().width() + 700, Colors.contentStartY + qtPosY))
        movie_out.append(qtOut)

        # Move ticker in on activate.
        qtActivate = DemoItemAnimation(self.ticker)
        qtActivate.setDuration(400)
        qtActivate.setStartPos(QtCore.QPointF(self.window.scene.sceneRect().width(), Colors.contentStartY + qtPosY))
        qtActivate.setPosAt(0.60, QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        qtActivate.setPosAt(0.70, QtCore.QPointF(qtendpos + 30, Colors.contentStartY + qtPosY))
        qtActivate.setPosAt(0.80, QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        qtActivate.setPosAt(0.90, QtCore.QPointF(qtendpos + 5, Colors.contentStartY + qtPosY))
        qtActivate.setPosAt(1.00, QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        movie_activate.append(qtActivate)

        # Move ticker out on deactivate.
        qtDeactivate = DemoItemAnimation(self.ticker)
        qtDeactivate.hideOnFinished = True
        qtDeactivate.setDuration(400)
        qtDeactivate.setStartPos(QtCore.QPointF(qtendpos, Colors.contentStartY + qtPosY))
        qtDeactivate.setPosAt(1.00, QtCore.QPointF(qtendpos, 800))
        movie_deactivate.append(qtDeactivate)

    def createUpnDownButtons(self):
        xOffset = 15.0
        yOffset = 450.0

        self.upButton = TextButton("", TextButton.LEFT, MenuManager.UP,
                self.window.scene, self.window.mainSceneRoot, TextButton.UP)
        self.upButton.prepare()
        self.upButton.setPos(xOffset, yOffset)
        self.upButton.setState(TextButton.DISABLED)

        self.downButton = TextButton("", TextButton.LEFT, MenuManager.DOWN,
                self.window.scene, self.window.mainSceneRoot, TextButton.DOWN)
        self.downButton.prepare()
        self.downButton.setPos(xOffset + 10 + self.downButton.sceneBoundingRect().width(), yOffset)

        movieShake = self.score.insertMovie('upndown -shake')

        shakeAnim = DemoItemAnimation(self.upButton,
                DemoItemAnimation.ANIM_UNSPECIFIED)
        shakeAnim.timeline.setCurveShape(QtCore.QTimeLine.LinearCurve)
        shakeAnim.setDuration(650)
        shakeAnim.setStartPos(self.upButton.pos())
        shakeAnim.setPosAt(0.60, self.upButton.pos())
        shakeAnim.setPosAt(0.70, self.upButton.pos() + QtCore.QPointF(-2, 0))
        shakeAnim.setPosAt(0.80, self.upButton.pos() + QtCore.QPointF(1, 0))
        shakeAnim.setPosAt(0.90, self.upButton.pos() + QtCore.QPointF(-1, 0))
        shakeAnim.setPosAt(1.00, self.upButton.pos())
        movieShake.append(shakeAnim)

        shakeAnim = DemoItemAnimation(self.downButton,
                DemoItemAnimation.ANIM_UNSPECIFIED)
        shakeAnim.timeline.setCurveShape(QtCore.QTimeLine.LinearCurve)
        shakeAnim.setDuration(650)
        shakeAnim.setStartPos(self.downButton.pos())
        shakeAnim.setPosAt(0.60, self.downButton.pos())
        shakeAnim.setPosAt(0.70, self.downButton.pos() + QtCore.QPointF(-5, 0))
        shakeAnim.setPosAt(0.80, self.downButton.pos() + QtCore.QPointF(-3, 0))
        shakeAnim.setPosAt(0.90, self.downButton.pos() + QtCore.QPointF(-1, 0))
        shakeAnim.setPosAt(1.00, self.downButton.pos())
        movieShake.append(shakeAnim)

    def createBackButton(self):
        backIn = self.score.insertMovie('back -in')
        backOut = self.score.insertMovie('back -out')
        backShake = self.score.insertMovie('back -shake')
        self.createLowLeftButton("Back", MenuManager.ROOT, backIn, backOut,
                backShake, Colors.rootMenuName)
class Game:
    clock = pygame.time.Clock()
    pockets = {
        "ur_pocket": [Vec2D(UR_POCKET), Vec2D(125, 94), Vec2D(113, 78), Vec2D(143, 75), Vec2D(128, 63)],
        "ul_pocket": [Vec2D(UL_POCKET), Vec2D(125, 480), Vec2D(113, 495), Vec2D(143, 498), Vec2D(128, 510)],
        "dl_pocket": [Vec2D(DL_POCKET), Vec2D(974, 480), Vec2D(986, 495), Vec2D(956, 498), Vec2D(971, 510)],
        "dr_pocket": [Vec2D(DR_POCKET), Vec2D(956, 75), Vec2D(971, 63), Vec2D(974, 94), Vec2D(986, 79)],
        "ml_pocket": [Vec2D(ML_POCKET), Vec2D(530, 498), Vec2D(539, 510), Vec2D(568, 498), Vec2D(560, 510)],
        "mr_pocket": [Vec2D(MR_POCKET), Vec2D(530, 75), Vec2D(539, 63), Vec2D(568, 75), Vec2D(560, 63)],
    }

    def __init__(self):
        self.moving_balls = deque([])
        self.hitted_balls = deque([])
        self.potted = []
        pygame.display.set_caption("Cool Snooker")
        self.table = pygame.image.load("Snooker_table3.png")
        self.white_ball = balls.WhiteBall(coords=POS_WHITE)
        self.redball1 = balls.RedBall(coords=POS_RED1)
        self.redball2 = balls.RedBall(coords=POS_RED2)
        self.redball3 = balls.RedBall(coords=POS_RED3)
        self.redball4 = balls.RedBall(coords=POS_RED4)
        self.redball5 = balls.RedBall(coords=POS_RED5)
        self.redball6 = balls.RedBall(coords=POS_RED6)
        self.redball7 = balls.RedBall(coords=POS_RED7)
        self.redball8 = balls.RedBall(coords=POS_RED8)
        self.redball9 = balls.RedBall(coords=POS_RED9)
        self.redball10 = balls.RedBall(coords=POS_RED10)
        self.redball11 = balls.RedBall(coords=POS_RED11)
        self.redball12 = balls.RedBall(coords=POS_RED12)
        self.redball13 = balls.RedBall(coords=POS_RED13)
        self.redball14 = balls.RedBall(coords=POS_RED14)
        self.redball15 = balls.RedBall(coords=POS_RED15)
        self.black = balls.ColorBall(coords=POS_BLACK, COLOR=BLACK, points=7)
        self.pink = balls.ColorBall(coords=POS_PINK, COLOR=PINK, points=6)
        self.blue = balls.ColorBall(coords=POS_BLUE, COLOR=BLUE, points=5)
        self.brown = balls.ColorBall(coords=POS_BROWN, COLOR=BROWN, points=4)
        self.green = balls.ColorBall(coords=POS_GREEN, COLOR=GREEN, points=3)
        self.yellow = balls.ColorBall(coords=POS_YELLOW, COLOR=YELLOW, points=2)
        self.first_player = Player("Player 1")
        self.second_player = Player("Player 2")
        self.all_balls = deque(
            [
                self.redball1,
                self.redball2,
                self.redball3,
                self.redball4,
                self.redball5,
                self.redball6,
                self.redball7,
                self.redball8,
                self.redball9,
                self.redball10,
                self.redball11,
                self.redball12,
                self.redball13,
                self.redball14,
                self.redball15,
                self.white_ball,
                self.black,
                self.pink,
                self.blue,
                self.brown,
                self.green,
                self.yellow,
            ]
        )
        self.cue = Cue()
        self.turn = self.first_player
        self.board_status = STATICK
        self.colol_order = iter([x for x in range(2, 8)])
        self.next_target_ball = next(self.colol_order)
        self.condition = STILL_RED
        self.score = Score()
        self.foul = False
        self.hit = False
        self.painter = Draw()

    def ball_update(self):
        for a in range(0, len(self.all_balls) - 1):
            for b in range(a + 1, len(self.all_balls)):
                ball, next_ball = self.all_balls[a], self.all_balls[b]
                delta = next_ball.coords - ball.coords
                if (next_ball.coords - ball.coords).length <= ball.RADIUS * 2:
                    if ball.velocity.length > 0 and next_ball.velocity.length > 0:
                        ball.coords += Vec2D.normalized(delta) * (delta.length - ball.RADIUS * 2)
                        next_ball.coords += Vec2D.normalized(-delta) * (delta.length - ball.RADIUS * 2)
                        self.ball_collision(ball, next_ball)
                    elif ball.velocity.length > 0:
                        if isinstance(ball, balls.WhiteBall):
                            self.hitted_balls.append(next_ball)
                        ball.coords += Vec2D.normalized(delta) * (delta.length - ball.RADIUS * 2)
                        self.ball_collision(ball, next_ball)
                    elif next_ball.velocity.length > 0:
                        if isinstance(next_ball, balls.WhiteBall):
                            self.hitted_balls.append(ball)
                        next_ball.coords += Vec2D.normalized(-delta) * (delta.length - ball.RADIUS * 2)
                        self.ball_collision(ball, next_ball)

    def balls_handler(self):
        for ball in self.all_balls:
            if ball.velocity.length > 0:
                ball.move(self.pockets)
            if ball.is_potted and ball not in self.potted:
                self.potted.append(ball)
            if ball.vizibility:
                self.painter.draw_balls(ball)

    def white_ball_grab(self):
        mouse_pos = Vec2D(pygame.mouse.get_pos())
        if (
            self.white_ball.coords.x - 8 < mouse_pos.x < self.white_ball.coords.x + 8
            and self.white_ball.coords.y - 8 < mouse_pos.y < self.white_ball.coords.y + 8
        ):
            for event in pygame.event.get():
                (mouse1, mouse2, mouse3) = pygame.mouse.get_pressed()
                if mouse1:
                    self.white_ball.grabed = True
                else:
                    self.white_ball.grabed = False
        if self.white_ball.grabed:
            self.white_ball.coords = mouse_pos

    def cue_handler(self):
        start_pos, end_pos = self.cue.get_cue_pos(self.white_ball.coords)
        self.painter.cue_draw(self.cue, start_pos, end_pos)
        keys = pygame.key.get_pressed()
        if keys[pygame.K_KP_ENTER]:
            new_velocity = Vec2D.normalized(start_pos - end_pos)
            force = Vec2D(self.white_ball.coords - start_pos).length
            self.white_ball.velocity = new_velocity * force ** 2 / MIN_HITTING_FORCE
            self.hit = True

    def if_statick_board(self):
        for ball in self.all_balls:
            if ball.velocity.length > 0 and ball not in self.moving_balls:
                self.moving_balls.append(ball)
            elif ball in self.moving_balls and ball.velocity.length == 0:
                self.moving_balls.remove(ball)
        if not self.moving_balls:
            self.board_status = STATICK
        else:
            self.board_status = NON_STATICK

    def potted_ball_handler(self, potted, color_points=None):
        red_ball = 0
        color_ball = 0
        points = 0
        if color_points is None:
            color_points = [0]
        else:
            color_points = color_points
        for ball in potted:
            if isinstance(ball, balls.WhiteBall):
                self.foul = True
            if isinstance(ball, balls.ColorBall):
                color_ball += 1
                color_points.append(ball.points)
                if self.turn.target != COLOR_TARGET:
                    self.foul = True
            if isinstance(ball, balls.RedBall):
                if self.turn.target != RED_TARGET:
                    self.foul = True
                red_ball += 1
                points += ball.points
            ball.velocity = Vec2D(0, 0)
            if isinstance(ball, balls.RedBall):
                self.all_balls.remove(ball)
                ball.is_potted = False
            else:
                self.ball_return(ball)
            ball.is_potted = False
        self.potted = []
        if color_ball > 1 or (red_ball > 0 and color_ball > 0):
            self.foul = True
        if self.foul is True:
            # print("Foul wrong ball potted")
            self.change_turn()
            if max(color_points) > FOUL_POINTS:
                self.turn.points += max(color_points)
            else:
                self.turn.points += FOUL_POINTS
        else:
            if self.turn.target == RED_TARGET:
                self.turn.points += points
            else:
                self.turn.points += max(color_points)
            self.turn.change_target()

    def game_handler(self):
        self.score.show_score(self.first_player, self.second_player, self.turn)
        self.ball_update()
        self.if_statick_board()
        self.check_condition()
        self.foul = False
        if self.board_status == STATICK:
            if not self.hitted_balls and self.hit is True and not self.potted:
                self.change_turn()
                self.turn.points += FOUL_POINTS
                # print("Foul no ball hit")
            self.hit = False
            self.cue_handler()
            if self.hitted_balls:
                if self.condition == STILL_RED:
                    if (isinstance(self.hitted_balls[0], balls.ColorBall) and self.turn.target != COLOR_TARGET) or (
                        isinstance(self.hitted_balls[0], balls.RedBall) and self.turn.target != RED_TARGET
                    ):
                        if not self.potted:
                            self.foul = True
                            self.change_turn()
                            # print("Foul wrong ball hit")
                            if self.hitted_balls[0].points > FOUL_POINTS:
                                self.turn.points += self.hitted_balls[0].points
                            else:
                                self.turn.points += FOUL_POINTS
                        else:
                            self.foul = True
                            points = [self.hitted_balls[0].points]
                            self.potted_ball_handler(self.potted, color_points=points)
                    if self.potted and self.foul is not True:
                        self.potted_ball_handler(self.potted)
                    elif self.foul is not True:
                        # print("No ball poted")
                        self.change_turn()
                else:
                    self.no_red_game_handler()
                self.hitted_balls = deque([])
            if self.potted:
                self.potted_ball_handler(self.potted)

    def change_turn(self):
        if self.turn == self.first_player:
            self.turn = self.second_player
        else:
            self.turn = self.first_player
        self.turn.target = RED_TARGET

    def ball_return(self, potted_ball):
        potted_ball.vizibility = True
        returning_pos = Vec2D(potted_ball.pos)
        color_balls_pos = [x.pos for x in self.all_balls if isinstance(x, balls.ColorBall)]
        empty_place = False
        my_place_taken = self.chek_for_place(potted_ball)
        if my_place_taken is True:
            for position in color_balls_pos:
                empty_position = self.chek_for_place(potted_ball, pos=position)
                if empty_position is not True:
                    empty_place = True
                    returning_pos = position
                    break
        if my_place_taken is True and empty_place is not True:
            found_place = False
            while found_place is not True:
                flag = self.chek_for_place(potted_ball, pos=returning_pos)
                if flag is not True:
                    found_place = True
                    break
                returning_pos.x += 1
            potted_ball.coords = returning_pos
        else:
            potted_ball.coords = returning_pos

    def chek_for_place(self, potted_ball, pos=None):
        if pos is None:
            pos = potted_ball.pos
        for ball in self.all_balls:
            if ball is not potted_ball:
                delta = ball.coords - pos
                if delta.length < ball.RADIUS * 2:
                    return True
        return False

    def check_condition(self):
        flag = True
        for ball in self.all_balls:
            if isinstance(ball, balls.RedBall):
                flag = False
                break
        if flag:
            if self.turn.target == COLOR_TARGET:
                self.condition = STILL_RED
            else:
                self.condition = RED_FREE

    def no_red_game_handler(self):
        points = [0]
        if self.hitted_balls[0].points == self.next_target_ball:
            if self.potted:
                if len(self.potted) > 1:
                    # print("Foul more then 1 colorball potted")
                    self.change_turn()
                    for ball in self.potted:
                        points.append(ball.points)
                        self.ball_return(ball)
                        ball.is_potted = False
                    self.potted = []
                    if max(points) > FOUL_POINTS:
                        self.turn.points += max(points)
                    else:
                        self.turn.points += FOUL_POINTS
                else:
                    if self.potted[0].points == self.next_target_ball:
                        self.turn.points += self.potted[0].points
                        self.all_balls.remove(self.potted[0])
                        try:
                            self.next_target_ball = next(self.colol_order)
                        except:
                            self.next_target_ball = False
                            # print("Game finished")
                    else:
                        # print("Foul wrong colorball potted")
                        self.change_turn()
                        if self.potted[0].points > FOUL_POINTS:
                            self.turn.points += self.potted[0].points
                        else:
                            self.turn.points += FOUL_POINTS
                        self.ball_return(self.potted[0])
                    self.potted[0].is_potted = False
                    self.potted.remove(self.potted[0])
            else:
                # print("No colorball potted")
                self.change_turn()
        else:
            # print("Foul wrong colorball hited")
            self.change_turn()
            if self.potted:
                for ball in self.potted:
                    points.append(ball.points)
                    self.ball_return(ball)
                    ball.is_potted = False
                self.potted = []
                points.append(self.hitted_balls[0].points)
                if max(points) > FOUL_POINTS:
                    self.turn.points += max(points)
                else:
                    self.turn.points += FOUL_POINTS
            else:
                if self.hitted_balls[0].points > FOUL_POINTS:
                    self.turn.points += self.hitted_balls[0].points
                else:
                    self.turn.points += FOUL_POINTS

    def ball_collision(self, ball, next_ball):
        delta = next_ball.coords - ball.coords
        unit_delta = Vec2D(delta / delta.get_length())
        unit_tangent = Vec2D(unit_delta.perpendicular())
        velocity_1_n = unit_delta.dot(ball.velocity)
        velocity_1_t = unit_tangent.dot(ball.velocity)
        velocity_2_n = unit_delta.dot(next_ball.velocity)
        velocity_2_t = unit_tangent.dot(next_ball.velocity)
        new_velocity_1_t = velocity_1_t
        new_velocity_2_t = velocity_2_t
        new_velocity_1_n = velocity_2_n
        new_velocity_2_n = velocity_1_n
        new_velocity_1_n = Vec2D(new_velocity_1_n * unit_delta)
        new_velocity_2_n = Vec2D(new_velocity_2_n * unit_delta)
        new_velocity_1_t = Vec2D(new_velocity_1_t * unit_tangent)
        new_velocity_2_t = Vec2D(new_velocity_2_t * unit_tangent)
        new_velocity_1 = Vec2D(new_velocity_1_n + new_velocity_1_t)
        new_velocity_2 = Vec2D(new_velocity_2_n + new_velocity_2_t)
        ball.velocity = new_velocity_1
        next_ball.velocity = new_velocity_2