Beispiel #1
0
    def __init__(self, game, gameView):
        super(GameWindow, self).__init__()

        stretchA = (1000 - 618) * (1000 - 618)
        stretchB = 1000000 - stretchA

        layout = QGridLayout(self)
        layout.setColumnStretch(0, stretchB)
        layout.setColumnStretch(1, stretchA)

        leftLayout = QGridLayout()
        leftLayout.setRowStretch(0, stretchB)
        leftLayout.setRowStretch(1, stretchA)
        rightLayout = QGridLayout()
        rightLayout.setRowStretch(0, stretchA)
        rightLayout.setRowStretch(1, stretchB)
        layout.addLayout(leftLayout, 0, 0)
        layout.addLayout(rightLayout, 0, 1)

        self.game = game
        self.game.playersUpdated.connect(self._onPlayersUpdated)

        gameView.player = game.connectionManager.player
        gameView.attackInitiated.connect(self.game._onAttackInitiated)

        self.gameView = GameViewWrapper(gameView)
        self.eventBox = EventBox()
        self.countryBox = CountryInfoBox(self)
        self.statBox = StatBox(gameView)

        self.lose = Title('YOU LOSE', 100)
        self.win = Title('YOU WIN', 100)
        self.lose.setParent(self)
        self.win.setParent(self)
        self.lose.raise_()
        self.win.raise_()
        self.lose.hide()
        self.win.hide()

        self.eventBox.setColor(QColor(Qt.black))
        self.countryBox.setColor(QColor(Qt.gray))
        self.statBox.setColor(QColor(Qt.gray))

        leftLayout.addWidget(self.gameView, 0, 0)
        leftLayout.addWidget(self.eventBox, 1, 0)
        rightLayout.addWidget(self.statBox, 0, 0)
        rightLayout.addWidget(self.countryBox, 1, 0)

        gameView.hoverCountry.connect(self.countryBox.updateCountry)
        gameView.ownerChanged.connect(self.statBox.refresh)

        game.gameEvent.connect(self.eventBox.addEvent)
        game.gameLose.connect(self._triggerLose)
        game.gameWin.connect(self._triggerWin)
Beispiel #2
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setFixedSize(MainWindow.WIDTH, MainWindow.HEIGHT)

        self.mainTitle = Title('Distributed Real-time Risk', 36)
        self.subTitle = Title(' ' * 36 + 'Team 23', 20)

        layout = QGridLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        assert LeftPanel.OFFSET_Y == MainFrame.OFFSET_Y
        assert LeftPanel.HEIGHT == MainFrame.HEIGHT
        assert LeftPanel.OFFSET_Y + LeftPanel.HEIGHT == BottomPanel.OFFSET_Y
        assert BottomPanel.OFFSET_Y + BottomPanel.HEIGHT == MainWindow.HEIGHT
        layout.setRowStretch(0, LeftPanel.OFFSET_Y)
        layout.setRowStretch(1, LeftPanel.HEIGHT)
        layout.setRowStretch(2, BottomPanel.HEIGHT)

        assert LeftPanel.WIDTH + MainFrame.WIDTH == MainWindow.WIDTH
        layout.setColumnStretch(0, LeftPanel.WIDTH)
        layout.setColumnStretch(1, MainFrame.WIDTH)

        self.leftPanel = LeftPanel()
        self.bottomPanel = BottomPanel()
        self.mainFrame = MainFrame()
        layout.addWidget(self.leftPanel, 1, 0)
        layout.addWidget(self.bottomPanel, 2, 0, 1, -1)
        layout.addWidget(self.mainFrame, 1, 1)

        self.bottomPanel.gameHallControl.backButtonClicked.connect(
            self._onBackButtonClicked)
        self.bottomPanel.gameHallControl.createButtonClicked.connect(
            self._onCreateButtonClicked)
        self.bottomPanel.gameHallControl.joinButtonClicked.connect(
            self._onJoinButtonClicked)
        self.bottomPanel.gameRoomControl.backButtonClicked.connect(
            self._onBackButtonClicked)
        self.bottomPanel.gameRoomControl.startButtonClicked.connect(
            self._onStartButtonClicked)
        self.leftPanel.gameHallPanel.mapList.mapSelected.connect(
            self._onMapSelected)
        self.leftPanel.gameHallPanel.gameList.gameSelected.connect(
            self._onGameSelected)

        self.selectedMap = None
        self.selectedGameLoader = None
        self.selectedGame = None

        self.state = MainWindow.STATE_NONE
        self.initialAnimationStarted = False
        QMetaObject.invokeMethod(self, '_startAnimation', Qt.QueuedConnection)
