Example #1
0
    def __init__(self, root=None):

        self.canvas = tk.Canvas(root)

        self.canvas.pack(expand=True, fill="both")

        sun = Sun(engine=self, mass=1000)
        sun_graphic = self.canvas.create_oval(sun.x - sun.radius,
                                              sun.y - sun.radius,
                                              sun.x + sun.radius,
                                              sun.y + sun.radius,
                                              fill="yellow")
        planet = Planet(engine=self, sun=sun)
        planet_graphic = self.canvas.create_oval(planet.x - planet.radius,
                                                 planet.y - planet.radius,
                                                 planet.x + planet.radius,
                                                 planet.y + planet.radius,
                                                 fill="green")
        lander = NaiveLander(engine=self,
                             sun=sun,
                             planet=planet,
                             acceleration_cap=0.5)
        lander_graphic = self.canvas.create_oval(lander.x - lander.radius,
                                                 lander.y - lander.radius,
                                                 lander.x + lander.radius,
                                                 lander.y + lander.radius,
                                                 fill="grey")
        self.graphic_dict = {
            sun: sun_graphic,
            planet: planet_graphic,
            lander: lander_graphic
        }
        self.update()
Example #2
0
def generate_sun():
    x = random.randrange(100, get_canvas_width() - 100)
    y = get_canvas_height()
    targetX = x
    targetY = random.randrange(200, get_canvas_height() // 2)
    m = Sun((x, y), (targetX, targetY))
    gfw.world.add(gfw.layer.sun, m)
Example #3
0
    def update(self):
        # state가 STATE_NEW이면 마우스 따라다니도록한다.
        if self.state == STATE_MOUNT:
            self.event_start += gfw.delta_time
            self.collisiontime += gfw.delta_time
            if self.event_start > self.event_time:
                if self.name != 'CherryBomb':
                    self.event_start = 0
                if self.name == 'SunFlower':
                    m = Sun((self.pos[0], self.pos[1]),
                            (self.pos[0], self.pos[1]))
                    gfw.world.add(gfw.layer.sun, m)
                elif self.name == 'Peashooter':
                    m = Bullet((self.pos[0], self.pos[1]), 'Normal')
                    gfw.world.add(gfw.layer.bullet, m)
                elif self.name == 'SnowPea':
                    m = Bullet((self.pos[0], self.pos[1]), 'snow')
                    gfw.world.add(gfw.layer.bullet, m)
                elif self.name == 'CherryBomb' and self.cherryBomb == False:
                    self.time += gfw.delta_time
                    self.fidx = round(self.time * self.fps)
                elif self.name == 'WallNut':
                    pass

        if self.name != 'CherryBomb':
            self.time += gfw.delta_time
            self.fidx = round(self.time * self.fps)
        else:  # 체리의 인덱스가 터짐이면 좀비와 충돌체크해서 주변 좀비 죽인다. 그리고 삭제된다.
            if self.fidx >= 6:
                self.cherryBomb = True
                if self.cherrybombtime == 0:
                    check_collision_cherrybomb(self.pos)
                self.cherrybombtime += gfw.delta_time
                if self.cherrybombtime > 1:
                    self.remove()
Example #4
0
    def add_sun(self):

        temperature = input("I see it's hot but what is the temperature? ")
        sky = input("How is the sky looking? ")
        is_over_90 = input("Is it over 90 degrees? (True or False) ")

        new_sun = Sun(temperature, is_over_90, sky)
        self.daily_forecast.append(new_sun)
Example #5
0
 def __init__(self, geocoder):
     self.local_time = LocalTime(geocoder)
     self.sun = Sun(geocoder)
     self.artwork = Artwork()
     self.city = City(geocoder)
     self.commute = Commute(geocoder)
     self.calendar = GoogleCalendar(geocoder)
     self.everyone = Everyone(geocoder)
Example #6
0
    def __init__(self):

        self.size = (800, 400)
        self.fps = 30
        self.screen = None

        self.sky = Sky(self)
        self.foreground = Foreground(self)
        self.sun = Sun(self)
Example #7
0
def init_gl():
    global obj
    global cam
    global sun
    global mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    global planets
    global asteroid
    global t
    global quad
    global ship

    glClearColor(0.0, 0.0, 0.0, 1.0)
    glClearDepth(1.0)
    glEnable(GL_DEPTH_TEST)
    glShadeModel(GL_SMOOTH)

    glEnable(GL_LIGHTING)

    glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb_0)
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos_0)
    glEnable(GL_LIGHT0)

    glLightfv(GL_LIGHT1, GL_POSITION, light_pos_1)
    glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, light_dir_1)
    glLightfv(GL_LIGHT1, GL_AMBIENT, light_amb_1)
    glLightfv(GL_LIGHT1, GL_DIFFUSE, light_dif_1)
    glEnable(GL_LIGHT1)

    obj = OBJ("cube.obj", textureFile="stars.jpg")
    obj.generate()

    cam = Camera()

    sun = Sun(textureFile="sun.jpg")

    mercury = Planet("mercury.jpg", 8, 5, 0.5, 0.1, 0.25)
    venus = Planet("venus.jpg", 9.6, 6, 0.4, 0.1, 0.35)
    earth = Planet("earth.jpg", 11.2, 7, 0.3, 0.1, 0.45, "moon.jpg",
                   [0.7, 0.8, 0.09])
    mars = Planet("mars.jpg", 12.8, 8, 0.2, 0.1, 0.33)
    jupiter = Planet("jupiter.jpg", 19.2, 12, 0.2, 1, 1.5, "jupiter-moon.jpg",
                     [3, 1, 0.3])
    saturn = Planet("saturn.jpg", 25.6, 16, 0.15, 0.2, 1.1)
    uranus = Planet("uranus.jpg", 30.4, 19, 0.11, 0.2, 0.8)
    neptune = Planet("neptune.jpg", 32.8, 20.5, 0.09, 0.2, 0.7)
    planets = [mercury, venus, earth, mars, jupiter, saturn, uranus, neptune]

    quad = gluNewQuadric()
    gluQuadricTexture(quad, GL_TRUE)

    asteroid = Asteroid(Fire())

    t = Texture("rings.jpg")

    ship = pywavefront.Wavefront('Apollo/apollo.obj')
