Example #1
0
 def init(self):
     self.gameMode = 'Image'
     self.solve = False
     self.solveSteps = []
     self.width = 500
     self.height = 600
     Star.init()
     self.star = pygame.sprite.Group()
     self.hint = False
     self.gameWon = False
     self.rows = 3
     Block.init(self.rows)
     self.blocks = pygame.sprite.Group()
     self.puzzleWidth = 500
     self.blockWidth = self.puzzleWidth / self.rows
     self.boardL = self.rows**2 - 1
     for i in range(self.rows):
         for j in range(self.rows):
             #Not taking the last block, as it is supposed to be blank
             if i + j == (self.rows - 1) * 2:
                 continue
             #Calculating location of blocks and adding them to sprite group
             x = j * (self.blockWidth) + (self.blockWidth / 2)
             y = i * (self.blockWidth) + (self.blockWidth / 2)
             self.blocks.add(Block(x, y, self.rows))
     #Loading up the blank and adding it to sprite group
     Blank.init()
     blankInitial = self.puzzleWidth * (5 / 6)
     self.blocks.add(Blank(blankInitial, blankInitial, self.rows))
     #If the board that was created is not valid, make a new one until it is
     if not self.isValidBoard(self, Block.board):
         self.init(self)
         return
Example #2
0
def starscos():
    #Guardar las estrellas de Stars.txt.
    archivo = open("stars.txt", "r")
    stars = []
    mStars = {}
    for linea in archivo.readlines():
        data = linea.split(' ', 6)
        if (len(data) > 6):
            data[6] = data[6].replace('\n', '').split('; ')
            star = Star(data[0], data[1], data[2], data[3], data[4], data[5],
                        data[6])
            stars.append(star)
            for nombre in data[6]:
                mStars.setdefault(str(nombre), star)
        else:
            stars.append(
                Star(data[0], data[1], data[2], data[3], data[4], data[5],
                     None))
    archivo.close()

    #Guardar todas las posiciones en Diccionarios.
    basepath = 'constelaciones/'
    constelaciones = {}
    for entry in os.listdir(basepath):
        if os.path.isfile(os.path.join(basepath, entry)):
            constelacion = open('constelaciones/' + entry, "r")
            edges = []
            for linea in constelacion.readlines():
                edges.append(linea.replace('\n', '').split(','))
            constelacion.close()
            constelaciones.setdefault(
                str(entry[:entry.find('.txt')]).casefold(), edges)
    return {'stars': stars, 'mStars': mStars, 'constelaciones': constelaciones}