Beispiel #3
0
def screen_update(screen, my_settings, ship, bullets, aliens, stats,
                  play_button, sb, bg, pause_btn, end_title, support,
                  score_display):
    # 关于背景图片
    screen.fill(0)
    screen.blit(bg, (0, 0))
    pause_btn.draw_pause_btn()

    ship.draw_ship()

    for bullet in bullets.sprites():  #很多的在这个编组里的子弹需要被一个个打印出来
        if stats.game_bullet_active:
            bullet.draw_bullet_up()
        else:
            bullet.draw_bullet()

    aliens.draw(screen)  #将某一个编组绘制出来的函数
    sb.show_score()
    if not stats.game_active and not stats.game_paused:
        screen.fill(0)
        screen.blit(bg, (0, 0))
        play_button.draw_replay_button()  #函数写在最后可以把按钮绘制在最上层
        end_title.draw_title()
        score_display.draw_score_title()
        h_score = Title(str(stats.high_score), screen)
        h_score.draw_high_score()

    support.draw_support()

    pygame.display.flip()  #让绘制出来的函数可见
Beispiel #4
0
def main():
    # 初期化
    pygame.init()
    pygame.mixer.init()

    # 画面生成
    pygame.display.set_mode((w, h), 0, 32)
    screen = pygame.display.get_surface()
    pygame.display.set_caption('Dangomushi')

    title = None
    gs = None
    scene = SC_Title

    # ゲームループ
    while True:
        # タイトル
        if scene == SC_Title:
            if title == None:
                title = Title(screen)
            title.Update()
            title.Draw()
            if title.finished:
                scene = SC_GetStar
                title = None

        # 星集め
        elif scene == SC_GetStar:
            if gs == None:
                gs = GetStar(screen)
            gs.Update()
            gs.Draw()
            if gs.finished:
                scene = SC_Title
                gs = None
Beispiel #5
0
    def game_over(self):
        """Go to intermediate screen then return to title
        """

        title_screen = Title(self)
        info_screen = InfoScreen(self, self.score, '', title_screen)
        self.change_state(info_screen)
Beispiel #6
0
 def get_titles(self, **kwargs) -> List[Title]:
   """
   Get data for multiple titles by searching by partial title and/or director matches.
   """
   results = []
   query_addon = []
   query_params = []
   for key, val in kwargs.items():
     if val:
       query_addon.append(f"{key} LIKE ?")
       query_params += ['%'+val+'%']
   if query_addon:
     query_addon = " WHERE " + " AND ".join(query_addon)
   else:
     query_addon = ""
   db_conn = sqlite3.connect(self.db_file)
   with db_conn:
     cur = db_conn.cursor()
     query = cur.execute("SELECT * FROM titles" + query_addon, query_params)
     colnames = [des[0] for des in query.description]
     for row in cur.fetchall():
       title = {}
       for i in range(len(colnames)):
         title[colnames[i]] = row[i] or ""
       try:
         results.append(Title(**title))
       except ValidationError as ve:
         self.logger.error(ve.errors())
   return results