def calc_sunrise(lat, lon, doy, date):
    date = date.replace(hour=0)
    sun = Sun()
    coords = {'longitude': lon, 'latitude': lat}
    sunr_dec = sun.getSunriseTime(coords, date=date)['decimal']
    suns_dec = sun.getSunsetTime(coords, date=date)['decimal']
    sunr_dec *= 60
    suns_dec *= 60
    sunrise = date + pd.to_timedelta(sunr_dec, unit='m')
    sunset = date + pd.to_timedelta(suns_dec, unit='m')
    return sunrise, sunset
Example #9
0
    def __init__(self, geocoder):
        """Schedule constructor.

        Args:
            geocoder (geocoder.Geocoder): Used to localize user specified locations
        """
        self._local_time = LocalTime(geocoder)
        self._sun = Sun(geocoder)
        self._artwork = Artwork()
        self._city = City(geocoder)
        self._commute = Commute(geocoder)
        self._calendar = GoogleCalendar(geocoder)
        self._everyone = Everyone(geocoder)
Example #10
0
def run_game():
    pygame.init()
    pygame.mixer.music.load('music/Phantom from Space.mp3')
    pygame.mixer.music.play(-1)
    pygame.mixer.music.set_volume(0.5)
    sw_settings = Settings()
    screen = pygame.display.set_mode(
        (sw_settings.screen_width, sw_settings.screen_height))
    pygame.display.set_caption("Earth's Defender")
    earth = Earth(sw_settings, screen)
    moon = Moon(sw_settings, screen)
    sun = Sun(sw_settings, screen)
    play_button = Button(sw_settings, screen, "Play")
    pause_message = PauseMessage(sw_settings, screen, "Pause")
    game_stats = GameStats(sw_settings)
    scoreboard = Scoreboard(sw_settings, screen, game_stats)
    ship = Ship(sw_settings, screen)
    alien_boss = AlienBoss(sw_settings, screen)
    bullets = Group()
    aliens = Group()
    aliens_bullets = Group()
    asteroids = Group()
    gf.create_fleet(sw_settings, screen, ship, aliens)

    while True:
        gf.check_events(sw_settings, screen, game_stats, scoreboard,
                        play_button, pause_message, ship, aliens, bullets,
                        aliens_bullets, asteroids)
        if game_stats.game_active and game_stats.game_pause:
            ship.update()
            gf.update_bullets(sw_settings, screen, game_stats, scoreboard,
                              ship, aliens, bullets, aliens_bullets, asteroids,
                              alien_boss)
            gf.update_aliens(sw_settings, game_stats, scoreboard, screen, ship,
                             aliens, bullets, aliens_bullets, asteroids)
            gf.check_alien_fires(sw_settings, screen, aliens, aliens_bullets)
            gf.update_aliens_bullets(sw_settings, game_stats, scoreboard,
                                     screen, ship, aliens, bullets,
                                     aliens_bullets, asteroids)
            gf.check_asteroid_fall(sw_settings, screen, asteroids)
            gf.update_asteroids(sw_settings, game_stats, scoreboard, screen,
                                ship, aliens, bullets, aliens_bullets,
                                asteroids)
            gf.update_alien_boss(sw_settings, screen, game_stats, alien_boss,
                                 aliens, aliens_bullets, bullets, asteroids)
        gf.update_screen(sw_settings, screen, earth, moon, sun, game_stats,
                         scoreboard, ship, aliens, bullets, aliens_bullets,
                         asteroids, play_button, pause_message, alien_boss)