Example #3
0
    def read_sectors (self, sectors, pop_code, match):
        for sector in sectors:
            try:
                lines = [line for line in codecs.open(sector,'r', 'utf-8')]
            except (OSError, IOError):
                self.logger.error("sector file %s not found" % sector)
                continue
            
            sec = Sector (lines[3], lines[4])
            sec.filename = os.path.basename(sector)
            
            lineno = 0
            for line in lines:
                lineno += 1
                if line.startswith ('Hex'):
                    lineno += 1
                    break
                if line.startswith ('# Subsector'):
                    data = line[11:].split(':',1)
                    pos  = data[0].strip()
                    name = data[1].strip()
                    sec.subsectors[pos] = Subsector(name, pos, sec)
                if line.startswith ('# Alleg:'):
                    algCode = line[8:].split(':',1)[0].strip()
                    algName = line[8:].split(':',1)[1].strip().strip('"')
                    # Collapse same Aligned into one
                    if match == 'collapse':
                        algCode = AllyGen.same_align(algCode)
                        self.alg[algCode] = Allegiance(algCode, algName) 
                    elif match == 'separate':
                        base = AllyGen.same_align(algCode)
                        if base not in self.alg: self.alg[base] = Allegiance(base, algName)
                        if algCode not in self.alg: self.alg[algCode] = Allegiance(algCode, algName)
                        pass
                
            for line in lines[lineno:]:
                if line.startswith('#') or len(line) < 20: 
                    continue
                star = Star (line, self.starline, sec, pop_code)
                sec.worlds.append(star)
                sec.subsectors[star.subsector()].worlds.append(star)
                
                base = AllyGen.same_align(star.alg)
                if match == 'collapse':
                    self.alg[base].worlds.append(star)
                elif match == 'separate':
                    try: 
                        self.alg[star.alg].worlds.append(star)
                    except KeyError:
                        self.logger.error ("Allegiance %s is not in the %s sector file allegiance list" % (star.alg, sec))
                        raise SystemExit(3)
                    if base != star.alg:
                        self.alg[base].worlds.append(star)
                    
            
            self.sectors.append(sec)
            self.logger.info("Sector {} loaded {} worlds".format(sec, len(sec.worlds) ) )

        self.set_bounding_sectors()
        self.set_positions()
    def TestEquals(self):
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)
        star2 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)
        star3 = Star.parse_line_into_star(
            "0104 Shana Ma             E551112-7 Lo Po                { -3 } (301-3) [1113] B     - - 913 9  Im K2 IV M7 V     ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)

        self.assertEqual(star1, star2)
        self.assertNotEqual(star1, star3)
        self.assertNotEqual(star2, star3)
Example #5
0
    def TestEquals(self):
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)
        star2 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)
        star3 = Star.parse_line_into_star(
            "0104 Shana Ma             E551112-7 Lo Po                { -3 } (301-3) [1113] B     - - 913 9  Im K2 IV M7 V     ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)

        self.assertEqual(star1, star2)
        self.assertNotEqual(star1, star3)
        self.assertNotEqual(star2, star3)
Example #6
0
    def create_FallingObject(self, typ, minmax, speed, screen, info_x):

        if typ == "Star":
            return Star(minmax, speed, screen, info_x)

        if typ == "Asteroid":
            return Asteroid(minmax, speed, screen, info_x)
Example #7
0
def main():
    MODE = "random"
    fig = plt.figure()
    ax = plt.subplot(111)
    ax.set_title(MODE)

    if MODE == "random":
        N = 3
        stars = []
        randomvals = np.random.rand(N, 6)
        while any(
                any((impossiblepos(val1, val2) and val1 is val2)
                    for val2 in randomvals) for val1 in randomvals):
            randomvals = np.random.rand(N, 4)
            print("apprehended")
        for vals in randomvals:
            mass = 4
            color = np.random.rand(3)
            stars += [
                Star((WIDTH * 0.5 * (vals[0] - 0.5), HEIGHT * 0.5 *
                      (vals[1] - 0.5)), (0.00 * vals[2], 0.00 * vals[3]),
                     mass=mass,
                     facecolor=color)
            ]

    universe = Universe(stars, ax, dt=5e-3, trace=TRACE)
    mov = anim.FuncAnimation(fig,
                             universe.update,
                             frames=100,
                             interval=1000 * universe.dt,
                             blit=True)
    try:
        plt.show()
    except AttributeError:
        print("AtrributeError")
Example #8
0
 def _search_range(self, Hex, allyMap, starMap):
     from Star import Star
     newBridge = None
     checked = []
     for direction in xrange(6):
         checkHex = AllyGen._get_neighbor(Hex, direction)
         if starMap.get(checkHex, False):
             if self.are_allies(starMap[Hex], starMap[checkHex]):
                 checked.append(checkHex)
             continue
         if self.are_allies(starMap[Hex], allyMap.get(checkHex, None)):
             checked.append(checkHex)
             continue
         for second in xrange(6):
             searchHex = AllyGen._get_neighbor(checkHex, second)
             if searchHex in checked:
                 newBridge = None
                 continue
             if searchHex == Hex or Star.axial_distance(searchHex,
                                                        Hex) == 1:
                 continue
             if starMap.get(searchHex, False) and \
                     self.are_allies(starMap[Hex], starMap[searchHex]):
                 newBridge = checkHex
                 checked.append(checkHex)
     if newBridge:
         allyMap[newBridge] = starMap[Hex]
    def __init__(self, star_n, H, W):
        self.H = H
        self.W = W
        self.star_list = []  # 保存有宇宙内全部恒星的列表
        self.star_id = []  # 保存有宇宙内全部恒星ID的列表

        self.civi_list = []  # 保存有宇宙内全部文明的列表
        self.Civi_Gen = 0.001  # 每年,每个无主的恒星系诞生生命的概率
        self.civi_n = 0  # 迄今为止有多少文明出现

        self.army_list = []  # 保存有所有的军队情况,黑暗森林打击等等

        self.TC_interstellar = 1e3  # 星际时代的技术值门槛
        self.TC_super = 1e10  # 技术值超过这个,达到光速
        self.q = 0.1  # 反败为胜概率
        self.p = 0.5  # 准备好战争后生命损失减少
        self.brocast_d = 400  # 多少距离内的可以听到宇宙广播

        self.history = ""  # 宇宙历史事件

        # 初始随机分布有恒星系
        def random_init_resource_point():
            return np.power(10, np.random.uniform(low=5, high=15))

        def random_init_pos(H, W):
            return (np.random.rand() * H, np.random.rand() * W)

        for i in range(star_n):
            pos = random_init_pos(H, W)
            Init_Resource_Point = random_init_resource_point()
            st = Star(pos=pos, Init_Resource_Point=Init_Resource_Point)
            self.star_list.append(st)
            self.star_id.append(f"Star_{i}")
 def create_star(self, description:str, x_position:float, y_position:float, mass:float):
     """Creates a star and appends it to the list planetary_objects."""
     if self.validate_position(x_position, y_position) == False:
         raise ValueError("There is already a planetary object in this position.")
     new_star = Star(description, x_position, y_position, mass)
     self.planetary_objects.append(new_star)
     return new_star
Example #11
0
 def _search_range(self, Hex, allyMap, starMap):
     from Star import Star
     newBridge = None
     checked = []
     for direction in xrange(6):
         checkHex = AllyGen._get_neighbor(Hex, direction)
         if starMap.get(checkHex, False):
             if self.are_allies(starMap[Hex], starMap[checkHex]):
                 checked.append(checkHex)
             continue
         if self.are_allies(starMap[Hex], allyMap.get(checkHex, None)):
             checked.append(checkHex)
             continue
         for second in xrange(6):
             searchHex = AllyGen._get_neighbor(checkHex, second)
             if searchHex in checked:
                 newBridge = None
                 continue
             if searchHex == Hex or Star.axial_distance(searchHex, Hex) == 1:
                 continue
             if starMap.get(searchHex, False) and \
                     self.are_allies(starMap[Hex], starMap[searchHex]):
                 newBridge = checkHex
                 checked.append(checkHex)
     if newBridge:
         allyMap[newBridge] = starMap[Hex]
Example #12
0
    def read_sectors(self, sectors, pop_code, ru_calc):
        for sector in sectors:
            try:
                lines = [line for line in codecs.open(sector, 'r', 'utf-8')]
            except (OSError, IOError):
                self.logger.error("sector file %s not found" % sector)
                continue
            self.logger.debug('reading %s ' % sector)

            sec = Sector(lines[3], lines[4])
            sec.filename = os.path.basename(sector)

            for lineno, line in enumerate(lines):
                if line.startswith('Hex'):
                    break
                if line.startswith('# Subsector'):
                    data = line[11:].split(':', 1)
                    pos = data[0].strip()
                    name = data[1].strip()
                    sec.subsectors[pos] = Subsector(name, pos, sec)
                if line.startswith('# Alleg:'):
                    algCode = line[8:].split(':', 1)[0].strip()
                    algName = line[8:].split(':', 1)[1].strip().strip('"')

                    base = AllyGen.same_align(algCode)
                    if base in self.alg:
                        self.alg[base].name = algName
                    if base not in self.alg:
                        self.alg[base] = Allegiance(base,
                                                    AllyGen.same_align_name(
                                                        base, algName),
                                                    base=True)
                    if algCode not in self.alg:
                        self.alg[algCode] = Allegiance(algCode,
                                                       algName,
                                                       base=False)

            for line in lines[lineno + 2:]:
                if line.startswith('#') or len(line) < 20:
                    continue
                star = Star.parse_line_into_star(line, sec, pop_code, ru_calc)
                if star:
                    sec.worlds.append(star)
                    sec.subsectors[star.subsector()].worlds.append(star)
                    star.alg_base = AllyGen.same_align(star.alg)

                    self.set_area_alg(star, self, self.alg)
                    self.set_area_alg(star, sec, self.alg)
                    self.set_area_alg(star, sec.subsectors[star.subsector()],
                                      self.alg)

            self.sectors[sec.name] = sec
            self.logger.info("Sector {} loaded {} worlds".format(
                sec, len(sec.worlds)))

        self.set_bounding_sectors()
        self.set_bounding_subsectors()
        self.set_positions()
        self.logger.debug("Allegiances: {}".format(self.alg))
Example #13
0
    def testHashValueSameAfterCaching(self):
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V  ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)

        # Grabbing hash value twice, once to seed Star._hash, second to dig it out of that cache
        oldHash = star1.__hash__()
        newHash = star1.__hash__()
        self.assertEqual(oldHash, newHash)