Beispiel #7
0
def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    # start_game = False
    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("Super Pong 64")

    start_game = False

    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats, "")
    title = Title(ai_settings, screen, "")

    # make the left paddle
    left_paddle = Left_Paddle(ai_settings, screen)
    right_paddle = Right_Paddle(ai_settings, screen)
    bottom_paddle = Bottom_Paddle(ai_settings, screen)
    top_paddle = Top_Paddle(ai_settings, screen)
    top_left = Top_Left(ai_settings, screen)
    center_line = Center_Line(ai_settings, screen)
    bottom_right = Bottom_Right(ai_settings, screen)
    balls = Group()

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

    # Start the main loop for the game
    while True:
        title.prep_title("")
        title.prep_rules("")
        gf.check_events(ai_settings, screen, stats, sb, play_button,
                        left_paddle, top_left, bottom_paddle, balls)

        if stats.game_active:

            left_paddle.update(ai_settings)
            right_paddle.update(ai_settings, balls)
            bottom_paddle.update(ai_settings)
            top_paddle.update(ai_settings, balls)
            bottom_right.update(ai_settings, balls)
            top_left.update(ai_settings)

            gf.update_balls(ai_settings, stats, screen, sb, left_paddle,
                            right_paddle, bottom_paddle, top_paddle, top_left,
                            bottom_right, balls)

            gf.update_top_paddle(ai_settings, top_paddle)
            gf.update_bottom_right(ai_settings, bottom_right)
            gf.update_right_paddle(ai_settings, right_paddle)

        gf.update_screen(ai_settings, screen, stats, sb, title, left_paddle,
                         right_paddle, bottom_paddle, center_line, top_paddle,
                         top_left, bottom_right, balls, play_button)
Beispiel #8
0
    def __init__(self):
        self.system = platform.system()

        pygame.init()
        pygame.display.set_caption('Flappy Bird')

        self.FPS = 55

        self.SCREEN_WIDTH = 1000
        self.SCREEN_HEIGHT = 563
        self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))

        self.sliding_background = SlidingBackground(self.screen)

        if self.system == 'Linux':
            self.flappy_bird_title = Title(self.screen, r'images/title2.0.png', 466, 137, 50)
        else:
            self.flappy_bird_title = Title(self.screen, r'images\title2.0.png', 466, 137, 50)

        if self.system == 'Linux':
            self.game_over_title = Title(self.screen, r'images/game_over2.0.png', 383, 90, 50)
        else:
            self.game_over_title = Title(self.screen, r'images\game_over2.0.png', 383, 90, 50)

        if self.system == 'Linux':
            self.start_image_button = ImageButton(self.screen, r'images/start_button3.0.png', 183, 109, 400)
        else:
            self.start_image_button = ImageButton(self.screen, r'images\start_button3.0.png', 183, 109, 400)

        self.scoreboard = ScoreBoard(self.screen)

        self.retry_button = Button(self.screen, 425, 'Retry')

        self.bird = Bird(self.screen)

        # True until reset in pressed
        self.game_active = False

        # True until obstacle was hit
        self.game_lost = False

        self.score = 0
        self.create_best_score_file()
        self.get_best_score()
Beispiel #9
0
    def __init__(self):
        pyxel.init(160, 120, caption="Kotonoha Run")
        pyxel.load(os.getcwd() + "/my_resource.pyxel")

        self.gama_state = GamaState.Title
        self.title = Title()
        self.gama_main = GamaMain()
        self.gama_result = GamaResult()

        pyxel.run(self.Update, self.Draw)
Beispiel #10
0
def _generate_title_morphs(path, title_name):
    title = Title(title_name)

    if os.path.isfile(path):
        title.find_morphs_from_file(path)
    else:
        for filename in os.listdir(path):
            if os.path.isfile(os.path.join(path, filename)):
                title.find_morphs_from_file(os.path.join(path, filename))

    return title
Beispiel #11
0
 def __init__(self):
     State.__init__(self)
     self.next_state = Title()
     self.screen.fill((125, 125, 125))
     self.timer = timer.Timer(2)
     self.image = image_handling.get_image('img/splashscreen/splash.png')
     self.alpha = 0
     self.image.set_alpha(0)
     self.image = pygame.transform.scale(self.image, self.screen.get_size())
     self.img_pos = image_handling.center(self.image.get_size(),
                                          self.screen.get_size())
     self.fade = False
     self.upscreen = True
Beispiel #12
0
    def __init__(self, parent):
        super(IntroFrame, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 15, 20, 20)

        self.title = Title('', 23)
        titleLayout = QHBoxLayout()
        titleLayout.setAlignment(Qt.AlignTop)
        titleLayout.addWidget(QLabel(' ' * 5))
        titleLayout.addWidget(self.title, 1)
        layout.addLayout(titleLayout, 0)

        self.loading = Loading(200)
        self.loading.hide()
        layout.addWidget(self.loading, 1, Qt.AlignCenter)