Example #11
0
def enter():
    background = Background()
    game_world.add_object(background, 0)

    ui_slot = Ui_slot()
    game_world.add_object(ui_slot, 0)

    peashooter_ui = Peashooter_ui()
    game_world.add_object(peashooter_ui, 0)

    peashooter = Peashooter()
    game_world.add_object(peashooter, 1)

    global sun
    sun = Sun()
    normal_zombie = Normal_zombie()
Example #12
0
    def __init__(self, building_height):
        rospy.init_node('offb')
        self.height = building_height
        self.GPS_ready = False

        # Wait for Offboard and drone to be ready
        ready = rospy.wait_for_message('/gps_ready_from_offboard', Bool, timeout=rospy.Duration(60*5)) # Wait for offboard to get GPS fix for 5 minutes, because sometimes GPS locks take long to get when a board is booted up the first time

        if ready:
            nav = NavSatFix()
            # And now put the node into a waiting loop to wait for GPS Lock from Offboard
            nav = rospy.wait_for_message('mavros/global_position/global', NavSatFix)
            self.coordinates = np.array([nav.latitude, nav.longitude])
        else:
            rospy.loginfo("Never got position confirmation from Offboard")

        self.house_result_pub = rospy.Publisher('/house_results_from_overpass_local', BuildingPolygonResult, queue_size=5) # Information about the house
        self.camera_stuff_pub = rospy.Publisher('/camera_and_distances', CameraStuff, queue_size=1)
        self.impression_keyframes_pub = rospy.Publisher('/impression_poses_from_planner', PoseArray, queue_size=5) # Poses to take one image of each facade of the house
        self.inspection_keyframes_pub = rospy.Publisher('/keyframes_poses_from_planner', PoseArray, queue_size=5)

        #self.segmented_image_sub = rospy.Subscriber('segmented_image_from_cnn', cnnResult, self.segmented_image_callback, queue_size=5)

        self.image_and_rois_sub = rospy.Subscriber('/segmented_image_from_cnn', ImageAndRois, callback=self.image_and_rois_callback)

        self.get_tiles_ready = False

        self.images_list = []
        self.rois_list = []

        self.s = Sun(self.coordinates[0], self.coordinates[1])
        self.m = Mission(80, 80)
        self.model_walls = []
        self.model_windows = []

        self.fig_thread = Thread(target=self.draw_thread, args=())
        self.fig_thread.daemon = True

        self.fig = []
        self.ax = []