Example #14
0
def makeStars(data):
    for i in range(data.numStars):
        startAngle = random.uniform(0, 2 * math.pi)
        currVector = Vector.fromAngle(startAngle) * 3
        data.stars.append(
            Star(
                data, currVector,
                rgbString(random.randint(0, 255), random.randint(0, 255),
                          random.randint(0, 255))))
Example #15
0
    def testHashValueSameAfterCaching(self):
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V  ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)

        # Grabbing hash value twice, once to seed Star._hash, second to dig it out of that cache
        oldHash = star1.__hash__()
        newHash = star1.__hash__()
        self.assertEqual(oldHash, newHash)
Example #16
0
def selfMode():
    global pauseCounter, objects, speed, score, bkgX, bkgX2
    global fallSpeed, event, powerups
    run = True
    avocado.falling = False
    score = 0
    while run:
        if pauseCounter > 0:
            pauseCounter += 1
            # delay before showing game over
            if pauseCounter * 40 > fallSpeed:
                gameOverScreen()

        newList = copy.copy(objects)
        for item in objects:
            # if instance of star, remove star from screen
            if item.collide(avocado.hitBox):
                if isinstance(item, Star):
                    newList.pop(objects.index(item))
                    score += 1
                elif isinstance(item, Chip):
                    avocado.jumping = True
                else:
                    avocado.sliding = True
            item.x -= 3
            # off the screen, get rid of the object
            if item.x < item.width * -3:
                newList.pop(newList.index(item))
        objects = newList
        # move background back leftwards
        bkgX -= 3
        # move background at different position
        bkgX2 -= 3
        # first background starts until the negative
        # width of the background
        if bkgX < bkg.get_width() * -1:
            bkgX = bkg.get_width()
        if bkgX2 < bkg.get_width() * -1:
            bkgX2 = bkg.get_width()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()
            if event.type == USEREVENT + 1:
                speed += 20
            if event.type == USEREVENT + 2:
                # every second, add star to screen
                rand = random.randrange(0, 2)
                if rand == 0:
                    objects.append(Chip(810, 340, 64, 64))
                else:
                    objects.append(Star(810, 340, 64, 64))

        clock.tick(speed)
        redrawWindow()
    def setUp(self):
        star_regex = ''.join([line.rstrip('\n') for line in Galaxy.regex])

        self.starline = re.compile(star_regex)
        self.star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)
        self.star2 = Star.parse_line_into_star(
            "0104 Shana Ma             E551112-7 Lo Po                { -3 } (301-3) [1113] B     - - 913 9  Im K2 IV M7 V     ",
            self.starline, Sector('Core', ' 0, 0'), 'fixed', None)

        self.logger = logging.getLogger("PyRoute")

        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        # create console handler and set level to debug
        ch = logging.StreamHandler()
        ch.setLevel("INFO")
        ch.setFormatter(formatter)
        self.logger.addHandler(ch)
Example #18
0
 def __systemInit(self):
     self.__bodies = []
     randNum = random.choices([1, 2, 3], weights=(90, 9, 1))[0]
     n = 0
     for s in range(1):
         self.__bodies.append(Star(self, n))
         n += 1
     for p in range(random.randint(self.__minBodies, self.__maxBodies)):
         self.__bodies.append(Planet(self, n))
         n += 1
Example #19
0
    def testParseIrkigkhanRUScaled(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, sector, 'fixed', 'scaled')

        expected = 756
        actual = star1.ru

        self.assertEqual(expected, actual)
Example #20
0
    def testParseIrkigkhanRUScaled(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, sector, 'fixed', 'scaled')

        expected = 756
        actual = star1.ru

        self.assertEqual(expected, actual)
Example #21
0
    def testParseSyss(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "2323 Syss                 C400746-8 Na Va Pi                   { -1 } (A67-2) [6647] BD   S  - 510 5  ImDv M9 III D M5 V",
            self.starline, sector, 'fixed', None)

        self.assertTrue(star1.sector.name == 'Core', star1.sector.name)
        self.assertEqual(star1.position, '2323')
        self.assertEqual(star1.name, 'Syss')
        self.assertEqual(star1.uwp, 'C400746-8')
        self.assertEqual(star1.stars, 'M9 III D M5 V')
        self.assertEqual(star1.star_list, ['M9 III', 'D', 'M5 V'])
Example #22
0
    def __load_positions(self):
        for data in self.level_data:
            name, x, y = self.__break_data(data)

            if name == 'earth':
                self.earth = Planet(x, y)
            if name == 'black_hole':
                self.black_hole = Black_Hole(x, y)
            if name == 'star':
                self.stars.append(Star(x, y))
            if name == 'neutron_star':
                self.neutron_stars.append(Neutron_Star(x, y))
Example #23
0
    def testParseSyss(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "2323 Syss                 C400746-8 Na Va Pi                   { -1 } (A67-2) [6647] BD   S  - 510 5  ImDv M9 III D M5 V",
            self.starline, sector, 'fixed', None)

        self.assertTrue(star1.sector.name == 'Core', star1.sector.name)
        self.assertEqual(star1.position, '2323')
        self.assertEqual(star1.name, 'Syss')
        self.assertEqual(star1.uwp, 'C400746-8')
        self.assertEqual(star1.stars, 'M9 III D M5 V')
        self.assertEqual(star1.star_list, ['M9 III', 'D', 'M5 V'])
Example #24
0
    def read_sectors(self, sectors, pop_code, ru_calc):
        for sector in sectors:
            try:
                lines = [line for line in codecs.open(sector, 'r', 'utf-8')]
            except (OSError, IOError):
                self.logger.error("sector file %s not found" % sector)
                continue
            self.logger.debug('reading %s ' % sector)

            sec = Sector(lines[3], lines[4])
            sec.filename = os.path.basename(sector)

            for lineno, line in enumerate(lines):
                if line.startswith('Hex'):
                    break
                if line.startswith('# Subsector'):
                    data = line[11:].split(':', 1)
                    pos = data[0].strip()
                    name = data[1].strip()
                    sec.subsectors[pos] = Subsector(name, pos, sec)
                if line.startswith('# Alleg:'):
                    algCode = line[8:].split(':', 1)[0].strip()
                    algName = line[8:].split(':', 1)[1].strip().strip('"')

                    base = AllyGen.same_align(algCode)
                    if base in self.alg:
                        self.alg[base].name = algName
                    if base not in self.alg:
                        self.alg[base] = Allegiance(base, AllyGen.same_align_name(base, algName), base=True)
                    if algCode not in self.alg:
                        self.alg[algCode] = Allegiance(algCode, algName, base=False)

            for line in lines[lineno + 2:]:
                if line.startswith('#') or len(line) < 20:
                    continue
                star = Star.parse_line_into_star(line, sec, pop_code, ru_calc)
                if star:
                    sec.worlds.append(star)
                    sec.subsectors[star.subsector()].worlds.append(star)
                    star.alg_base = AllyGen.same_align(star.alg)

                    self.set_area_alg(star, self, self.alg)
                    self.set_area_alg(star, sec, self.alg)
                    self.set_area_alg(star, sec.subsectors[star.subsector()], self.alg)

            self.sectors[sec.name] = sec
            self.logger.info("Sector {} loaded {} worlds".format(sec, len(sec.worlds)))

        self.set_bounding_sectors()
        self.set_bounding_subsectors()
        self.set_positions()
        self.logger.debug("Allegiances: {}".format(self.alg))