def run_game():
    #Initialize pygame, settings, and screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    pygame.mixer.music.load('sounds/background.mp3')
    pygame.mixer.music.play(-1)

    #Make the play button
    play_button = Button(ai_settings, screen, "Play Game")
    hs_button = Button2(ai_settings, screen, "High Scores")
    title = Title(ai_settings, screen)
    title2 = Title2(ai_settings, screen)

    #Create an instance to store game stats and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #Make a ship, a group of bullets, a group of bunkers, and a group of aliens
    ship = Ship(ai_settings, screen)
    bullets = Group()
    abullets = Group()
    aliens = Group()
    bunkers = Group()

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

    #Create the bunkers
    gf.create_bunker_rows(ai_settings, screen, bunkers)

    #Start the main loop for the game
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, hs_button,
                        ship, aliens, bullets)

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

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button, hs_button, title, title2, bunkers)
Beispiel #14
0
def init():
    global titles

    loaded_titles = None

    try:
        try:
            with open(file_name, 'rb') as f:
                loaded_titles = pickle.load(f)
        except FileNotFoundError:
            open(file_name, 'wb+')
        if loaded_titles is not None:
            print("Loaded from cache")
            titles = loaded_titles
            return
    except ValueError:
        print("Cannot read json")

    print("Start generating:", strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
    print("Fetching popular started...:",
          strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
    imdb_manager.fetch_popular_titles()
    print("Fetching popular ended...:",
          strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
    popular_titles = imdb_manager.title_id_list

    total_images_count = 0
    movies_count = 0

    for title in popular_titles:
        images_list = get_canonical_images(
            imdb.get_title_images(title.title_id))
        total_images_count += len(images_list)
        movies_count += 1
        if len(images_list) > 0:
            titles.append(Title(title.name, title.year, images_list))

    with open(file_name, 'wb') as f:
        pickle.dump(titles, f, pickle.HIGHEST_PROTOCOL)

    print("Movies with images:", str(len(titles)))
    print("Total images:", str(total_images_count))
    print("End generating:", strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
Beispiel #15
0
    def __init__(self, textSource):
        self.textSource = textSource
        self.speedLimit = 70
        self.clock = pygame.time.Clock()
        self.screenRect = Rect(0, 0, 640, 480)
        self.screen = pygame.display.set_mode(self.screenRect.size)
        self.background = pygame.Surface(self.screenRect.size).convert()
        self.elements = pygame.sprite.RenderUpdates()
        self.inputData = InputData(textSource)
        self.music = RunMusic()
        self.title = Title()
        self.game_over = True
        self.elements.add(self.title)
        self.background.fill((255, 255, 255))
        self.screen.blit(self.background, (0, 0))

        self.coverText = self.inputData.getWelcomeWords()
        pygame.display.set_caption('王者打字游戏')
        pygame.display.update()
Beispiel #16
0
 def get_title(self, id: str) -> Title:
   """
   Get title data by id, which is matched to id in the titles table
   """
   db_conn = sqlite3.connect(self.db_file)
   with db_conn:
     cursor = db_conn.cursor()
     query = cursor.execute("SELECT * FROM titles WHERE id = ?", [id])
     colnames = [des[0] for des in query.description]
     result = cursor.fetchone()
     if not result:
       return None
     title = {}
     for i in range(len(colnames)):
       title[colnames[i]] = result[i] or ""
   try:
     return Title(**title)
   except ValidationError as ve:
     self.logger.error(ve.errors())
Beispiel #17
0
def run_game():
    #Initialize the game and create a screen object
    pygame.init()
    game_settings = Settings()
    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption('Letters Killer')

    #Intialize the statistics
    stats = Stats(game_settings)

    #Initialize all the sounds in need
    sounds = Sound(game_settings)

    #Initialize the falling targets
    targets = Group()

    #Initialize an aim
    aim = Aim(screen, game_settings)

    #Initialize a button
    button = Button(screen, game_settings)

    #Initialize the title
    title = Title(screen, game_settings)

    #Initialize the big man
    man = Man(screen, game_settings)
    while True:

        #Create a target with random value
        gf.create_targets(screen, game_settings, targets)

        #Check the events and responds
        gf.check_events(targets, game_settings, stats, button, aim, sounds,
                        title)

        #Update the screen
        gf.update_screen(screen, game_settings, stats, button, targets, aim,
                         title)
Beispiel #18
0
    def make_first_city(self, models):
        self.active = True
        r = lambda: random.randint(0, 255)
        self.color = '#%02X%02X%02X' % (r(), r(), r())
        new_culture = False
        self.food_limit = 750
        if self.culture == None:
            self.culture = Culture(self.color)
            new_culture = True
        self.name = self.culture.generate_name(models, "t")
        while len(self.name) < 6 or len(
                self.name
        ) > 10 or ' ' in self.name or '-' in self.name or ')' in self.name:
            self.name = self.culture.generate_name(models, "t")
        if new_culture:
            self.culture.name = self.name + "ian"
        self.leader = Character(models, self.culture, self, 40)
        ### CREATE TITLE
        self.title = Title(self.name, None, [], [self], 1)
        self.title.setGovFormGameStart(self.leader.focus)
        self.leader.titles.append(self.title)
        self.leader.refresh_fullname()
        self.chars.append(self.leader)
        for f in self.field.field_neighbor(10):
            if f.city is not None:
                if f.city.culture == None:
                    f.city.culture = self.culture
        for f in self.field.field_neighbor(1):
            if f.owner is not None:
                if not f.owner.active:
                    f.owner = self
                    self.territory.append(f)
            else:
                f.owner = self
                self.territory.append(f)

        self.calculate_values()
        self.detect_resources()
        self.pop = self.wealth * 10 + random.randint(-100, 100)
        self.wpc = self.wealth / self.pop
Beispiel #19
0
    def __init__(self, parent):
        super(DetailFrame, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 15, 20, 20)

        self.title = Title('', 23)
        titleLayout = QHBoxLayout()
        titleLayout.setAlignment(Qt.AlignTop)
        titleLayout.addWidget(QLabel(' ' * 5))
        titleLayout.addWidget(self.title, 1)
        layout.addLayout(titleLayout, 0)

        detailLayout = QGridLayout()
        detailLayout.setColumnStretch(0, self.width() * 0.618)
        detailLayout.setColumnStretch(1, self.width() * (1 - 0.618))

        self.preview = Preview()
        self.info = Info()
        detailLayout.addWidget(self.preview, 0, 0)
        detailLayout.addWidget(self.info, 0, 1)

        layout.addLayout(detailLayout, 1)
Beispiel #20
0
    def search_title_data(self, data):
        """
        Sort of a sub-method of add_title
        Scrapes pre-chosen websites for info about a title with
        the given details (name, year, type)
        :param data: (Title's name, Title's year, Title's Type)
                      Name: Name of the title
                      Year: Release year of the title (minimum search year)
                      Type: Type of the title

        Success:
            :returns: A title with all the data scraped online
            :rtype: Title
        Failure:
            :returns: Error message (Reason for failure)
            :rtype: str
        """
        data = Database.injection_arr(data)
        print("Adding title\n\tName: {}\n\tYear: {}\n\tType: {}".format(*data))
        data[0] = data[0].lower()
        title_type = data[2]
        titles = dict(
            self.cursor.execute("""SELECT name,
        date FROM {}""".format(TYPE_TO_TABLE[title_type])))
        for title, year in titles.items():
            if data[0] == title.lower() and data[1] == year.split("-")[0]:
                return "Exists"
        title = Title(*data)
        if title.error_flag:
            return "Error"
        links = list(
            self.cursor.execute("""SELECT
        imdb FROM {}""".format(TYPE_TO_TABLE[title_type])))
        links = [link[0] for link in links]  # That's just how it gets stuff
        print("LINKS:", repr(links))
        print("IMDB:", repr(title.imdb_page))
        if title.imdb_page in links:
            return "Exists"
        return title
Beispiel #21
0
    def fetch_popular_titles(cls):
        while cls.start_page < cls.max_pages_count:
            print("\n\npage =", cls.start_page)
            print("offset =", cls.offset)
            url = cls.update_url()

            http = urllib3.PoolManager()
            r = http.request('GET', url, headers=cls._headers)

            soup = BeautifulSoup(r.data, 'html.parser')
            results_table = soup.find('table', {'class': 'results'})
            tr_list = results_table.find_all('tr')
            tr_list.pop(0)
            cls.offset += cls._offset_increment_step
            cls.start_page += cls._page_increment_step
            for tr in tr_list:
                title_id = tr.find('span').attrs['data-tconst']
                title_year = tr.find('span', {
                    'class': 'year_type'
                }).text.replace('(', '').replace(')', '')
                title_name = tr.find_all('a')[1].text
                cls.title_id_list.append(
                    Title(title_id=title_id, name=title_name, year=title_year))
Beispiel #22
0
 def __init__(self):
     self.img = None
     self.legend = Legend()
     self.title = Title()
     self.autosize = App.cfg['image']['autosize']
     self.autosize_minpx = App.cfg['image']['autosize_minpx']
     self.basewidth = App.cfg['image']['basewidth']
     self.baseheight = App.cfg['image']['baseheight']
     self.padding = App.cfg['image']['padding']
     self.showborder = App.cfg['image']['border']
     self.showtitle = App.cfg['title']['show']
     self.showlegend = App.cfg['legend']['show']
     self.showgrid = App.cfg['axis']['grid']
     self.showaxis = App.cfg['axis']['show']
     self.showflat = App.cfg['image']['flatline']
     self.showtimestamp = App.cfg['image']['timestamp']
     self.timestampcolor = App.cfg['image']['timestampcolor']
     self.bordercolor = App.cfg['image']['bordercolor']
     self.streetcolor = App.cfg['image']['streetcolor']
     self.flatcolor = App.cfg['image']['flatcolor']
     self.gridcolor = App.cfg['axis']['gridcolor']
     self.axiscolor = App.cfg['axis']['color']
     self.axisfont = App.cfg['axis']['font']
     self.bgcolor = App.cfg['image']['bgcolor']
Beispiel #23
0
def run_game():
    #初始化
    pygame.init()

    #设置类的对象
    my_settings = Setting()
    screen = pygame.display.set_mode(
        (my_settings.screen_width, my_settings.screen_height))
    pygame.display.set_caption("the first of my game")

    #对象的创建

    play_button = Button('play', screen)  #按钮
    pause_btn = PauseBtn(screen)

    ship = Ship(my_settings, screen)
    aliens = Group()
    bullets = Group()
    stats = GameStats(my_settings)
    sb = ScoreBoard(screen, my_settings, stats)
    bg = pygame.image.load("./image/back4.png")
    sp = StartPage(screen)
    start_bg = pygame.image.load("./image/back4.png")
    title = Title("Maybe Our Game", screen)
    end_title = Title("HAAAAAAA YOU LOSE", screen)
    score_display = Title("YOUR SCORE:", screen)
    support = Support(screen, my_settings)

    # bgm 的创建
    pygame.mixer.init()
    bg_sound = pygame.mixer.Sound('./music/开头.mp3')
    bg_sound.play()

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

    SUPPLY_TIME = pygame.USEREVENT
    pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)

    while True:
        if stats.game_first_page:
            gf.check_events(ship, my_settings, screen, bullets, stats,
                            play_button, aliens, sb, bg_sound, pause_btn, sp,
                            SUPPLY_TIME, support)
            gf.first_page_show(screen, sp, start_bg, title)
        else:
            gf.check_events(ship, my_settings, screen, bullets, stats,
                            play_button, aliens, sb, bg_sound, pause_btn, sp,
                            SUPPLY_TIME, support)
            if stats.game_active and not stats.game_paused:
                ship.update()
                gf.update_aliens(
                    aliens,
                    my_settings,
                    ship,
                    stats,
                    bullets,
                    screen,
                    sb,
                )
                gf.bullet_update(bullets, aliens, screen, my_settings, ship,
                                 stats, sb)
                gf.support_upate(support, my_settings, ship, stats)
            gf.screen_update(screen, my_settings, ship, bullets, aliens, stats,
                             play_button, sb, bg, pause_btn, end_title,
                             support, score_display)
Beispiel #24
0
 def init_title_screen(self):
     title = Title(self.config, self.states)
     self.states.append(title)
    def bar_menu(self):

        # clear sprite groups for bar labels
        self.bartitles.empty()

        font = {"family": "Arial", "size": self.padding * 1.5}

        colors = {
            "background": (205, 205, 205),
            "selected": (200, 200, 150),
            "hover": (150, 200, 150),
            "error": (200, 150, 150),
            "text": (25, 25, 25)
        }

        colors_text = {
            "background": (225, 225, 225),
            "selected": (250, 250, 200),
            "hover": (200, 250, 200),
            "error": (250, 200, 200),
            "text": (75, 75, 75)
        }

        bar_selected = ""

        # find the selected bar
        for bar in self.bars:
            if bar.selected:
                bar_selected = bar

        if bar_selected:

            font["size"] = int(self.height / 80 * 2)

            padd = self.padding * 5
            xpos = padd + self.height / 8 * 3 + font[
                "size"] * 3 * 2 + self.bbarheight

            button_delete_rect = pygame.Rect(
                xpos, self.height - self.buttonheight - self.padding,
                self.bbarheight, self.buttonheight)

            self.menu.add(
                Button(font,
                       colors,
                       button_delete_rect,
                       "Delete",
                       "delete_bar",
                       id=4))

            # Name label
            font["size"] = int(self.padding * 1.5)
            self.bartitles.add(
                Title(font, colors, (xpos, self.height - self.bbarheight),
                      "Name:"))

            # Value label
            self.bartitles.add(
                Title(font, colors,
                      (xpos, self.height - self.bbarheight + font["size"] + 2),
                      "Value:"))

            # Name
            self.bartitles.add(
                Title(font, colors_text,
                      (xpos + self.padding * 6, self.height - self.bbarheight),
                      bar_selected.caption))

            # Value
            self.bartitles.add(
                Title(font, colors_text,
                      (xpos + self.padding * 6,
                       self.height - self.bbarheight + font["size"] + 2),
                      str(bar_selected.value)))
    def main_menu(self):
        # clear the GUI
        self.menu.empty()
        self.titles.empty()

        font = {"family": "Arial", "size": int(self.width / 80 * 2)}

        colors = {
            "background": (225, 225, 225),
            "selected": (250, 250, 200),
            "hover": (200, 250, 200),
            "error": (250, 200, 200),
            "text": (75, 75, 75)
        }

        xpos = self.padding
        input_caption_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            self.height / 8 * 3, self.buttonheight)
        input_caption = InputBox(font, colors, input_caption_rect, self.fps, 0)

        xpos += self.height / 8 * 3 + self.padding
        input_value_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            font["size"] * 3, self.buttonheight)
        input_value = InputBox(font, colors, input_value_rect, self.fps, 1)

        button_colors = {
            "background": (205, 205, 205),
            "selected": (200, 200, 150),
            "hover": (150, 200, 150),
            "error": (200, 150, 150),
            "text": (25, 25, 25)
        }

        xpos += font["size"] * 3 + self.padding
        button_submit_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            font["size"] * 3, self.buttonheight)
        button_submit = Button(font, button_colors, button_submit_rect, "Add",
                               "submit_values")

        xpos += font["size"] * 3 + self.padding
        button_save_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            self.bbarheight, self.buttonheight)
        button_save = Button(font,
                             button_colors,
                             button_save_rect,
                             "Save image",
                             "save_image",
                             id=3)

        self.menu.add(input_caption)
        self.menu.add(input_value)
        self.menu.add(button_submit)
        self.menu.add(button_save)

        self.titles.add(
            Title(font, colors,
                  (self.padding, self.width - self.bbarheight + self.padding),
                  "Caption:"))
        self.titles.add(
            Title(font, colors, (self.height / 8 * 3 + self.padding * 2,
                                 self.width - self.bbarheight + self.padding),
                  "Value:"))