Example #13
0
 def level2init(self):
     self.mainscreen = True
     self.planetChange = False
     self.playing = True
     self.onScreen = True
     self.shipCount = 0
     self.score = 350
     self.makePlanets()
     self.gamex, self.gamey = self.width / 2, self.height / 2
     self.initShip(self.gamex, self.gamey)
     Sun.init()
     self.sunx, self.suny, self.r = (self.width / 2, self.height / 2, 120)
     self.sun = Sun(self.sunx, self.suny)
     self.initFuel()
     self.sungroup = pygame.sprite.Group(self.sun)
     self.planetList = [self.mars, self.uranus, self.mercury, self.neptune]
     pygame.font.init()
     self.starImage = pygame.transform.rotate(
         pygame.transform.scale(
             pygame.image.load('images/stars.png').convert_alpha(),
             (self.width, self.height)), 0)
     self.counter = 0
     self.initScore = 350
Example #14
0
    sleep(x)
    GPIO.output(REVERSE_PIN, GPIO.LOW)
    #    GPIO.cleanup()
    debug("stopped")
    return


def debug(x):
    print(x)
    return


# This is the start of the main program

coords = {'longitude': 0.34, 'latitude': 51.1}
sun = Sun()

print sun.getSunriseTime(coords)
# Sunrise time UTC (decimal, 24 hour format)
push("hi")
print sun.getSunriseTime(coords)['hr']
print sun.getSunriseTime(coords)['min']

print sun.getSunsetTime(coords)['hr']
print sun.getSunsetTime(coords)['min']

GPIO.setmode(GPIO.BOARD)
PIR_PIN = 26
GPIO.setup(PIR_PIN, GPIO.IN)