Example #25
0
 def __init__(self, name, screen_x, screen_y, frames_per_second):
     Game.__init__(self, name, screen_x, screen_y)
     ship_position = Point(config.SCREEN_X/2, config.SCREEN_Y/2)
     self.ship = Ship(ship_position, config.SHIP_INITIAL_DIRECTION, config.SHIP_COLOR)
     self.bullet = Bullet(Point(0,0), config.BULLET_RADIUS, 0, config.BULLET_COLOR)
     self.stars = []
     for i in range(config.STAR_COUNT):
         s = Star()
         self.stars.append(s)
     self.rocks = []
     for i in range(config.ROCK_COUNT):
         (x,y) = random.randint(0, config.SCREEN_X), random.randint(0, config.SCREEN_Y)
         p = Point(x,y)
         r = Rock(p, random.uniform(0, 360.0), config.ROCK_COLOR, (random.uniform(0.0, config.ROCK_MAX_ROTATION_SPEED) * random.uniform(-1.0,1.0)), random.randint(0, config.ROCK_MAX_SPEED))
         self.rocks.append(r)
Example #26
0
def setup():
    # Canvas
    global width, height
    size(600, 600)

    # Number of Stars
    def number_of_stars():
        if width <= 500:
            return 20
        else:
            return 40

    # Star Object
    for i in range(number_of_stars()):
        stars.append(Star())
Example #27
0
    def testParseIrkigkhan(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, sector, 'fixed', None)

        self.assertTrue(star1.sector.name == 'Core', star1.sector.name)
        self.assertTrue(star1.position == '0103')
        self.assertTrue(star1.q == 0 and star1.r == 2, "%s, %s" % (star1.q, star1.r))
        self.assertTrue(star1.name == 'Irkigkhan')
        self.assertTrue(star1.uwp == 'C9C4733-9')
        self.assertTrue(star1.alg == 'Im')
        self.assertTrue(star1.population == 10, "Population %s" % star1.population)
        self.assertTrue(star1.wtn == 9, "wtn %s" % star1.wtn)
        self.assertFalse(star1.tradeCode.industrial)
        self.assertFalse(star1.tradeCode.agricultural)
        self.assertFalse(star1.tradeCode.poor)
        self.assertFalse(star1.tradeCode.rich)
        self.assertTrue(star1.ggCount == 3)
        self.assertEqual(star1.star_list, ['M2 V'])
Example #28
0
    def testParseShanaMa(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "0104 Shana Ma             E551112-7 Lo Po                { -3 } (301-3) [1113] B     - - 913 9  Im K2 IV M7 V     ",
            self.starline, sector, 'fixed', None)

        self.assertTrue(star1.sector.name == 'Core', star1.sector.name)
        self.assertTrue(star1.position == '0104')
        self.assertTrue(star1.q == 0 and star1.r == 3, "%s, %s" % (star1.q, star1.r))
        self.assertTrue(star1.name == 'Shana Ma')
        self.assertTrue(star1.uwp == 'E551112-7')
        self.assertTrue(star1.alg == 'Im')
        self.assertTrue(star1.population == 0, "Population %s" % star1.population)
        self.assertTrue(star1.wtn == 2, "wtn %s" % star1.wtn)
        self.assertFalse(star1.tradeCode.industrial)
        self.assertFalse(star1.tradeCode.agricultural)
        self.assertTrue(star1.tradeCode.poor)
        self.assertFalse(star1.tradeCode.rich)
        self.assertTrue(star1.ggCount == 3)
        self.assertEqual(len(star1.star_list), 2)
        self.assertEqual(star1.star_list, ['K2 IV', 'M7 V'])
Example #29
0
    def __init__(self, level, continent, difficult):
        self.level = level
        self.continent = continent
        self.difficult = difficult

        self.current_rating_level = int(levels_rating[self.continent+self.difficult][str(self.level)])
        #Colors
        self.black = (0,0,0)
        self.white = (255,255,255)

        self.background = pygame.image.load('resources/levels/'+self.continent+'/bglevel'+str(self.level)+'.jpg').convert()
        self.name = Configuration.level_name_json(languageID, self.continent, self.level)

        self.font = pygame.font.Font('resources/ThrowMyHandsUpintheAirBold.ttf',35)
        self.level_title = Text(self.font,self.name,self.black,SCREEN_WIDTH/3+40,30)

        #Timer
        self.timer = Timer()

        self.tweener = pytweener.Tweener()

        self.star = Star(self.difficult)
        self.button_returnmenu = Button('resources/button_returnmenu.png',830,30)
        self.button_playreboot = Button('resources/button_playreboot.png',900,30)
        self.button_pause = Button('resources/button_pause.png',970,30)

        self.sprites = pygame.sprite.Group()
        self.sprites.add(self.button_returnmenu)
        self.sprites.add(self.button_playreboot)
        self.sprites.add(self.button_pause)

        self.title_shadow = pygame.image.load('resources/sombra_titulo_'+self.difficult+'.png').convert_alpha()

        #Pause instance
        self.pause = Pause()

        #Game_Counter instance
        self.game_counter = GameCounter()

        self.clock = pygame.time.Clock()
Example #30
0
    def testParseIrkigkhan(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "0103 Irkigkhan            C9C4733-9 Fl                   { 0 }  (E69+0) [4726] B     - - 123 8  Im M2 V           ",
            self.starline, sector, 'fixed', None)

        self.assertTrue(star1.sector.name == 'Core', star1.sector.name)
        self.assertTrue(star1.position == '0103')
        self.assertTrue(star1.q == 0 and star1.r == 2,
                        "%s, %s" % (star1.q, star1.r))
        self.assertTrue(star1.name == 'Irkigkhan')
        self.assertTrue(star1.uwp == 'C9C4733-9')
        self.assertTrue(star1.alg == 'Im')
        self.assertTrue(star1.population == 10,
                        "Population %s" % star1.population)
        self.assertTrue(star1.wtn == 9, "wtn %s" % star1.wtn)
        self.assertFalse(star1.tradeCode.industrial)
        self.assertFalse(star1.tradeCode.agricultural)
        self.assertFalse(star1.tradeCode.poor)
        self.assertFalse(star1.tradeCode.rich)
        self.assertTrue(star1.ggCount == 3)
        self.assertEqual(star1.star_list, ['M2 V'])