Beispiel #27
0
 def __init__(self):
     GameManager.__init__(self, Title(self))
def run_game():

    # Initialize game and create a screen object.
    pygame.init()
    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("Alien Invasion")

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

    hi_button =  Button2(ai_settings, screen)

    # Create an instance to store game statistics.
    stats = GameStats(ai_settings)
    # foo = open("foo.txt", "w")
    # foo.write("0")
    # foo.close()
    fo = open("foo.txt", "r+")
    stats.high_score = int(fo.readline())
    stats.high_score2 = int(fo.readline())
    stats.high_score3 = int(fo.readline())
    fo.close()
    print("hiscore: " + str(stats.high_score))


    # Create an instance to store game statistics and create a scoreboard.
    sb = Scoreboard(ai_settings, screen, stats)
    title = Title(ai_settings, screen, "", stats)


    # Make a ship, a group of bullets, and a group of aliens.

    ship = Ship(ai_settings, screen)

    ufo = UFO(ai_settings, screen)

    # Make a group to store bullets in.
    # blue = Blue(ai_settings, screen)
    # red = Red(ai_settings, screen)
    # green = Green(ai_settings, screen)
    bullets = Group()
    alien_bullets = Group()
    aliens = Group()

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

    # Start the main loop for the game.
    while True:
        title.prep_title("")
        title.prep_rules("")
        title.prep_blue_msg("")
        title.prep_red_msg("")
        title.prep_green_msg("")
        gf.check_events(ai_settings, screen, stats, sb, play_button, hi_button, ship,
            aliens, bullets, alien_bullets)

        if stats.game_active:
            ship.update(clock)
            ufo.update()
            # ship.explode(hit)
            # if hit == True and ship.image == 'images/Ship Full.gif':
            #     ship.center_ship()
            # We update the aliens’ positions after the bullets have been updated,
            # because we’ll soon be checking to see whether any bullets hit any aliens.
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                bullets, alien_bullets)
            # print(len(bullets))
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                bullets, alien_bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                         ufo, title, bullets, alien_bullets, play_button,
                         hi_button)