print howfar()
Example #15
0
def main():
    global sunnum, font, fontImg
    # peashooter = Peashooter()
    clickimage = []
    # sunflower = SunFlower()
    wallnut = WallNut()
    p1 = []
    peaList = []
    sunFlowerList = []

    sunList = []
    zombieList = []
    zombie = Zombie()
    zombieList.append(zombie)

    enemy_zombie_list = []

    flower_product_list = []

    # FPS
    block = pygame.time.Clock()

    index = 0
    # 是否点击卡片
    is_pick = False
    # 区域种植判断
    is_plant = False
    # 太阳下落时间
    SUN_EVENT = pygame.USEREVENT + 1
    pygame.time.set_timer(SUN_EVENT, 3000)  # 3秒出现一个

    # 太阳花产能
    FLOWER_PRODUCT_SUM_EVENT = pygame.USEREVENT + 1
    pygame.time.set_timer(FLOWER_PRODUCT_SUM_EVENT, 5000)

    #
    ZOMBIE_EVENT = pygame.USEREVENT + 1
    pygame.time.set_timer(ZOMBIE_EVENT, 5000)

    z = Zone()
    bulletList = []
    PAUSE = False
    FINAL = 0

    while 1:

        pygame.mixer.music.play()  # 播放音乐
        block.tick(25)  # FPS为25

        # 鼠标点击
        press = pygame.mouse.get_pressed()
        # 鼠标坐标
        x, y = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == SUN_EVENT:
                sun = Sun()
                sunList.append(sun)
            # 太阳花产能
            if event.type == FLOWER_PRODUCT_SUM_EVENT:
                for flower in sunFlowerList:
                    if not flower.isProductSum:
                        sun = Sun()
                        sun.rect.left = flower.rect.left
                        sun.rect.top = flower.rect.top
                        sun.belong = flower
                        flower_product_list.append(sun)
                        flower.isProductSum = True  # 无法生产

            if event.type == ZOMBIE_EVENT:
                zombie = Zombie()
                zombieList.append(zombie)

            # 暂停,点击ESC
            if event.type == pygame.KEYDOWN:
                if event.key == 27:
                    PAUSE = not PAUSE

            if event.type == pygame.MOUSEMOTION:
                if 537 <= x <= 749 and 378 <= y <= 481:
                    if press[0]:
                        PAUSE = not PAUSE
                if not is_pick:
                    if press[0]:
                        if 330 <= x <= 330 + card.get_rect().width and 7 <= y <= 7 + card.get_rect().height:
                            peashooter = Peashooter()
                            clickimage.append(peashooter)
                            pick_type = 'pea'
                            is_pick = True
                        if 380 <= x <= 380 + card_1.get_rect().width and 7 <= y <= 7 + card_1.get_rect().height:
                            sunflower = SunFlower()
                            clickimage.append(sunflower)
                            pick_type = 'flower'
                            is_pick = True

                else:
                    if z.is_plant_zone(x, y):
                        if z.getIndex(x, y) and not is_plant:
                            if pick_type == 'pea':
                                p = Peashooter()
                                a, b = z.getIndex(x, y)
                                p.zone = z.getGridPos(a, b)
                                if not z.plantInfo[b][a]:
                                    p1.append(p)
                                    is_plant = True
                                    if press[0]:
                                        peaList.append(p)
                                        enemy_zombie_list.append(p)
                                        # bullet = p.shot()
                                        # bulletList.append(bullet)
                                        clickimage.clear()
                                        p1.clear()
                                        is_pick = False
                                        z.plantInfo[b][a] = 1
                                        sunnum = str(int(sunnum) - 100)
                                        fontImg = font.render(sunnum, True, (0, 0, 0))

                                        # print(z.plantInfo[a][b])
                            elif pick_type == 'flower':
                                f = SunFlower()
                                a, b = z.getIndex(x, y)
                                f.zone = z.getGridPos(a, b)
                                if not z.plantInfo[b][a]:
                                    p1.append(f)
                                    is_plant = True
                                    if press[0]:
                                        sunFlowerList.append(f)
                                        enemy_zombie_list.append(f)
                                        clickimage.clear()
                                        p1.clear()
                                        is_pick = False
                                        z.plantInfo[b][a] = 1
                                        sunnum = str(int(sunnum) - 100)
                                        fontImg = font.render(sunnum, True, (0, 0, 0))
                        else:
                            p1.clear()
                            is_plant = False

                    if press[2]:
                        is_pick = False
                        clickimage.clear()
                        p1.clear()
                        is_plant = False

                        # if 330 <= x <= 405 and 180 <= y <= 274:

                    # else:
                    #     p1.clear()

                for sun in sunList:
                    if sun.rect.collidepoint((x, y)):
                        if press[0]:
                            # 点击太阳消失
                            sunList.remove(sun)
                            # 收集加分
                            # global sunnum, font, fontImg
                            sunnum = str(int(sunnum) + 25)
                            fontImg = font.render(sunnum, True, (0, 0, 0))

                for sun in flower_product_list:
                    if sun.rect.collidepoint((x, y)):
                        if press[0]:
                            # 点击太阳消失
                            flower_product_list.remove(sun)
                            # 收集加分
                            sunnum = str(int(sunnum) + 25)
                            fontImg = font.render(sunnum, True, (0, 0, 0))
                            # 收集后可继续生产
                            sun.belong.isProductSum = False

        # 打印图片
        if int(zombie.rect.left) < 200:
            FINAL += 1
            PAUSE = True
        if not PAUSE:
            screen.blit(backgroud, (0, 0))
            screen.blit(card_slot, (250, 0))
            screen.blit(card, (330, 7))
            screen.blit(card_1, (380, 7))
            screen.blit(card_2, (430, 6))
            screen.blit(fontImg, (275, 60))

            if index > 13:
                index = 0
            # screen.blit(peashooter.images[index % 13], peashooter.rect)
            # screen.blit(sunflower.images[index % 18], sunflower.rect)
            # screen.blit(wallnut.images[index % 16], wallnut.rect)

            for image in clickimage:
                screen.blit(image.images[0], (x, y))
            for p in p1:
                screen.blit(p.images[0], p.zone)
            # 豌豆射手
            for pea in peaList:
                if pea.is_live:
                    if index % 99 == 1:
                        bullet = pea.shot()
                        bulletList.append(bullet)
                    screen.blit(pea.images[index % 13], pea.zone)
                else:
                    peaList.remove(pea)
                    enemy_zombie_list.remove(pea)
            # 太阳花
            for sunFlower in sunFlowerList:
                if sunFlower.is_live:
                    screen.blit(sunFlower.images[index % 18], sunFlower.zone)
                else:
                    sunFlowerList.remove(sunFlower)
                    enemy_zombie_list.remove(sunFlower)
            # 阳光
            for sun in sunList:
                screen.blit(sun.images[index % 22], sun.rect)
                sun.down()

            # 产能
            for sun in flower_product_list:
                screen.blit(sun.images[index % 22], sun.rect)

            for bullet in bulletList:
                if bullet.status:
                    screen.blit(bullet.images, bullet.rect)
                    bullet.move()
                    bullet.hit(zombieList)
                else:
                    bulletList.remove(bullet)

            for zombie in zombieList:
                if zombie.is_live:
                    zombie.changimage()
                    screen.blit(zombie.images[index % 20], zombie.rect)
                    zombie.move()
                    zombie.attack(enemy_zombie_list)
                else:
                    zombieList.remove(zombie)

            pygame.display.update()

            index += 1
        else:
            if FINAL > 0:
                screen.blit(final_draw, (350, 70))
            else:
                screen.blit(pause_draw, (450, 100))

        pygame.display.update()