Example #31
0
    def init(self):
        self.bgColor = (0, 0, 0)
        Ship.init()
        self.x = 0
        self.y = 0
        self.star = Star(self.x, self.y)
        ship = Ship(self.width / 2, self.height / 2)
        self.starGroup = pygame.sprite.GroupSingle(self.star)
        self.shipGroup = pygame.sprite.GroupSingle(ship)
        Asteroid.init()
        self.asteroids = pygame.sprite.Group()
        for i in range(5):
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            self.asteroids.add(Asteroid(x, y))

        self.bullets = pygame.sprite.Group()

        Explosion.init()
        self.explosions = pygame.sprite.Group()

        self.timer = 0
Example #32
0
    def testParseShanaMa(self):
        sector = Sector('Core', ' 0, 0')
        star1 = Star.parse_line_into_star(
            "0104 Shana Ma             E551112-7 Lo Po                { -3 } (301-3) [1113] B     - - 913 9  Im K2 IV M7 V     ",
            self.starline, sector, 'fixed', None)

        self.assertTrue(star1.sector.name == 'Core', star1.sector.name)
        self.assertTrue(star1.position == '0104')
        self.assertTrue(star1.q == 0 and star1.r == 3,
                        "%s, %s" % (star1.q, star1.r))
        self.assertTrue(star1.name == 'Shana Ma')
        self.assertTrue(star1.uwp == 'E551112-7')
        self.assertTrue(star1.alg == 'Im')
        self.assertTrue(star1.population == 0,
                        "Population %s" % star1.population)
        self.assertTrue(star1.wtn == 2, "wtn %s" % star1.wtn)
        self.assertFalse(star1.tradeCode.industrial)
        self.assertFalse(star1.tradeCode.agricultural)
        self.assertTrue(star1.tradeCode.poor)
        self.assertFalse(star1.tradeCode.rich)
        self.assertTrue(star1.ggCount == 3)
        self.assertEqual(len(star1.star_list), 2)
        self.assertEqual(star1.star_list, ['K2 IV', 'M7 V'])
Example #33
0
def playHardGame():
    global pauseCounter, objects, speed, score, bkgX, bkgX2
    global fallSpeed, event, powerups
    run = True
    avocado.falling = False
    score = 0
    while run:
        if pauseCounter > 0:
            pauseCounter += 1
            # delay gives about 2 seconds
            if pauseCounter * 40 > fallSpeed:
                gameOverScreen()

        newList = copy.copy(objects)
        for item in objects:
            # if instance of star, remove star from screen
            if item.collide(avocado.hitBox):
                if isinstance(item, Star):
                    newList.pop(objects.index(item))
                    score += 1
                else:
                    avocado.falling = True
                    if pauseCounter == 0:
                        fallSpeed = speed
                        pauseCounter = 1
            item.x -= 7
            # off the screen, get rid of the object
            if item.x < item.width * -3:
                newList.pop(newList.index(item))
        objects = newList

        # move background back leftwards
        bkgX -= 7
        # move background at different position
        bkgX2 -= 7
        # first background starts until the negative
        # width of the background
        if bkgX < bkg.get_width() * -1:
            bkgX = bkg.get_width()
        if bkgX2 < bkg.get_width() * -1:
            bkgX2 = bkg.get_width()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()
            if event.type == USEREVENT + 5:
                speed += 60
            if event.type == USEREVENT + 6:
                # every second, add star to screen
                rand = random.randrange(0, 3)
                if rand == 0:
                    objects.append(Chip(810, 340, 64, 64))
                elif rand == 1:
                    objects.append(Star(810, 340, 64, 64))
                else:
                    objects.append(Onion(810, -0.5, 48, 320))

        keys = pygame.key.get_pressed()

        if keys[pygame.K_UP]:
            if not (avocado.jumping):
                avocado.jumping = True

        if keys[pygame.K_DOWN]:
            if not (avocado.sliding):
                avocado.sliding = True

        clock.tick(speed)
        redrawWindow()
Example #34
0
        points_t.append(float(780 - starty) / (endy - starty))
        points_t.append(float(42 - starty) / (endy - starty))

        points_t.sort()
        result = [(pt_1 + t * (pt_2 - pt_1))
                  for t in (points_t[2], points_t[3])
                  for (pt_1, pt_2) in zip(line_pt_1, line_pt_2)]
        logging.getLogger("PyRoute.HexMap").debug(result)
        return (result[0], result[1]), (result[2], result[3])


if __name__ == '__main__':
    sector = Sector('# Core', '# 0,0')
    hexMap = HexMap(None)
    pdf = hexMap.document(sector)
    hexMap.write_base_map(pdf, sector)

    galaxy = Galaxy(0, 0)

    star1 = Star(
        "0102 Shana Ma             E551112-7 Lo Po                { -3 } (300-3) [1113] B     - - 913 9  Im K2 IV M7 V     ",
        galaxy.starline, 0, 0)
    star2 = Star(
        "0405 Azimuth              B847427-B Ni Pa                { 1 }  (634+1) [455B] Bc    N - 200 13 Im M2 V M7 V      ",
        galaxy.starline, 0, 0)
    hexMap.trade_line(pdf, [star1, star2])
    hexMap.system(pdf, star1)
    hexMap.system(pdf, star2)

    hexMap.writer.close()