Beispiel #29
0
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.bullets = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        self.evil_bullets = pygame.sprite.Group()
        
        self.a_map = World_map()
                
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width,self.settings.screen_height))
        pygame.display.set_caption("Invasion")
               
        self.level = 0
        self.stats = Stats(self)
        
        temp_x, temp_y = 200, 50
        temp_color = (0, 100, 0)
        temp_text_color =(255, 255, 255)
        self.play_button = Button(self, temp_x, temp_y, temp_color, temp_text_color, "PLAY")
        self.play_button.rect.y -= 65
        self.play_button._prep_msg("NEW GAME")
        
        
        temp_x, temp_y = 200, 50
        temp_color = (20, 40, 0)
        temp_text_color =(255, 255, 255)
        self.exit_button = Button(self, temp_x, temp_y, temp_color, temp_text_color, "EXIT")
        self.exit_button.rect.y += 185
        self.exit_button._prep_msg("EXIT")
        
        temp_x, temp_y = 200, 50
        temp_color = (80, 60, 0)
        temp_text_color =(255, 255, 255)
        self.title_button = Button(self, temp_x, temp_y, temp_color, temp_text_color, "TITLE")
        self.title_button.rect.y += 125
        self.title_button._prep_msg("TITLE")
        self.title = Title(self)
        self.title_active = False
        
        temp_x, temp_y = 200, 50
        temp_color = (150, 200, 0)
        temp_text_color =(255, 255, 255)
        self.help_button = Button(self, temp_x, temp_y, temp_color, temp_text_color, "HELP")
        self.help_button.rect.y += 65
        self.help_button._prep_msg("HELP")
        self.help_ = Help(self)
        self.help_active = False
        
        temp_x, temp_y = 200, 50
        temp_color = (150, 200, 0)
        temp_text_color =(255, 255, 255)
        self.back_button = Button(self, temp_x, temp_y, temp_color, temp_text_color, "BACK")
        self.back_button.rect.y += 185
        self.back_button._prep_msg("BACK")

        
        
        temp_x, temp_y = 250, 50
        temp_color = (0, 240, 0)
        temp_text_color =(255, 255, 255)
        self.restart_button = Button(self, temp_x, temp_y, temp_color, temp_text_color, "Restart level")
        
        temp_x, temp_y = 350, 50
        temp_color = (100, 100, 100)
        temp_text_color =(255, 0, 0)
        self.win_button = Button(self, temp_x, temp_y, temp_color, temp_text_color, "YOU ARE A WINNER!")
        
        self.myTank = Ship(self)
        self.myTank.live  = 0
        
        #interface
        self.liveboard = Lives(self)
        self.score = 0
        self.scoreboard = Score(self)

        self.image = pygame.image.load('images/brick_wall3.png')        
        self.rect = self.image.get_rect()
        
        self.aid = pygame.image.load('images/aid.png')   
Beispiel #30
0
 def title(self, text):
     self._title = Title(text)