Example #16
0
 def __init__(self, geocoder):
     self._local_time = LocalTime(geocoder)
     self._sun = Sun(geocoder)
     self._weather = Weather(geocoder)
Example #17
0
def classFactory(iface):
    # load Sun class from file Sun
    from sun import Sun
    return Sun(iface)
Example #18
0
                                                    maxBytes=1 * 1024 * 1024,
                                                    backupCount=2)
file_handler.setLevel(LOG_LVL)

# Add a formatter
formatter = logging.Formatter(LOG_FORMAT)
file_handler.setFormatter(formatter)

global_logger.addHandler(file_handler)

# Add another handler that will stream to output
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.ERROR)
# logger.addHandler(stream_handler)  # uncomment this to check if this works.
"""setting up lights"""
sun = Sun(LIGHTS)
"""setting up fans"""
wind = Wind(FANS)
"""
import all the configured DH22 sensors, and set them up with names
This only has the capacity for 2 sensors right now, but hopefully will allow any number in the future.
"""
for dht22_sensor in DHT22:
    if dht22_sensor[1] == 'internal':
        in_sense = Sensor(dht22_sensor[0], Adafruit_DHT.DHT22, dht22_sensor[1])
    elif dht22_sensor[1] == 'external':
        ext_sense = Sensor(dht22_sensor[0], Adafruit_DHT.DHT22,
                           dht22_sensor[1])
str_sensor = ','.join([str(x) for x in Sensor.array
                       ])  # put all the names of the sensors together
logger.info("DHT22 sensors configured: {}".format(str_sensor))
Example #19
0
 def create_sun(self):
     """Create the sun."""
     self.sun = Sun()
Example #20
0
 def cal_sun_loc(self):
     sun=Sun()
     sun.cal(self.days_0)
     self.planets['Sun']=sun