Example #35
0
    def __init__(self, num_of_workers=1):
        Starsmasher.__instance__ = self

        #self.library = cdll.LoadLibrary('./libstarsmasher.so')
        self.toolsLibrary = cdll.LoadLibrary('./tools/tools.so')
        # The following variables are present in
        # sph.input

        self.num_of_workers = num_of_workers

        self.ndisplace = 0
        self.displacex = 0.0
        self.displacey = 0.0
        self.displacez = 0.0

        self.semimajoraxis = 0.0
        self.bimpact = -1.e30
        self.e0 = -1.e30
        self.vinf2 = 1.e30

        self.tf = 50000
        self.dtout = 100

        self.n = 100000

        self.gflag = 1
        self.nnopt = 22 + self.gflag
        self.nav = 3
        self.alpha = 1
        self.beta = 2
        self.ngr = 3
        self.hco = 1.0
        self.hfloor = 0.0
        self.nrelax = 1
        self.trelax = 1.e30

        self.sep0 = 200
        self.equalmass = 0
        self.treloff = 0
        self.tresplintmuoff = 0.0

        self.nitpot = 1
        self.tscanon = 0
        self.sepfinal = 1.e30
        self.nintvar = 2

        self.ngravprocs = -2
        self.qthreads = 0

        self.mbh = 20.0
        self.runit = 6.9599e10
        self.munit = 1.9891e33

        self.cn1 = 0.5e0
        self.cn2 = 0.06e0
        self.cn3 = 0.06e0
        self.cn4 = 1.e30
        self.cn5 = 0.02e0
        self.cn6 = 0.02e0
        self.cn7 = 4.0e0

        self.computeexclusivemode = 0

        self.omega_spin = 0.0e0
        #check if this is required
        self.ppn = 12
        self.neos = 1
        self.nselfgravity = 1
        self.gam = 5.0 / 3.0
        self.reat = -1.0e0
        self.npoly = 1.50

        #starmass and starradius are in units of
        #Msun and Rsun

        self.starmass = 1.0e0
        self.starradius = 1.0e0
        self.ncooling = 0
        self.nkernel = 0
        self.teq = 100.0e0

        self.tjumpahead = 1.0e30
        self.startfile1 = 'sph.start1u'
        self.startfile2 = 'sph.start2u'

        self.eosfile = 'sph.eos'
        self.opacityfile = 'sph.opacity'

        self.profilefile = 'eg.last1.muse_s2mm'
        self.throwaway = False

        self.stellarevolutioncodetype = 1

        # The following parameters are present in sph.init

        self.simulationtype = '1es'
        self.dirname = 'data'

        self.star1 = Star()
        self.star2 = Star()