Example #21
0
    def read(self, input):
        self.planets = []
        self.read_planets = 0  # number of planets read

        try:

            line = input.readline()
            attribute = 0  # this variable determines which attribute is being read
            self.reset_attributes()

            while line != "":
                line = "".join(line.split())  # strips all whitespaces
                if line == "":  # skip a blank row
                    line = input.readline()
                    continue
                try:
                    if attribute == 0:  # read the name
                        self.name = self.read_name(line)
                        attribute += 1
                    elif attribute == 1:  # read the mass
                        self.mass = self.read_mass(line)
                        attribute += 1
                    elif attribute == 2:  # read the diameter
                        self.diameter = self.read_diameter(line)
                        attribute += 1
                    elif attribute == 3:  # read the position vector
                        self.position = self.read_position(line)
                        attribute += 1
                    elif attribute == 4:  # read the velocity vector
                        self.velocity = self.read_velocity(line)
                        self.route = Route(self.position, self.velocity)

                        if self.name.lower() == "aurinko" or self.name.lower(
                        ) == "sun":  # check if planet is the Sun
                            planet = Sun(self.name, self.route, self.mass,
                                         self.diameter)
                            print("Succesfully saved the Sun, called {:s}".
                                  format(self.name))
                        else:
                            planet = Planet(self.name, self.route, self.mass,
                                            self.diameter)
                            print(
                                "Succesfully saved planet called {:s}".format(
                                    self.name))
                        self.planets.append(planet)
                        self.read_planets += 1
                        self.reset_attributes()
                        attribute = 0

                except Exception as e:  # if an error happened while reading an attribute
                    if self.name != None:
                        print(
                            "Failed to load a planet called {:s}. Error: {:s}".
                            format(self.name, str(e)))
                    else:
                        print(
                            "Failed to load planet number {:d} entirely! Error: {:s}"
                            .format(self.read_planets, str(e)))
                    '''
					Should implement here some code that skips to next planet
					'''

                line = input.readline()

        except:
            pass

        return self.planets
def main():
    global sun_num_surface, choose
    global text
    index = 0
    while True:
        clock.tick(20)
        if not pygame.mixer.music.get_busy():
            pygame.mixer.music.play()
        index += 1
        # 碰撞检测
        for bullet in bulletGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(bullet, zombie):
                    zombie.energy -= 1
                    bulletGroup.remove(bullet)
        for wallNut in wallnutGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(wallNut, zombie):
                    zombie.ismeetwallnut = True
                    wallNut.zombies.add(zombie)
        for peashooter in peashooterGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(peashooter, zombie):
                    zombie.ismeetwallnut = True
                    peashooter.zombies.add(zombie)
        for sunflower in sunFlowerGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(sunflower, zombie):
                    zombie.ismeetwallnut = True
                    sunflower.zombies.add(zombie)
        screen.blit(bg_img, (0, 0))
        screen.blit(seedbank_img, (250, 0))
        screen.blit(sun_num_surface, (270, 60))

        screen.blit(flowerSeed, (320, 0))
        screen.blit(peashooterSeed, (382, 0))
        screen.blit(wallnutSeed, (446, 0))
        sunFlowerGroup.update(index)
        sunFlowerGroup.draw(screen)
        peashooterGroup.update(index)
        peashooterGroup.draw(screen)
        bulletGroup.update(index)
        bulletGroup.draw(screen)
        zombieGroup.update(index)
        zombieGroup.draw(screen)
        wallnutGroup.update(index)
        wallnutGroup.draw(screen)
        sunGroup.update(index)
        sunGroup.draw(screen)

        (x, y) = pygame.mouse.get_pos()
        if choose == 1:
            screen.blit(sunflowerImg, (x, y))
        elif choose == 2:
            screen.blit(peashooterImg, (x, y))
        elif choose == 3:
            screen.blit(wallnutImg, (x, y))
        for event in pygame.event.get():
            if event.type == GEN_SUN_EVENT:
                for sprite in sunFlowerGroup:
                    now = time.time()
                    if now - sprite.lasttime >= 5:
                        sun = Sun(sprite.rect)
                        sunGroup.add(sun)
                        sprite.lasttime = now

            if event.type == GEN_BULLET_EVENT:
                for sprite in peashooterGroup:
                    bullet = Bullet(sprite.rect, backgdsize)
                    bulletGroup.add(bullet)

            if event.type == GEN_ZOMBIE_EVENT:
                zombie = Zombie()
                zombieGroup.add(zombie)

            if event.type == GEN_FLAGZOMBIE_EVENT:
                flagzombie = Flagzombie()
                zombieGroup.add(flagzombie)

            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                pressed_key = pygame.mouse.get_pressed()
                if pressed_key[0] == 1:
                    x, y = pygame.mouse.get_pos()
                    print(x, y)
                    if 320 <= x <= 382 and 0 <= y <= 89 and text >= 50:
                        # 点中了太阳花
                        choose = 1
                    elif 383 <= x < 446 and 0 <= y <= 89 and text >= 100:
                        # 点中了豌豆射手
                        choose = 2
                    elif 447 <= x < 511 and 0 <= y <= 89 and text >= 50:
                        # 点中了坚果墙
                        choose = 3
                    elif 250 < x < 1200 and 90 < y < 600:
                        if choose == 1:
                            current_time = time.time()
                            sunflower = Sunflower(current_time)
                            sunflower.rect.x = x
                            sunflower.rect.y = y
                            sunFlowerGroup.add(sunflower)
                            choose = 0

                            text -= 50
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))
                        elif choose == 2:
                            peashooter = Peashooter()
                            peashooter.rect.y = y
                            peashooter.rect.x = x
                            peashooterGroup.add(peashooter)
                            choose = 0

                            text -= 100
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))
                        elif choose == 3:
                            wallnut = Wallnut()
                            wallnut.rect.y = y
                            wallnut.rect.x = x
                            wallnutGroup.add(wallnut)
                            choose = 0

                            text -= 50
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))
                    for sun in sunGroup:
                        if sun.rect.collidepoint(x, y):
                            sunGroup.remove(sun)
                            text += 50
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))

        pygame.display.update()
Example #23
0
        for a_sun in self._sun:
            print(a_sun)


if __name__ == '__main__':

    try:
        solSys1 = Solar_System()
        solSys1.add_sun('porcupine')
        print(solSys1)
    except TypeError as ve:
        print('Dealt with TypeError:', ve)

    try:
        solSys2 = Solar_System()
        sunny4 = Sun('Mayonnaise', 5, 14, 3, 23, 'yellow')
        solSys2.add_sun(sunny4)
        print(solSys2)
    except TypeError as ve:
        print('Dealt with TypeError:', ve)

    try:
        solSys3 = Solar_System()
        solSys3.add_planet('pineapple')
        print(solSys3)
    except TypeError as ve:
        print('Dealt with TypeError:', ve)

    try:
        solSys4 = Solar_System()
        planet4 = Planet('Pedro', 5, 2, 5, 'red')
Example #24
0
def getSunsetTime(longitude, latitude):
    from sun import Sun
    coords = {'longitude': longitude, 'latitude': latitude}
    sun = Sun()
    sunset = sun.getSunsetTime(coords)
    return utc2local_time(sunset['hr'], sunset['min'])
coord1 = [10.32522211465866, 55.47169437449494]
coord2 = [10.32524982538288, 55.47166787993427]
coord3 = [10.32531271941916, 55.47168811627513]
coord4 = [10.32528783658924, 55.47171798510018]

utm1 = utm.from_latlon(coord1[1], coord1[0])
utm2 = utm.from_latlon(coord2[1], coord2[0])
utm3 = utm.from_latlon(coord3[1], coord3[0])
utm4 = utm.from_latlon(coord4[1], coord4[0])

lat = 55.471689
lon = 10.325267
utm_center = utm.from_latlon(lat, lon)

s = Sun(lat, lon)
m = Mission(0.8, 0.8)

local1 = [utm_center[0] - utm1[0], utm_center[1] - utm1[1]]
local2 = [utm_center[0] - utm2[0], utm_center[1] - utm2[1]]
local3 = [utm_center[0] - utm3[0], utm_center[1] - utm3[1]]
local4 = [utm_center[0] - utm4[0], utm_center[1] - utm4[1]]

height = 2.0
east_wall = Boundary(local1[0], local1[1], 0.0, local2[0], local2[1], 0.0,
                     local1[0], local1[1], height, "wall", s.get_lightsource())
south_window = Boundary(0.3857, -2.1862, 0.5, 1.3943, -1.532, 0.8, 0.3857,
                        -2.1862, 0.5 + 0.6, "window", s.get_lightsource())
north_wall = Boundary(local2[0], local2[1], 0.0, local3[0], local3[1],
                      0.0, local2[0], local2[1], height, "wall",
                      s.get_lightsource())