Example #36
0
class Game():
    def __init__(self, level, continent, difficult):
        self.level = level
        self.continent = continent
        self.difficult = difficult

        self.current_rating_level = int(levels_rating[self.continent+self.difficult][str(self.level)])
        #Colors
        self.black = (0,0,0)
        self.white = (255,255,255)

        self.background = pygame.image.load('resources/levels/'+self.continent+'/bglevel'+str(self.level)+'.jpg').convert()
        self.name = Configuration.level_name_json(languageID, self.continent, self.level)

        self.font = pygame.font.Font('resources/ThrowMyHandsUpintheAirBold.ttf',35)
        self.level_title = Text(self.font,self.name,self.black,SCREEN_WIDTH/3+40,30)

        #Timer
        self.timer = Timer()

        self.tweener = pytweener.Tweener()

        self.star = Star(self.difficult)
        self.button_returnmenu = Button('resources/button_returnmenu.png',830,30)
        self.button_playreboot = Button('resources/button_playreboot.png',900,30)
        self.button_pause = Button('resources/button_pause.png',970,30)

        self.sprites = pygame.sprite.Group()
        self.sprites.add(self.button_returnmenu)
        self.sprites.add(self.button_playreboot)
        self.sprites.add(self.button_pause)

        self.title_shadow = pygame.image.load('resources/sombra_titulo_'+self.difficult+'.png').convert_alpha()

        #Pause instance
        self.pause = Pause()

        #Game_Counter instance
        self.game_counter = GameCounter()

        self.clock = pygame.time.Clock()

    def update(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
            elif event.type == MOUSEBUTTONDOWN:
                if self.button_returnmenu.rect.collidepoint(event.pos[0],event.pos[1]):
                    levelsselector_start(self.continent,self.difficult)
                if self.button_pause.rect.collidepoint(event.pos[0],event.pos[1]):
                    self.timer.stop()
                    self.pause.status = True
                if self.button_playreboot.rect.collidepoint(event.pos[0],event.pos[1]):
                    game_start(self.level,self.continent,self.difficult)
                if (self.star.rect.collidepoint(event.pos[0],event.pos[1])
                    and not self.star.move):
                    if android:
                        android.vibrate(1)
                    self.star.change_state()
                    self.tweener.addTween(self.star,x=1024,tweenTime=1, tweenType=pytweener.Easing.Elastic.easeIn)
                    if self.timer.time()<=4:
                        #Write rating of level and total rating of continent
                        levels_rating[self.continent+self.difficult][str(self.level)] = "3"
                        Configuration.override_rating_json(levels_rating)
                        self.level_goal = LevelGoal(3)
                    elif self.timer.time()>4 and self.timer.time()<= 6:
                        if not self.current_rating_level == 3:
                            levels_rating[self.continent+self.difficult][str(self.level)] = "2"
                            Configuration.override_rating_json(levels_rating)
                        self.level_goal = LevelGoal(2)
                    elif self.timer.time()> 6:
                        if (not self.current_rating_level == 2 or
                            not self.current_rating_level == 3):
                            levels_rating[self.continent+self.difficult][str(self.level)] = "1"
                            Configuration.override_rating_json(levels_rating)
                        self.level_goal = LevelGoal(1)
                    self.timer.stop()

        #print self.timer.time()
        self.timer.time()
        self.dt = self.clock.tick(60)
        self.tweener.update(self.dt/1000.0)

    def draw(self,screen):
        screen.blit(self.background,(0,0))
        screen.blit(self.title_shadow,(0,0))
        self.level_title.draw(screen)
        self.sprites.draw(screen)

        screen.blit(self.star.image,(self.star.x,self.star.y))

        pygame.display.flip()
        #Instance pause with funcion update. Parameters: screen. __draw()
        self.pause.update(screen)

        #Instance GameCounter with funcion update. Parameters: screen. __draw()
        self.game_counter.update(screen)

        #Instance LevelGoal with funcion update. Parameters: screen. __draw()
        if self.star.x > 1000:
            self.level_goal.state = True
            self.level_goal.update(screen)
Example #37
0
    def main(self, screen, difficulty, rect_player):
        # タイトルと設定情報の描画
        star_num = self.titlefont.render("Star:{0}".format(self.get_star),
                                         True, (255, 255, 255))
        lim_time = LIMIT_TIME - int((time.time() - self.start_time))
        time_num = self.titlefont.render("Time:{0}".format(lim_time), True,
                                         (255, 255, 255))
        screen.blit(self.title, (20, 50))

        # 終了条件を満たしていたら
        if lim_time <= 0:
            screen.blit(self.result, (500, 50))
            screen.blit(star_num, (500, 150))
            # ランキング情報を1度だけ読み出し順位を確認する
            if self.read_ranking == False:
                self.write_point = self.ranking.read_ranking(self.get_star)
                self.read_ranking = True

            # ランキングで更新があったら名前を入力させる
            if self.write_point:
                screen.blit(
                    self.titlefont.render("New Record!", True,
                                          (255, 255, 255)), (430, 250))
                # スクリーンキーボードを表示する
                for i, eng in enumerate(self.eng_chara):
                    for j, chara in enumerate(eng):
                        screen.blit(
                            self.comment.render(chara, True, (255, 255, 255)),
                            (350 + j * 40, 400 + i * 40))
                screen.blit(self.comment.render("END", True, (255, 255, 255)),
                            (350 + 220, 400 + 2 * 40))
                screen.blit(
                    self.comment.render(self.your_name, True, (255, 255, 255)),
                    (350, 350))  # 名前を表示
                # 今自分が選択している位置を四角形で表示
                pygame.draw.rect(
                    screen, (255, 255, 0),
                    Rect(350 + 40 * self.choose[X], 410 + 40 * self.choose[Y],
                         30, 30), 2)
                self.input_name()
            else:
                screen.blit(
                    self.titlefont.render("press enter!", True,
                                          (255, 255, 255)), (430, 250))
                # エンターを押したら終了するための処理
                con = self.control.control()
                if con == 'return':
                    rect_player.center = (450, 220)
                    self.media.kirakira.play()
                    self.media.play_bgm(1)
                    return Mode.MENU
        # まだ終了していなかったら(制限時間内なら)
        else:
            screen.blit(time_num, (900, 10))
            screen.blit(star_num, (900, 100))
            ran = random.randint(0, 100)
            # 生成した乱数が難易度の一定数以内なら星を生成する
            if ran <= (difficulty[Difficulty.STAR] - 1):
                self.star_list.append(Star(random.randint(100, 1100), 50))
            # 生成された星を描画する
            for i, star in enumerate(self.star_list):
                screen.blit(self.media.star, (star.x, star.y))
                star.y += 2  # 星を落とす
                # もしキャラクターと星が重なっていたら星を取得
                if star.hit(rect_player, 15 * difficulty[Difficulty.SIZE]):
                    self.star_list.pop(i)
                    self.get_star += 1
                    self.media.hit.play()
                # 地面以下なら星を消滅
                elif self.star_list[i].y > 600:
                    self.star_list.pop(i)

            # 横移動用コントロール
            con = self.control.control2()
            if con == 'left':
                if rect_player.centerx > 100:
                    rect_player.center = (rect_player.centerx -
                                          difficulty[Difficulty.SPEED], 550)
            elif con == 'right':
                if rect_player.centerx < 1100:
                    rect_player.center = (rect_player.centerx +
                                          difficulty[Difficulty.SPEED], 550)

        return Mode.PLAY
Example #38
0
    def mousePressed(self, x, y):
        #Out of bounds check
        if not 0 < x < self.width or not 0 < y < self.height:
            return
        #Option to return to menu if game is lost
        if self.gameWon:
            if 0 < x < 166 and 500 < y < 600:
                self.gameMode = 'Menu'
            if x > 333 and y > 500:
                self.init(self)
            return
        #Menu button in game
        if 0 < x < 166 and 500 < y < 600:
            self.gameMode = 'Menu'
            return
        #Turning on/off hints:
        if 333 < x < 500 and 500 < y < 600:
            self.hint = not self.hint
            return
        if 166 < x < 333 and 500 < y < 600:
            if self.solve:
                self.solve = False
                return
            self.star.empty()
            self.solveSteps = solver.callWithLargeStack(
                solver.solve, Block.board)
            xI, yI = self.solveSteps[0][0], self.solveSteps[0][1]
            newStarX = self.blockWidth / 2 + (xI * self.blockWidth)
            newStarY = self.blockWidth / 2 + (yI * self.blockWidth)
            self.star.add(Star(newStarX, newStarY, self.rows))
            self.solve = True
        #Calculating the index of the blank
        self.bI = Block.board.index(self.boardL)
        self.bX = self.bI % self.rows
        self.bY = self.bI // self.rows
        #Calculating index of the click
        cX = int(x // self.blockWidth)
        cY = int(y // self.blockWidth)
        #During solving, only correct moves allowed
        if self.solve:
            if [cX, cY] != self.solveSteps[0]:
                return
        i = int(cY * self.rows + cX)
        dx, dy = 0, 0
        if abs(self.bX - cX) + abs(self.bY - cY) < 2:  #If valid move
            #Updating solve move
            if self.solve:
                self.solveSteps.pop(0)
                self.star.empty()
                if len(self.solveSteps) > 0:
                    xI, yI = self.solveSteps[0][0], self.solveSteps[0][1]
                    newStarX = self.blockWidth / 2 + (xI * self.blockWidth)
                    newStarY = self.blockWidth / 2 + (yI * self.blockWidth)
                    self.star.add(Star(newStarX, newStarY, self.rows))
            #Updating the numeric board that checks legality
            Block.board[i], Block.board[self.bI] = \
            Block.board[self.bI], Block.board[i]
            for block in self.blocks:
                #Finds which block was clicked
                if  abs(x-block.x) < (self.blockWidth / 2) and \
                    abs(y-block.y) < (self.blockWidth / 2):
                    #Determining the direction the block will move
                    if self.bX > cX:
                        dx = 1
                    elif self.bX < cX:
                        dx = -1
                    elif self.bY > cY:
                        dy = 1
                    elif self.bY < cY:
                        dy = -1

                    #Updating the block
                    block.update(block.x + (self.blockWidth * dx),
                                 block.y + (self.blockWidth * dy), self.width,
                                 self.height)
        for block in self.blocks:
            if isinstance(block, Blank):
                #Updating the blank in opposite direction of the block
                dx, dy = -dx, -dy
                block.update(block.x + (self.blockWidth * dx),
                             block.y + (self.blockWidth * dy), self.width,
                             self.height)
        #Win condition
        if Block.board == list(range(self.boardL + 1)):
            self.gameWon = True
Example #39
0
def generate_level(level, gr, clock, bg, pos_pl=None):
    level = load_level(level)
    new_player, x, y = None, None, None
    pos_player = None
    player_list = list()
    player_list.append(0)
    for y in range(len(level)):
        for x in range(len(level[y])):
            pos = x, y
            if level[y][x] == 'g':
                Tiles.GrassBlock(gr, pos)
            elif level[y][x] == '@':
                pos_player = x, y
                # вернем игрока, а также размер поля в клетках
            elif level[y][x] == 'o':
                pos_bee = x, y
                bee = Bee(gr, pos_bee, None, player_list)
                bees.append(bee)
            elif level[y][x] == 's':
                Tiles.SmallStoneBlock(gr, pos)
            elif level[y][x] == 'd':
                Tiles.Dirty(gr, pos)
            elif level[y][x] == 'u':
                pos_slug = x, y
                slug = Slug(gr, pos_slug, None, player_list)
                slugs.append(slug)
            elif level[y][x] == 'p':
                Tiles.Platform(gr, pos)
            elif level[y][x] == 'e':
                pos_piranha = x, y
                piranha = PiranhaPlant(gr, pos_piranha, None, player_list)
                piranhas.append(piranha)
            elif level[y][x] == 'b':
                Tiles.Sign(gr, pos)
            elif level[y][x] == 't':
                Tiles.Tree(gr, pos)
            elif level[y][x] == 'k':
                Tiles.Bush(gr, pos)
            elif level[y][x] == 'r':
                Tiles.Rock(gr, pos)
            elif level[y][x] == 'c':
                Tiles.Door(gr, pos)
            elif level[y][x] == 'h':
                Tiles.House(gr, pos)
            elif level[y][x] == 'f':
                Tiles.FaceBlock(gr, pos)
            elif level[y][x] == 'm':
                Tiles.Shrooms(gr, pos)
            elif level[y][x] == 'w':
                Tiles.Skulls(gr, pos)
            elif level[y][x] == 'z':
                Tiles.SpikesSkull(gr, pos)
            elif level[y][x] == '#':
                star = Star(gr, pos, None, player_list)
                stars.append(star)
    x_max = x * BLOCK_SIZE[0]
    y_max = y * BLOCK_SIZE[1]
    if pos_pl is not None:
        new_player = Player(gr, pos_pl, clock, x_max, bg, rel_coords=True)
    else:
        new_player = Player(gr, pos_player, clock, x_max, bg)
    player_list[0] = new_player
    # slug = Slug(gr, pos_slug)
    return new_player, x_max, y_max
Example #40
0
    print(z)


def end(hard, start, cj, csys, cst, csts, cbh, cbhs, hj):
    if hard and hj is not None:
        t.titles(hard, start, cj, csys, cst, csts, cbh, cbhs, hj)
    else:
        hard = h
        start = s
        t.titles(hard, start, cj, csys, cst, csts, cbh, cbhs)


start = time.time()

Sys = System(s_p=[0, 0, 0, 1, 0, 0, 0])
St = Star(Sys)
Bh = BlackHole(Sys)

while True:
    if change_nj:
        nj = random.randint(30, 80) * 100
    change_nj = False
    act = input('Напишите ваше действие: ')
    if act.lower() == 'прыжок':
        j1 = f'Для прыжка потребуется {nj} единиц энергии'
        j2 = f'У вас {enrg} единиц энергии'
        j3 = 'Вы действительно хотите совершить прыжок? Д(а)/Н'
        app = input(f'{z}\n{j1}\n{j2}\n{j3}\n{z}\n')
        if app.lower() == 'д' or app.lower() == 'да':
            if enrg < nj:
                if Sys.get_obj('St') is not None:
Example #41
0
def play_game():
    global highscore
    asteroids = []
    starlist = []
    explosions = []
    puplist = []
    score = 0
    plr = Player(window, WINDOW_SIZE)
    last_spawn = pygame.time.get_ticks()
    last_pup_spawn = pygame.time.get_ticks()
    asteroid_reload = random.randint(*getSpawnRate(score))
    powerup_reload = random.randint(*PUP_SPAWN_RATE)

    #         w      s      a      d
    keys = [False, False, False, False]
    shooting = False

    while True:  # game loop

        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN:
                key = event.key
                if key == K_w:
                    keys[0] = True
                elif key == K_s:
                    keys[1] = True
                elif key == K_a:
                    keys[2] = True
                elif key == K_d:
                    keys[3] = True
                elif key == K_SPACE:
                    shooting = True
            elif event.type == KEYUP:
                key = event.key
                if key == W:
                    keys[0] = False
                elif key == S:
                    keys[1] = False
                elif key == A:
                    keys[2] = False
                elif key == D:
                    keys[3] = False
                elif key == SPACE:
                    shooting = False

        # Clear the screen
        window.fill(BGCOLOR)

        # Generate stars.
        if len(starlist) < MAX_STARS:
            starlist.append(Star(window, WINDOW_SIZE, starlist))

        for star in starlist:
            star.step()

        if len(
                asteroids
        ) < MAX_ASTEROIDS and last_spawn + asteroid_reload <= pygame.time.get_ticks(
        ):
            asteroids.append(
                Asteroid(asteroids, window, WINDOW_SIZE, getLvl(score)))
            last_spawn = pygame.time.get_ticks()
            asteroid_reload = random.randint(*getSpawnRate(score))

        if last_pup_spawn + powerup_reload <= pygame.time.get_ticks():
            if random.randint(1, 2) % 2 == 0:
                puplist.append(Powerup(window, WINDOW_SIZE, puplist))

            last_pup_spawn = pygame.time.get_ticks()
            powerup_reload = random.randint(*PUP_SPAWN_RATE)

        for explosion in explosions:
            explosion.step()

        for asteroid in asteroids:
            asteroid.step()

        for powerup in puplist:
            powerup.step()

        if shooting:
            plr.shoot()

        # Move the player & handle shooting
        plr.move(keys)
        plr.draw()

        for powerup in puplist:
            if plr.checkcollision(powerup):
                #powerup.applyeffect(plr)
                pygame.mixer.Sound('../res/powerup.wav').play()
                if powerup.ptype == POWERUP_SHIELD:
                    plr.takedmg(-1)
                elif powerup.ptype == POWERUP_POINTS:
                    score += random.randint(1, 10)
                powerup.destroy()

        for asteroid in asteroids:
            for bullet in plr.bullets:
                if asteroid.checkcollision(bullet):
                    asteroidhit.play()
                    bullet.destroy()
                    asteroid.destroy()
                    score += 1
                    explosions.append(
                        Explosion(window,
                                  (asteroid.position.x, asteroid.position.y),
                                  explosions))

            if asteroid.checkcollision(plr):
                gameover = plr.takedmg(1)
                asteroid.destroy()

                if gameover:
                    plr.bullets.clear()
                    return score

        # Draw score
        highscore = max(score, highscore)

        textSfcObj = fontObj.render((SCORE_TEXT % (score, highscore)), True,
                                    WHITE)
        textRect = textSfcObj.get_rect()
        #textRect.center = (440, 25)
        textRect.center = (WINDOW_SIZE[0] - 85, 15)

        lvlSfc = fontObj.render(LEVEL_TEXT % getLvl(score), True, WHITE)
        lvlRect = lvlSfc.get_rect()
        lvlRect.center = (WINDOW_SIZE[0] - 50, 40)

        window.blit(textSfcObj, textRect)
        window.blit(lvlSfc, lvlRect)
        pygame.display.update()
        fpsClock.tick(FPS)