Exemplo n.º 1
0
def create_water(ai_settings, screen, waters, water_number, list_number):
    '''创建一个外星人并将其放在当前行'''
    water = Water(ai_settings, screen)
    water_height = water.rect.height
    water.y = water.rect.height + 2 * water.rect.height * water_number
    water.rect.y = water.y
    water.rect.x = water.rect.width + 2 * water.rect.width * list_number
    waters.add(water)
Exemplo n.º 2
0
def place_water(pos, water_blocks, water_rects, other_blocks1, other_blocks2, image):
	water = Water(image)
	water.rect.center = pos
	while not water.rect.right % 15 == 0:
		water.rect = water.rect.move(-1, 0)
	while not water.rect.bottom % 15 == 0:
		water.rect = water.rect.move(0, -1)
	if water.rect.collidelist(water_rects) < 0 and  water.rect.collidelist(other_blocks1) < 0 and  water.rect.collidelist(other_blocks2) < 0:
		water_blocks.append(water)
	return water_blocks
Exemplo n.º 3
0
def tracker():
    form = Waterer(request.form)
    if request.method=="POST":
        fire = form.water.data
        fire2= form.water2.data
        fire3= form.water3.data

        fire6= form.note1.data
        fire7= form.note2.data
        fire8 = form.pain1.data


        fire10= Water(fire,fire2,fire3,fire6,fire7,fire8)

        water_db = root.child('water')
        water_db.push({
            'Water': fire10.get_water(),
            "Water2": fire10.get_water2(),
            "Water3": fire10.get_water3(),
            "Note1": fire10.get_note1(),
            "Note2": fire10.get_note2(),
            "Pain1": fire10.get_pain1(),

        })
    return render_template('tracker.html',form=form)
Exemplo n.º 4
0
    def __init__(self):
        self._my_exchange_table = \
            [[0 for col in range(self._NUMBER_OF_RSC + 1)] for row in range(self._NUMBER_OF_RSC + 1)]
        self._other_exchange_table = \
            [[0 for col in range(self._NUMBER_OF_RSC + 1)] for row in range(self._NUMBER_OF_RSC + 1)]

        self._rsc_enum = {'food': 0, 'water': 1}

        # Information of Civilization
        self._total_population = 0
        self._total_tools = 0

        # Initialize it
        self._init_rsc_table(self._my_exchange_table, -1)
        self._init_rsc_table(self._other_exchange_table, -1)

        self._degree_of_civilized = 0

        # Resource Object List
        self._food = Food(0)
        self._water = Water(0)

        # Person Object Lists
        # 여기 수정중
        self._food_maker = FoodMaker(has_tool=0,
                                     _food=self._food,
                                     _water=self._water,
                                     _population=0)
        self._water_maker = WaterMaker(has_tool=0,
                                       _food=self._food,
                                       _water=self._water,
                                       _population=0)

        # Communication Data(Dictionary)
        self._civil1_info_dic = {
            'Civil1_NumPeople': self._total_population,
            'Civil1_Food': self._food.getquantity(),
            'Civil1_Water': self._water.getquantity(),
            'Civil1_DegOfCivilized': self._degree_of_civilized,
        }
        self._civil2_info_dic = {
            'Civil2_NumPeople': 0,
            'Civil2_Food': 0,
            'Civil2_Water': 0,
            'Civil2_DegOfCivilized': 0,
        }

        self._db_manager = DBManager.DBManager(
            civil_dic1=self._civil1_info_dic, civil_dic2=self._civil2_info_dic)
Exemplo n.º 5
0
def diabetes():
    water = root.child('water').get()
    list = []

    for pubid in water:

        admindata=water[pubid]

        if admindata['Note1'] != " ":
            admindatapage=Water(admindata['Water'],admindata['Water2'],admindata['Water3'],admindata['Note1'],admindata['Pain1'],admindata['Note2'])
            admindatapage.set_pubid(pubid)
            print(admindatapage.get_pubid())
            list.append(admindatapage)

    return render_template('diabetesedit.html', water=list)
Exemplo n.º 6
0
 def add_water(self):
     """
     Add Water() obj to values in dict.
     """
     for coordinate in self.coordinates:
         if coordinate not in list(self.board.keys()):
             self.board[coordinate] = Water()
Exemplo n.º 7
0
 def action(self):
     x = self.__outer.x
     y = self.__outer.y
     water_over = self.__outer.water_amount - self.__outer.water_capacity
     water = Water(self.__outer._ecosystem, x, y, water_over )
     self.__outer._ecosystem.water_map[x][y] = water
     self.__outer._ecosystem.plant_map[x][y] = None
     self.__outer._ecosystem.flower_map[x][y].clear()
     self._status = bt.Status.FAIL
Exemplo n.º 8
0
def create_waters(ai_settings, screen, waters):
    '''创建外星人群'''
    #创建第一行外星人
    water = Water(ai_settings, screen)
    number_waters_x = get_number_waters_x(ai_settings, water.rect.width)
    number_waters_y = get_number_waters_y(ai_settings, water.rect.height)
    for number_list in range(number_waters_x):
        for water_number in range(number_waters_y):
            create_water(ai_settings, screen, waters, water_number,
                         number_list)
Exemplo n.º 9
0
    def __init__(self, initial_generator):
        self.seed()
        self.viewer = None

        self.world = Box2D.b2World()
        self.ship = None
        self.lander = None
        self.particles = []
        self.water = Water([0, 1], force_const_volume=True)

        self.prev_reward = None

        self.origin = (W / 2, H / 20)

        # dummy initial variables, will be set in update_initials
        self.initial_pos_x = self.origin[0]
        self.initial_pos_y = self.origin[1] + H / 2
        self.initial_vel = 0
        self.initial_dir = 0
        self.initial_vdir = 0
        self.ship_width = 100
        # non constant hyperparameters
        self.initial_generator = initial_generator
        self.difficulty = 0.1

        self.steps = 0

        high = np.array(
            [np.inf] * 8)  # useful range is -1 .. +1, but spikes can be higher
        self.observation_space = spaces.Box(-high, high)

        if self.continuous:
            # Action is two floats [main engine, left-right engines].
            # Main engine: -1..0 off, 0..+1 throttle from 50% to 100% power. Engine can't work with less than 50% power.
            # Left-right:  -1.0..-0.5 fire left engine, +0.5..+1.0 fire right engine, -0.5..0.5 off
            self.action_space = spaces.Box(-1, +1, (2, ))
        else:
            # Nop, fire left engine, main engine, right engine
            self.action_space = spaces.Discrete(4)

        self.reset()
Exemplo n.º 10
0
def calc_wettable_squares_from_file(filename):
    ground = create_ground_slice(filename)
    wx = ground.well_coordinate[0]
    wy = ground.well_coordinate[1] + 1
    water = Water(wx, wy, ground, None)
    squares_to_check = [(wx, wy)]

    while squares_to_check:
        # print(f'{len(squares_to_check)} squares to check')
        new_squares_to_check = ground.check_square(squares_to_check.pop())
        squares_to_check.extend(new_squares_to_check)

    print(f'total wet squares: {ground.wet_squares}')
    print(f'wet squares in range: {ground.wet_squares_in_range}')
    return ground.wet_squares_in_range
Exemplo n.º 11
0
    def __init__(self, *args, **kwargs):
        self.power = ""
        # get data and merge on 'tds'
        if "Electricity" in args:
            self.power = "Electricity"
            self.data = Electricity().get_data(**kwargs)
        else:
            self.power = "Water"
            self.data = Water().get_data(**kwargs)
        self.coords = Coords().get_all_data()

        # cleanup the data
        self.merge_coords()
        self.add_year_column()
        self.set_dtypes()

        # compute df of mean consumption by (tds x year)
        self.tds_by_year = None
        self.get_by_year_data()

        # add other pre-computed dataframes here
        # ...
        self.tds_sum_year = None
        self.get_aggregate_data()
Exemplo n.º 12
0
Arquivo: scene.py Projeto: jkotur/duck
	def __init__( self , fov , ratio , near , far  , skybox_img , duck_img ) :
		self.fov = fov
		self.far = far
		self.near = near 
		self.ratio = ratio

		self.last_time = timer()

		self.water = Water( 128 )
		self.box   = Skybox( skybox_img )
		self.duck  = Mesh( 'data/duck.gpt' , duck_img , 'shad/anisotropic' )
		self.path  = BSpline( (-1,1) , (-1,1) )

		self.light = np.array( (0,2,0) )

		self.water.drop_rnd()
Exemplo n.º 13
0
def init_game():
    for y, row in enumerate(settings.field):
        for x, column in enumerate(row):
            if column == 1:
                settings.grass.append(
                    Grass(settings.main_surf, settings.field_size,
                          settings.cells_size, (x, y)))
            elif column == 2:
                settings.armor.append(
                    Armor(settings.main_surf, settings.field_size,
                          settings.cells_size, (x, y)))
            elif type(column) is list:

                for add_nums in column:
                    if add_nums[0] == 0:
                        if add_nums[1] % 2 == 0:
                            ind = 0
                        else:
                            ind = 3
                    else:
                        if add_nums[1] % 2 == 0:
                            ind = 2
                        else:
                            ind = 1

                    settings.bricks.append(
                        Brick(settings.main_surf, settings.field_size,
                              settings.cells_size,
                              (50 + settings.cells_size * x +
                               add_nums[0] * settings.cells_size // 2,
                               50 + settings.cells_size * y +
                               add_nums[1] * settings.cells_size // 4), ind))
            elif column == 4:
                settings.fin.append(
                    Fin(settings.main_surf, settings.field_size,
                        settings.cells_size, (x, y)))
                settings.fin_pos.append([x, y])

            elif column == 5:
                settings.spawns.append([x, y])
            elif column == 6:
                settings.bots_spawn.append([x, y])
            elif column == 7:
                settings.water.append(
                    Water(settings.main_surf, settings.field_size,
                          settings.cells_size, (x, y)))
Exemplo n.º 14
0
	def initGL(self):
		from skydome import Skydome

		if not glInitVertexBufferObjectARB():
			sys.stderr.write("ERROR: Vertex buffer objects is not supported\n")
			#Global.quit = 1
			return

		glClearColor( 0.0, 0.0, 0.0, 0.0)
		glClearDepth(1.0)
		glDepthFunc(GL_LEQUAL)
		glEnable(GL_DEPTH_TEST)
		glShadeModel(GL_SMOOTH)
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
		glViewport(0, 0, self.main.config.getint('Resolution', 'Width'),
				self.main.config.getint('Resolution', 'Height'))
		glMatrixMode(GL_PROJECTION)

		#glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0)

		glLoadIdentity()
		gluPerspective(60.0, self.main.config.getfloat('Resolution','Width')
				/ self.main.config.getfloat('Resolution', 'Height'), 0.1, 5000.0)
		glMatrixMode(GL_MODELVIEW)

		#Lighting
		diffuseMaterial = (0.5, 0.5, 0.0, 1.0)
		mat_specular = (1.0, 1.0, 1.0, 1.0)
		light_position = (150.0, 0.0, 75.0, 1.0)

		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, diffuseMaterial)
		glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseMaterial)
		glLightfv(GL_LIGHT1, GL_POSITION, light_position)

		glEnable(GL_LIGHTING)
		glDisable(GL_LIGHT0)
		glEnable(GL_LIGHT1)
		###########

		glEnable(GL_NORMALIZE)

		self.skydome = Skydome()

		if not self.main.args['disableWater']:
			self.water = Water()
Exemplo n.º 15
0
	def __init__( self , fovy , ratio , near , far ) :
		self.fovy = fovy
		self.near = near 
		self.far = far
		self.ratio = ratio

		self.camera = None

		self.water = Water()
		self.water.set_borders( (-10,10,-10,10,-10,10) )
#        self.water.set_borders( (-100,100,-10,1000,-100,100) )

		self.mode = 0

		def mkpln( s , p , r , a , c ) :
			p = Plane((s,s),np.dot(tr.translation_matrix(p),tr.rotation_matrix(r*m.pi/180.0,a)))
			p.c = c
			return p

#        self.borders = [
#                mkpln(200,(-100,0,0),-90,(0,0,1),(.4,1,0)) ,
#                mkpln(200,( 100,0,0), 90,(0,0,1),(.4,1,0)) ,
#                mkpln(200,(0,0,-100), 90,(1,0,0),(.4,1,0)) ,
#                mkpln(200,(0,0, 100),-90,(1,0,0),(.4,1,0)) ,
#                mkpln(200,(0,-10,0),  0,(1,0,0),(.4,1,0)) ]

		self.borders = [
				mkpln(20,(-10,0,0),-90,(0,0,1),(.4,1,0)) ,
				mkpln(20,( 10,0,0), 90,(0,0,1),(.4,1,0)) ,
				mkpln(20,(0,0,-10), 90,(1,0,0),(.4,1,0)) ,
				mkpln(20,(0,0, 10),-90,(1,0,0),(.4,1,0)) ,
				mkpln(20,(0,-10,0),  0,(1,0,0),(.4,1,0)) ,
				mkpln(20,(0, 10,0),180,(1,0,0),(.4,1,0)) ]

		self.x = 0.0

		self.last_time = timer()

		self.plane_alpha = 65.0 / 180.0 * m.pi

		self.lpos = [ 1 ,-1 , 0 ]
Exemplo n.º 16
0
def update_wiki(id):
    form=Waterer(request.form)
    if request.method=='POST':
        general=form.water2.data
        symptoms=form.water.data
        surgery=form.water3.data
        types=form.note1.data
        longtermeffect=form.pain1.data
        stay=form.note2.data

        wikiupdate=Water(symptoms,general,surgery,types,stay,longtermeffect)
        wikiupdate_db= root.child('water/'+id)

        wikiupdate_db.set({
            "Water2":wikiupdate.get_water2(),
            "Water":wikiupdate.get_water(),
            "Water3":wikiupdate.get_water3(),
            "Note1":wikiupdate.get_note1(),
            "Pain1":wikiupdate.get_pain1(),
            'Note2':wikiupdate.get_note2(),
        })

        flash('Magazine Updated Sucessfully.', 'success')

        return redirect(url_for('diabetes'))
    else:
        url = 'water/'+id
        wikidata=root.child(url).get()

        if wikidata['Water'] != " ":
            wikiadmin= Water(wikidata['Water'],wikidata['Water2'],wikidata['Water3'],wikidata['Note1'],wikidata['Note2'],wikidata['Pain1'])
            wikiadmin.set_pubid((id))
            form.water2.data=wikiadmin.get_water2()
            form.water.data=wikiadmin.get_water()
            form.water3.data=wikiadmin.get_water3()
            form.note1.data=wikiadmin.get_note1()
            form.pain1.data=wikiadmin.get_pain1()
            form.note2.data=wikiadmin.get_note2()

        return render_template('updatewiki.html',form=form)
Exemplo n.º 17
0
Arquivo: scene.py Projeto: jkotur/duck
class Scene :
	def __init__( self , fov , ratio , near , far  , skybox_img , duck_img ) :
		self.fov = fov
		self.far = far
		self.near = near 
		self.ratio = ratio

		self.last_time = timer()

		self.water = Water( 128 )
		self.box   = Skybox( skybox_img )
		self.duck  = Mesh( 'data/duck.gpt' , duck_img , 'shad/anisotropic' )
		self.path  = BSpline( (-1,1) , (-1,1) )

		self.light = np.array( (0,2,0) )

		self.water.drop_rnd()

	def gfx_init( self ) :
		self.camera = Camera( ( 0 , 5 ,  0 ) , ( 1 , 1 , 0 ) , ( 1 , 0 , 0 ) )
		self._update_proj()

		self.water.gfx_init()
		self.box  .gfx_init()
		self.duck .gfx_init()

	def draw( self ) :
		self.time = timer()
		dt = self.time - self.last_time

		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()
			   
		self.camera.look()

		self.box.draw()

		self.path.next( dt )
		self.water.drop( *((self.path.value+1.0)*self.water.n/2.0) ,
				force = np.linalg.norm(self.path.tangent)*25 )
		self.water.step( dt * .5 )
		self.water.draw( self.box.texture , self.camera.matrix )

		self.duck.draw( self.path.value , self.path.tangent , self.light )

		self.last_time = self.time

	def set_fov( self , fov ) :
		self.fov = fov
		self._update_proj()

	def set_near( self , near ) :
		self.near = near
		self._update_proj()

	def set_ratio( self , ratio ) :
		self.ratio = ratio
		self._update_proj()

	def set_screen_size( self , w , h ) :
		self.width  = w 
		self.height = h
		self.set_ratio( float(w)/float(h) )

	def set_fov( self , fov ) :
		self.fov = fov
		self._update_proj()

	def set_near( self , near ) :
		self.near = near
		self._update_proj()

	def set_ratio( self , ratio ) :
		self.ratio = ratio
		self._update_proj()

	def set_screen_size( self , w , h ) :
		self.width  = w
		self.height = h
		self.set_ratio( float(w)/float(h) )

	def mouse_move( self , df ) :
		self.camera.rot( *map( lambda x : -x*.2 , df ) )

	def key_pressed( self , mv ) :
		self.camera.move( *map( lambda x : x*.05 , mv ) )

	def _update_proj( self ) :                                         
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluPerspective( self.fov , self.ratio , self.near , self.far )
		glMatrixMode(GL_MODELVIEW)
Exemplo n.º 18
0
def create_water_s(x, y, n=2):
    wall_list = []
    for i in range(n):
        wall = Water(x, y+60*i)
        wall_list.append(wall)
    return wall_list
Exemplo n.º 19
0
def create_water_h(x, y, n=2):
    water_list = []
    for i in range(n):
        water = Water(x+60*i, y)
        water_list.append(water)
    return water_list
Exemplo n.º 20
0
# Boat
boat_img = pygame.image.load('cargo_ship_1.png')
boat_X = 355
boat_Y = 505
boat_X_change = 0
boat_Y_change = 0


def boat_move(boat_X):
    screen.blit(boat_img, (boat_X, boat_Y))


# Water Section /*/*/*/

# defining water class
w1 = Water()


# Movement of water..
def moving_water():
    for i in range(w1.wave_len):
        for j in range(w1.wave_wid):
            screen.blit(w1.W_wave_img[i][j],
                        (w1.W_wave_X[i][j], w1.W_wave_Y[i][j]))
            w1.wave_move()
    # pygame.display.update()


# Object Section /*/*/*/

# Objects making
Exemplo n.º 21
0
import threading
from water import Water
from communication import Communication
from db import Connection
from sensoren import Sensoren
import time
from apiMain import start

#com = Communication("RPI", "192.168.2.156

com = Communication("RPI", "0.0.0.0")
sensoren = Sensoren(pinRain=22, pinVent1=17, pinVent2=27)
water = Water(com, sensoren)

db = Connection(host="localhost",
                user="******",
                password="******",
                database="sensor_data")

t_com = threading.Thread(target=com.server)
t_sensoren = threading.Thread(target=sensoren.update_data)
t_water = threading.Thread(target=water.main)
t_api = threading.Thread(target=start)

if __name__ == '__main__':
    print("Starting")
    t_com.start()
    t_sensoren.start()
    t_water.start()
    t_api.start()
Exemplo n.º 22
0
def main():
    global SCREEN_FULLSCREEN
    pygame.init()

    util.load_config()

    if len(sys.argv) > 1:
        for arg in sys.argv:
            if arg == "-np":
                Variables.particles = False
            elif arg == "-na":
                Variables.alpha = False
            elif arg == "-nm":
                Variables.music = False
            elif arg == "-ns":
                Variables.sound = False
            elif arg == "-f":
                SCREEN_FULLSCREEN = True

    scr_options = 0
    if SCREEN_FULLSCREEN: scr_options += FULLSCREEN
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),scr_options ,32)

    pygame.display.set_icon(util.load_image("kuvake"))
    pygame.display.set_caption("Trip on the Funny Boat")

    init()

    joy = None
    if pygame.joystick.get_count() > 0:
        joy = pygame.joystick.Joystick(0)
        joy.init()

    try:
        util.load_music("JDruid-Trip_on_the_Funny_Boat")
        if Variables.music:
            pygame.mixer.music.play(-1)
    except:
        # It's not a critical problem if there's no music
        pass

    pygame.time.set_timer(NEXTFRAME, 1000 / FPS) # 30 fps

    Water.global_water = Water()

    main_selection = 0

    while True:
        main_selection = Menu(screen, ("New Game", "High Scores", "Options", "Quit"), main_selection).run()
        if main_selection == 0:
            # New Game
            selection = Menu(screen, ("Story Mode", "Endless Mode")).run()
            if selection == 0:
                # Story
                score = Game(screen).run()
                Highscores(screen, score).run()
            elif selection == 1:
                # Endless
                score = Game(screen, True).run()
                Highscores(screen, score, True).run()
        elif main_selection == 1:
            # High Scores
            selection = 0
            while True:
                selection = Menu(screen, ("Story Mode", "Endless Mode", "Endless Online"), selection).run()
                if selection == 0:
                    # Story
                    Highscores(screen).run()
                elif selection == 1:
                    # Endless
                    Highscores(screen, endless = True).run()
                elif selection == 2:
                    # Online
                    Highscores(screen, endless = True, online = True).run()
                else:
                    break
        elif main_selection == 2:
            # Options
            selection = Options(screen).run()
        else: #if main_selection == 3:
            # Quit
            return
Exemplo n.º 23
0
def main():
    pygame.init()

    noparticles = False
    usealpha = True

    if len(sys.argv) > 1:
        for arg in sys.argv:
            if arg == "-np":
                noparticles = True
            elif arg == "-na":
                usealpha = False

    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

    pygame.display.set_icon(util.load_image("kuvake"))
    pygame.display.set_caption("Trip on the Funny Boat")

    init()

    joy = None
    if pygame.joystick.get_count() > 0:
        joy = pygame.joystick.Joystick(0)
        joy.init()

    try:
        util.load_music("JDruid-Trip_on_the_Funny_Boat")
        pygame.mixer.music.play(-1)
    except:
        pass

    pygame.time.set_timer(NEXTFRAME, 1000 / FPS)  # 30 fps

    Water.global_water = Water(usealpha)

    while True:
        selection = Menu(screen).run()
        if selection == Menu.NEWGAME:
            #print "New game!"
            selection = Menu(screen, gametype_select=True).run()
            if selection == Menu.STORY:
                score = Game(screen, usealpha, noparticles).run()
                #print "Final score: " + str(score)
                Highscores(screen, score).run()
            elif selection == Menu.ENDLESS:
                score = Game(screen, usealpha, noparticles, True).run()
                #print "Final score: " + str(score)
                Highscores(screen, score, True).run()
        elif selection == Menu.HIGHSCORES:
            #print "High scores!"
            selection = Menu(screen, gametype_select=True).run()
            if selection == Menu.STORY:
                Highscores(screen).run()
            elif selection == Menu.ENDLESS:
                Highscores(screen, endless=True).run()
        #elif selection == Menu.OPTIONS:
        #print "Options!"
        #elif selection == Menu.QUIT:
        else:
            #print "Quit! :-("
            return
Exemplo n.º 24
0
class Data:
    def __init__(self, *args, **kwargs):
        self.power = ""
        # get data and merge on 'tds'
        if "Electricity" in args:
            self.power = "Electricity"
            self.data = Electricity().get_data(**kwargs)
        else:
            self.power = "Water"
            self.data = Water().get_data(**kwargs)
        self.coords = Coords().get_all_data()

        # cleanup the data
        self.merge_coords()
        self.add_year_column()
        self.set_dtypes()

        # compute df of mean consumption by (tds x year)
        self.tds_by_year = None
        self.get_by_year_data()

        # add other pre-computed dataframes here
        # ...
        self.tds_sum_year = None
        self.get_aggregate_data()

    # Merging coordinates with other datasets on TDS value
    def merge_coords(self):
        """
        Merge the coords into (lat,long) into the data
        """
        self.data = self.data.merge(self.coords, on="tds")

    # Setting the datatype of the merged dataset
    def set_dtypes(self):
        """
        Set the datatypes to intended types
        """
        self.data.latitude = self.data.latitude.astype(float)
        self.data.longitude = self.data.longitude.astype(float)
        self.data.year = self.data.year.astype(int)
        if self.power == "Electricity":
            self.data.consumption_kwh = self.data.consumption_kwh.astype(float)
        else:
            self.data.consumption_hcf = self.data.consumption_hcf.astype(float)

    # Adding a year column from the revenue month column
    def add_year_column(self):
        """
        Create a new column with the year from revenue_month
        """
        years = self.data["revenue_month"].apply(lambda x: int(x.split("-")[0]))
        self.data["year"] = years

    # Getting the mean consumption for each year
    def get_by_year_data(self):
        """
        Get difference in the mean consumption between years.
        """
        if self.power == "Electricity":
            self.tds_by_year = self.data.groupby(["tds", "year"]).consumption_kwh.mean()
        else:
            self.tds_by_year = self.data.groupby(["tds", "year"]).consumption_hcf.mean()

    # Getting the total consumption for each year
    def get_aggregate_data(self):
        """
        Get the total consumption for each year
        """
        if self.power == "Electricity":
            self.tds_sum_year = self.data.groupby(["tds", "year"]).consumption_kwh.sum()
        else:
            self.tds_sum_year = self.data.groupby(["tds", "year"]).consumption_hcf.sum()
Exemplo n.º 25
0
class Scene :
	def __init__( self , fovy , ratio , near , far ) :
		self.fovy = fovy
		self.near = near 
		self.far = far
		self.ratio = ratio

		self.camera = None

		self.water = Water()
		self.water.set_borders( (-10,10,-10,10,-10,10) )
#        self.water.set_borders( (-100,100,-10,1000,-100,100) )

		self.mode = 0

		def mkpln( s , p , r , a , c ) :
			p = Plane((s,s),np.dot(tr.translation_matrix(p),tr.rotation_matrix(r*m.pi/180.0,a)))
			p.c = c
			return p

#        self.borders = [
#                mkpln(200,(-100,0,0),-90,(0,0,1),(.4,1,0)) ,
#                mkpln(200,( 100,0,0), 90,(0,0,1),(.4,1,0)) ,
#                mkpln(200,(0,0,-100), 90,(1,0,0),(.4,1,0)) ,
#                mkpln(200,(0,0, 100),-90,(1,0,0),(.4,1,0)) ,
#                mkpln(200,(0,-10,0),  0,(1,0,0),(.4,1,0)) ]

		self.borders = [
				mkpln(20,(-10,0,0),-90,(0,0,1),(.4,1,0)) ,
				mkpln(20,( 10,0,0), 90,(0,0,1),(.4,1,0)) ,
				mkpln(20,(0,0,-10), 90,(1,0,0),(.4,1,0)) ,
				mkpln(20,(0,0, 10),-90,(1,0,0),(.4,1,0)) ,
				mkpln(20,(0,-10,0),  0,(1,0,0),(.4,1,0)) ,
				mkpln(20,(0, 10,0),180,(1,0,0),(.4,1,0)) ]

		self.x = 0.0

		self.last_time = timer()

		self.plane_alpha = 65.0 / 180.0 * m.pi

		self.lpos = [ 1 ,-1 , 0 ]

	def gfx_init( self ) :
		self.camera = Camera( ( 0 , 20 ,50 ) , ( 0 , 0 , 0 ) , ( 0 , 1 , 0 ) )

		self.water.gfx_init()

		self._update_proj()

		glEnable( GL_DEPTH_TEST )
		glEnable( GL_NORMALIZE )
		glEnable( GL_CULL_FACE )
		glEnable( GL_COLOR_MATERIAL )
		glColorMaterial( GL_FRONT , GL_AMBIENT_AND_DIFFUSE )

	def draw( self ) :
		self.time = timer()

		dt = self.time - self.last_time

		self._step( dt )

		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

		self.camera.look()

		self.lpos = [ 3,2,1 ]

		self._set_lights()

		self._draw_scene()

		self.x+=dt*.3

		self.last_time = self.time

	def _step( self , dt ) :
		self.water.wave( dt )

	def _draw_scene( self ) :
		glTranslatef( -1.5 , - 1.5 , -1.5 )
		glCullFace( GL_BACK )
		self.water.draw()
		glCullFace( GL_FRONT )
		for b in self.borders :
			glColor3f( *b.c )
			b.draw()

	def _update_proj( self ) :
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluPerspective( self.fovy , self.ratio , self.near , self.far )
		glMatrixMode(GL_MODELVIEW)

	def _set_lights( self ) :
		glEnable(GL_LIGHTING);
		glLightfv(GL_LIGHT0, GL_AMBIENT, [ 0.2 , 0.2 , 0.2 ] );
		glLightfv(GL_LIGHT0, GL_DIFFUSE, [ 0.5 , 0.5 , 0.5 ] );
		glLightfv(GL_LIGHT0, GL_SPECULAR,[ 0.0 , 0.0 , 0.0 ] );
		glLightfv(GL_LIGHT0, GL_POSITION, self.lpos );
		glEnable(GL_LIGHT0); 

	def set_fov( self , fov ) :
		self.fov = fov
		self._update_proj()

	def set_near( self , near ) :
		self.near = near
		self._update_proj()

	def set_ratio( self , ratio ) :
		self.ratio = ratio
		self._update_proj()

	def set_screen_size( self , w , h ) :
		self.width  = w 
		self.height = h
		self.set_ratio( float(w)/float(h) )

	def mouse_move( self , df , buts ) :
		if 3 in buts and buts[3] :
			self.camera.rot( *map( lambda x : -x*.2 , df ) )

	def key_pressed( self , mv ) :
		self.camera.move( *map( lambda x : x*.25 , mv ) )

	def toggle_control( self ) :
		self.mode = not self.mode

	def set_model( self , mtype ) :
		if mtype == 0 :
			self.water.set( Water.SPH_T )
		elif mtype == 1 :
			self.water.set( Water.LBM_T )
Exemplo n.º 26
0
class Civilization:
    # const
    _NUMBER_OF_RSC = 1
    CIVILNUM = 1

    def __init__(self):
        self._my_exchange_table = \
            [[0 for col in range(self._NUMBER_OF_RSC + 1)] for row in range(self._NUMBER_OF_RSC + 1)]
        self._other_exchange_table = \
            [[0 for col in range(self._NUMBER_OF_RSC + 1)] for row in range(self._NUMBER_OF_RSC + 1)]

        self._rsc_enum = {'food': 0, 'water': 1}

        # Information of Civilization
        self._total_population = 0
        self._total_tools = 0

        # Initialize it
        self._init_rsc_table(self._my_exchange_table, -1)
        self._init_rsc_table(self._other_exchange_table, -1)

        self._degree_of_civilized = 0

        # Resource Object List
        self._food = Food(0)
        self._water = Water(0)

        # Person Object Lists
        # 여기 수정중
        self._food_maker = FoodMaker(has_tool=0,
                                     _food=self._food,
                                     _water=self._water,
                                     _population=0)
        self._water_maker = WaterMaker(has_tool=0,
                                       _food=self._food,
                                       _water=self._water,
                                       _population=0)

        # Communication Data(Dictionary)
        self._civil1_info_dic = {
            'Civil1_NumPeople': self._total_population,
            'Civil1_Food': self._food.getquantity(),
            'Civil1_Water': self._water.getquantity(),
            'Civil1_DegOfCivilized': self._degree_of_civilized,
        }
        self._civil2_info_dic = {
            'Civil2_NumPeople': 0,
            'Civil2_Food': 0,
            'Civil2_Water': 0,
            'Civil2_DegOfCivilized': 0,
        }

        self._db_manager = DBManager.DBManager(
            civil_dic1=self._civil1_info_dic, civil_dic2=self._civil2_info_dic)

    def _init_rsc_table(self, _table, num):
        for r in range(0, self._NUMBER_OF_RSC + 1):
            for c in range(0, self._NUMBER_OF_RSC + 1):
                if r is c:
                    pass
                else:
                    _table[r][c] = num

    # Produce Resource
    def rsc_produce(self):
        self._food_maker.make_food()
        self._water_maker.make_water()

    # Consume Resource
    def rsc_comsume(self):
        # Consume Foods
        self._food_maker.consume_food()
        self._water_maker.consume_food()

        # Consume Water
        self._food_maker.consume_water()
        self._water_maker.consume_water()

    # Exchange
    def exchange_rsc(self):
        print("Exchange Resources!!")

    # Check if is insufficient
    def is_rsc_insufficient(self, kind_of_food):
        if kind_of_food.getquantity() < self._total_population * 2:
            return True
        else:
            return False

    def get_db_manager(self):
        return self._db_manager

    # amount of person movement
    def person_movement(self):

        civil1_pop = self._civil1_info_dic['Civil1_NumPeople']
        civil2_pop = self._civil2_info_dic['Civil2_NumPeople']

        d_p = 10

        if civil1_pop < civil2_pop:
            d_p *= -1
        else:
            d_p *= 1

        self._civil1_info_dic['Civil1_NumPeople'] += d_p
        self._civil2_info_dic['Civil2_NumPeople'] -= d_p

    def change_ratio_of_maker(self):
        sum_of_importance = self._food._importance + self._water._importance
        ratio_of_foodmaker = self._food._importance / sum_of_importance
        self._food_maker._population = int(self._total_population *
                                           ratio_of_foodmaker)
        self._water_maker._population = self._total_population - self._food_maker._population

    def set_rsc_importance(self):
        self._set_importance(self._food)
        self._set_importance(self._water)

    def _set_importance(self, kind_of_rsc):
        # Importance of each Resource, Life resource amend
        importance_limit = self._total_population * 2

        if kind_of_rsc.is_life_rsc() is True:
            importance_limit *= kind_of_rsc.CONST_LIFE_RESOURCE

        if kind_of_rsc.getquantity() < importance_limit:
            kind_of_rsc._importance += abs(self._food.getquantity() -
                                           self._water.getquantity()) / 2
        else:
            kind_of_rsc._importance = 100

    def set_first_info(self, civil_num):
        name_str = 'Civil' + str(civil_num) + '_'
        _civil_info_dic = self.get_db_manager().download_db(civil_num)

        # IF CivilNumber different from database, not update local
        if civil_num is not self.CIVILNUM:
            pass
        else:
            self._total_population = _civil_info_dic[name_str + 'NumPeople']
            self._food.setquantity(_civil_info_dic[name_str + 'Food'])
            self._water.setquantity(_civil_info_dic[name_str + 'Water'])
            self._degree_of_civilized = _civil_info_dic[name_str +
                                                        'DegOfCivilized']

        if civil_num is 1:
            self._civil1_info_dic = _civil_info_dic
        else:
            self._civil2_info_dic = _civil_info_dic

    # Civilization 1
    def _civil1_save_data_in_dic(self):
        self._civil1_info_dic = {
            'Civil1_NumPeople': self._total_population,
            'Civil1_Food': self._food.getquantity(),
            'Civil1_Water': self._water.getquantity(),
            'Civil1_DegOfCivilized': self._degree_of_civilized,
        }

    # Civilization 2
    def _civil2_save_data_in_dic(self):
        # Get the data from server
        self._civil2_info_dic = {
            'Civil2_NumPeople': 0,
            'Civil2_Food': 0,
            'Civil2_Water': 0,
            'Civil2_DegOfCivilized': 0,
        }

    def update_info_dic(self, num_of_civil):
        if num_of_civil is 1:
            self._civil1_save_data_in_dic()
        else:
            self._civil2_save_data_in_dic()

    def print_rsc_quantity(self):
        print('Food :' + str(self._food.getquantity()))
        print('Water:' + str(self._water.getquantity()))

    def get_info_dic(self, civil_num):
        if civil_num is 1:
            return self._civil1_info_dic
        else:
            return self._civil2_info_dic
Exemplo n.º 27
0
class Lander(gym.Env):
    metadata = {
        'render.modes': ['human', 'rgb_array'],
        'video.frames_per_second': FPS
    }

    continuous = False

    def __init__(self, initial_generator):
        self.seed()
        self.viewer = None

        self.world = Box2D.b2World()
        self.ship = None
        self.lander = None
        self.particles = []
        self.water = Water([0, 1], force_const_volume=True)

        self.prev_reward = None

        self.origin = (W / 2, H / 20)

        # dummy initial variables, will be set in update_initials
        self.initial_pos_x = self.origin[0]
        self.initial_pos_y = self.origin[1] + H / 2
        self.initial_vel = 0
        self.initial_dir = 0
        self.initial_vdir = 0
        self.ship_width = 100
        # non constant hyperparameters
        self.initial_generator = initial_generator
        self.difficulty = 0.1

        self.steps = 0

        high = np.array(
            [np.inf] * 8)  # useful range is -1 .. +1, but spikes can be higher
        self.observation_space = spaces.Box(-high, high)

        if self.continuous:
            # Action is two floats [main engine, left-right engines].
            # Main engine: -1..0 off, 0..+1 throttle from 50% to 100% power. Engine can't work with less than 50% power.
            # Left-right:  -1.0..-0.5 fire left engine, +0.5..+1.0 fire right engine, -0.5..0.5 off
            self.action_space = spaces.Box(-1, +1, (2, ))
        else:
            # Nop, fire left engine, main engine, right engine
            self.action_space = spaces.Discrete(4)

        self.reset()

    def seed(self, seed=None):
        self.np_random, seed = seeding.np_random(seed)
        return [seed]

    def _destroy(self):
        if not self.ship: return
        self.world.contactListener = None
        self._clean_particles(True)
        self.world.DestroyBody(self.ship)
        self.ship = None
        self.world.DestroyBody(self.lander)
        self.lander = None
        self.world.DestroyBody(self.legs[0])
        self.world.DestroyBody(self.legs[1])

    def reset(self):
        self.update_initials()

        self._destroy()
        self.world.contactListener_keepref = ContactDetector(self)
        self.world.contactListener = self.world.contactListener_keepref
        self.game_over = False
        self.prev_shaping = None

        # ship
        self.ship = self.world.CreateStaticBody(
            position=self.origin,
            shapes=polygonShape(
                vertices=[(x / SCALE, y / SCALE)
                          for x, y in SHIP['vertices'](self.ship_width)]))

        self.ship.color1 = SHIP['color1']
        self.ship.color2 = SHIP['color2']

        # lander
        self.lander = self.world.CreateDynamicBody(
            position=(self.initial_pos_x, self.initial_pos_y),
            angle=self.initial_dir,
            fixtures=fixtureDef(
                shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                             for x, y in ROCKET['vertices']]),
                density=5.0,
                friction=0.1,
                categoryBits=0x0010,
                maskBits=0x001,  # collide only with ground
                restitution=0.0)  # 0.99 bouncy
        )
        self.lander.color1 = ROCKET['body_color1']
        self.lander.color2 = ROCKET['body_color2']
        self.lander.ApplyForceToCenter(
            (self.initial_vel * math.sin(self.initial_dir),
             -self.initial_vel * math.cos(self.initial_dir)), True)
        self.lander.ApplyAngularImpulse(self.initial_vdir, True)

        self.legs = []
        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(self.initial_pos_x - i * ROCKET['leg_away'] / SCALE,
                          self.initial_pos_y),
                angle=self.initial_dir + i * 0.05,
                fixtures=fixtureDef(
                    shape=polygonShape(box=(ROCKET['leg_w'] / SCALE,
                                            ROCKET['leg_h'] / SCALE)),
                    density=1.0,
                    restitution=0.0,
                    categoryBits=0x0020,
                    maskBits=0x001))
            leg.ground_contact = False
            leg.color1 = ROCKET['leg_color1']
            leg.color2 = ROCKET['leg_color2']
            rjd = revoluteJointDef(
                bodyA=self.lander,
                bodyB=leg,
                localAnchorA=(0, 0),
                localAnchorB=(i * ROCKET['leg_away'] / SCALE,
                              ROCKET['leg_down'] / SCALE),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=ROCKET['leg_spring_torque'],
                motorSpeed=+0.3 * i  # low enough not to jump back into the sky
            )
            if i == -1:
                rjd.lowerAngle = +0.9 - 0.5  # Yes, the most esoteric numbers here, angles legs have freedom to travel within
                rjd.upperAngle = +0.9
            else:
                rjd.lowerAngle = -0.9
                rjd.upperAngle = -0.9 + 0.5
            leg.joint = self.world.CreateJoint(rjd)
            self.legs.append(leg)

        self.drawlist = [self.lander, self.ship] + self.legs

        return self.step(np.array([0, 0]) if self.continuous else 0)[0]

    def _create_particle(self, mass, x, y, ttl):
        p = self.world.CreateDynamicBody(
            position=(x, y),
            angle=0.0,
            fixtures=fixtureDef(
                shape=circleShape(radius=5 / SCALE, pos=(0, 0)),
                density=mass,
                friction=0.1,
                categoryBits=0x0100,
                maskBits=0x001,  # collide only with ground
                restitution=0.3))
        p.ttl = ttl
        self.particles.append(p)
        self._clean_particles(False)
        return p

    def _clean_particles(self, all):
        while self.particles and (all or self.particles[0].ttl < 0):
            self.world.DestroyBody(self.particles.pop(0))

    def step(self, action):
        assert self.action_space.contains(
            action), "%r (%s) invalid " % (action, type(action))

        # Engines
        tip = (math.sin(self.lander.angle), math.cos(self.lander.angle))
        side = (-tip[1], tip[0])
        dispersion = [
            self.np_random.uniform(-1.0, +1.0) / SCALE for _ in range(2)
        ]

        m_power = 0.0
        if (self.continuous and action[0] > 0.0) or (not self.continuous
                                                     and action == 2):
            # Main engine
            if self.continuous:
                m_power = (np.clip(action[0], 0.0, 1.0) +
                           1.0) * 0.5  # 0.5..1.0
                assert m_power >= 0.5 and m_power <= 1.0
            else:
                m_power = 1.0
            ox = tip[0] * (
                4 / SCALE + 2 * dispersion[0]) + side[0] * dispersion[
                    1]  # 4 is move a bit downwards, +-2 for randomness
            oy = -tip[1] * (4 / SCALE +
                            2 * dispersion[0]) - side[1] * dispersion[1]
            impulse_pos = (self.lander.position[0] + ox,
                           self.lander.position[1] + oy)
            p = self._create_particle(
                0.7, impulse_pos[0], impulse_pos[1], m_power
            )  # particles are just a decoration, 3.5 is here to make particle speed adequate
            p.ApplyLinearImpulse((ox * ROCKET['main_engine_power'] * m_power,
                                  oy * ROCKET['main_engine_power'] * m_power),
                                 impulse_pos, True)
            self.lander.ApplyLinearImpulse(
                (-ox * ROCKET['main_engine_power'] * m_power,
                 -oy * ROCKET['main_engine_power'] * m_power), impulse_pos,
                True)

        s_power = 0.0
        if (self.continuous
                and np.abs(action[1]) > 0.5) or (not self.continuous
                                                 and action in [1, 3]):
            # Orientation engines
            if self.continuous:
                direction = np.sign(action[1])
                s_power = np.clip(np.abs(action[1]), 0.5, 1.0)
                assert s_power >= 0.5 and s_power <= 1.0
            else:
                direction = action - 2
                s_power = 1.0
            ox = tip[0] * dispersion[0] + side[0] * (
                3 * dispersion[1] +
                direction * ROCKET['side_engine_away'] / SCALE)
            oy = -tip[1] * dispersion[0] - side[1] * (
                3 * dispersion[1] +
                direction * ROCKET['side_engine_away'] / SCALE)
            impulse_pos = (self.lander.position[0] + ox - tip[0] * 17 / SCALE,
                           self.lander.position[1] + oy +
                           tip[1] * ROCKET['side_engine_height'] / SCALE)
            p = self._create_particle(0.14, impulse_pos[0], impulse_pos[1],
                                      s_power)
            p.ApplyLinearImpulse((ox * ROCKET['side_engine_power'] * s_power,
                                  oy * ROCKET['side_engine_power'] * s_power),
                                 impulse_pos, True)
            self.lander.ApplyLinearImpulse(
                (-ox * ROCKET['side_engine_power'] * s_power,
                 -oy * ROCKET['side_engine_power'] * s_power), impulse_pos,
                True)

        self.world.Step(1.0 / FPS, 6 * 30, 2 * 30)

        pos = self.lander.position
        vel = self.lander.linearVelocity
        state = [
            (pos.x - W / 2) / (W / 2),
            (pos.y - (self.origin[1] + ROCKET['leg_down'] / SCALE)) / (W / 2),
            vel.x * (W / 2) / FPS, vel.y * (H / 2) / FPS,
            3 * self.lander.angle, 100.0 * self.lander.angularVelocity / FPS,
            1.0 if self.legs[0].ground_contact else 0.0,
            1.0 if self.legs[1].ground_contact else 0.0
        ]
        assert len(state) == 8

        reward = 0
        shaping = \
         - 10*np.sqrt(state[0]*state[0] + state[1]*state[1]) \
         - 10*np.sqrt(state[2]*state[2] + state[3]*state[3]) \
         - 30*abs(state[4]) + 1*state[6] + 1*state[7]   # And one point for legs contact, the idea is if you
        # lose contact again after landing, you get negative reward
        if self.prev_shaping is not None:
            reward = shaping - self.prev_shaping
        self.prev_shaping = shaping

        reward -= m_power * 0.3  # less fuel spent is better, about -30 for heuristic landing
        reward -= s_power * 0.03

        done = False
        success = False
        if self.game_over or abs(state[0]) >= 1.5 or state[1] <= -0.05:
            done = True
            reward = -100
        if not self.lander.awake:
            done = True
            reward = +500
            success = True

        self.steps += 1

        info = {
            'attempt_over': done,
            'attempt_succesful': success,
            'attempt_duration': self.steps
        }

        if done:
            state = self.reset()
            self.steps = 0

        return np.array(state), reward, done, info

    def render(self, mode='human'):
        from gym.envs.classic_control import rendering

        if self.viewer is None:
            self.viewer = rendering.Viewer(VIEWPORT_W, VIEWPORT_H)
            self.viewer.set_bounds(0, W, 0, H)

            def key_press(key, mod):
                if key == 0xff1b:  # Escape
                    self.close()  # close window
                    sys.exit()

            self.unwrapped.viewer.window.on_key_press = key_press

        # environment
        self.env_polys = []
        self.env_colors = []
        self.env_polys.append([(x * W, y * H) for x, y in ENV['sky_vertices']])
        self.env_colors.append(ENV['sky_color'])

        water_x, water_y = self.water.step()

        scale = 0.02
        water_poly = [(W, 0), (0, 0)] + list(
            zip(W * water_x, H *
                (ENV['water_level'] + scale * water_y))) + [(W, 0)]
        self.env_polys.append(water_poly)
        self.env_colors.append(ENV['water_color'])

        for i, p in enumerate(self.env_polys):
            self.viewer.draw_polygon(p, color=self.env_colors[i])

        # particles and lander
        for obj in self.particles:
            obj.ttl -= 0.15
            obj.color1 = (max(0.2, 0.2 + obj.ttl), max(0.2, 0.5 * obj.ttl),
                          max(0.2, 0.5 * obj.ttl))
            obj.color2 = (max(0.2, 0.2 + obj.ttl), max(0.2, 0.5 * obj.ttl),
                          max(0.2, 0.5 * obj.ttl))

        self._clean_particles(False)

        for obj in self.particles + self.drawlist:
            for f in obj.fixtures:
                trans = f.body.transform
                if type(f.shape) is circleShape:
                    t = rendering.Transform(translation=trans * f.shape.pos)
                    self.viewer.draw_circle(f.shape.radius,
                                            20,
                                            color=obj.color1).add_attr(t)
                    self.viewer.draw_circle(f.shape.radius,
                                            20,
                                            color=obj.color2,
                                            filled=False,
                                            linewidth=1).add_attr(t)
                else:
                    path = [trans * v for v in f.shape.vertices]
                    self.viewer.draw_polygon(path, color=obj.color1)
                    path.append(path[0])
                    self.viewer.draw_polyline(path,
                                              color=obj.color2,
                                              linewidth=1)

        return self.viewer.render(return_rgb_array=mode == 'rgb_array')

    def close(self):
        if self.viewer is not None:
            self.viewer.close()
            self.viewer = None

    def update_initials(self):
        if not self.initial_generator:
            return

        difficulties = self.initial_generator(self.difficulty)

        self.initial_pos_x = (difficulties['pos_x'] + 1) * W / 2
        self.initial_pos_y = self.origin[1] + difficulties['pos_y'] * (
            H - self.origin[1])
        self.initial_vel = difficulties['vel']
        self.initial_dir = difficulties['dir']
        self.initial_vdir = difficulties['vdir']

        self.ship_width = difficulties['ship_width']
Exemplo n.º 28
0
class Graphics:
	wireframe = False
	vertices = []
	reDraw = False
	toggleDrawAxes = False
	spectator = False
	numberOfVertices = 0

	def __init__(self, main):
		from font import Font

		global g_fVBOObjects
		g_fVBOObjects = []

		self.main = main
		self.g_nFrames = 0
		self.fps = 0

		init_opengl(main)

		self.font = Font()

	def addSurface(self, Mesh, Obj, Texture):
		g_pMesh = CMesh()
		vertices, vnormals, f, self.vertexCount = \
				loadObj(Obj)

		g_pMesh.textureId, textureWidthRatio, textureHeightRatio = \
				loadTexture(Texture)

		xMax = xMin = vertices[0][0]
		zMax = zMin = vertices[0][2]
		for i in vertices:
			if i[0] < xMin: xMin = i[0]
			elif i[0] > xMax: xMax = i[0]

			if i[2] < zMin: zMin = i[2]
			elif i[2] > zMax: zMax = i[2]

		sizeX = xMax - xMin
		sizeY = zMax - zMin

		texCoords = Numeric.zeros ((self.vertexCount, 2), 'f')

		nIndex = 0
		for i in vertices:
			self.vertices.append( CVector3(i[0], i[1], i[2]) )
			self.numberOfVertices += 1
			texCoords[nIndex, 0] = (i[0]-xMin) / sizeX * textureWidthRatio
			texCoords[nIndex, 1] = (i[2]-zMin) / sizeY * textureHeightRatio
			nIndex += 1

		self.verticesId, self.vnormalsId, self.texCoordsId = \
				createVBO(Obj, vertices, vnormals, texCoords)

		g_pMesh.verticesId = self.verticesId
		g_pMesh.vnormalsId = self.vnormalsId
		g_pMesh.texCoordsId = self.texCoordsId
		g_pMesh.vertexCount = self.vertexCount

		g_fVBOObjects.append(g_pMesh)

	def loadStaticObject(self, x, y, z, model, texture):
		g_pMesh = CMesh()
		vertices, vnormals, f, vertexCount = \
				loadObj(model)

		for v in vertices: # transform
			v[0] += x
			v[1] += y
			v[2] += z

		g_pMesh.textureId, textureWidthRatio, textureHeightRatio = \
				loadTexture(texture)

		xMax = xMin = vertices[0][0]
		zMax = zMin = vertices[0][2]
		for i in vertices:
			if i[0] < xMin: xMin = i[0]
			elif i[0] > xMax: xMax = i[0]

			if i[2] < zMin: zMin = i[2]
			elif i[2] > zMax: zMax = i[2]

		sizeX = xMax - xMin
		sizeY = zMax - zMin

		texCoords = Numeric.zeros ((vertexCount, 2), 'f')

		nIndex = 0
		for i in vertices:
			self.vertices.append( CVector3(i[0], i[1], i[2]) )
			self.numberOfVertices += 1
			texCoords[nIndex, 0] = (i[0]-xMin) / sizeX * textureWidthRatio
			texCoords[nIndex, 1] = (i[2]-zMin) / sizeY * textureHeightRatio
			nIndex += 1

		verticesId, vnormalsId, texCoordsId = \
				createVBO(model, vertices, vnormals, texCoords)

		g_pMesh.verticesId = verticesId
		g_pMesh.vnormalsId = vnormalsId
		g_pMesh.texCoordsId = texCoordsId
		g_pMesh.vertexCount = vertexCount

		g_fVBOObjects.append(g_pMesh)

	def initGL(self):
		from skydome import Skydome

		if not glInitVertexBufferObjectARB():
			sys.stderr.write("ERROR: Vertex buffer objects is not supported\n")
			#Global.quit = 1
			return

		glClearColor( 0.0, 0.0, 0.0, 0.0)
		glClearDepth(1.0)
		glDepthFunc(GL_LEQUAL)
		glEnable(GL_DEPTH_TEST)
		glShadeModel(GL_SMOOTH)
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
		glViewport(0, 0, self.main.config.getint('Resolution', 'Width'),
				self.main.config.getint('Resolution', 'Height'))
		glMatrixMode(GL_PROJECTION)

		#glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0)

		glLoadIdentity()
		gluPerspective(60.0, self.main.config.getfloat('Resolution','Width')
				/ self.main.config.getfloat('Resolution', 'Height'), 0.1, 5000.0)
		glMatrixMode(GL_MODELVIEW)

		#Lighting
		diffuseMaterial = (0.5, 0.5, 0.0, 1.0)
		mat_specular = (1.0, 1.0, 1.0, 1.0)
		light_position = (150.0, 0.0, 75.0, 1.0)

		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, diffuseMaterial)
		glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseMaterial)
		glLightfv(GL_LIGHT1, GL_POSITION, light_position)

		glEnable(GL_LIGHTING)
		glDisable(GL_LIGHT0)
		glEnable(GL_LIGHT1)
		###########

		glEnable(GL_NORMALIZE)

		self.skydome = Skydome()

		if not self.main.args['disableWater']:
			self.water = Water()

	def printFPS(self):
		self.fps = self.g_nFrames
		pygame.display.set_caption("FarornasGrotta - %d FPS" % (self.fps))
		self.g_nFrames = 0

	def drawAxes(self):
		""" Draws x, y and z axes """
		light = glIsEnabled(GL_LIGHTING)
		if light:
			glDisable(GL_LIGHTING)

		glColor3f(1.0, 0.0, 0.0)
		glBegin(GL_LINES)
		glVertex3f(-1000.0, 0.0, 0.0)
		glVertex3f( 1000.0, 0.0, 0.0)
		glEnd()

		glColor3f(0.0, 1.0, 0.0)
		glBegin(GL_LINES)
		glVertex3f(0.0, -1000.0, 0.0)
		glVertex3f(0.0,  1000.0, 0.0)
		glEnd()

		glColor3f(0.0, 0.0, 1.0)
		glBegin(GL_LINES)
		glVertex3f(0.0, 0.0, -1000.0)
		glVertex3f(0.0, 0.0, 1000.0)
		glEnd()

		if light:
			glEnable(GL_LIGHTING)

	def drawPlayerList(self):
		glPushMatrix()

		glDisable(GL_LIGHTING)

		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

		glLoadIdentity()
		glTranslated(-320.0, -240.0, -410.0)

		glColor3f(1.0, 1.0, 1.0)

		row = 3

		self.font.glPrint(80.0, 480 - 30.0 * row, "Name")
		self.font.glPrint(420.0, 480 - 30.0 * row, "Frags")
		self.font.glPrint(500.0, 480 - 30.0 * row, "Deaths")
		row += 1

		i = 0
		for obj in self.main.physics.objects:
			if obj.data.type != "player1":
				continue

			if obj.data.id == self.main.player.data.id:
				glColor3f(0.0, 1.0, 0.0)
			else:
				glColor3f(1.0, 1.0, 1.0)

			self.font.glPrint(80.0, 480.0 - 30.0*row, "%s" % obj.data.name)
			self.font.glPrint(420.0, 480.0 - 30.0*row, "%5d" % obj.data.frags)
			self.font.glPrint(500.0, 480.0 - 30.0*row, "%6d" % obj.data.deaths)

			i += 1
			row += 1


		glEnable(GL_LIGHTING)

		glPopMatrix()

	def drawFPS(self):
		glPushMatrix()
		glDisable(GL_LIGHTING)
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
		glLoadIdentity()
		glTranslated(-320.0, -240.0, -410.0)

		glColor3f(1.0, 1.0, 1.0)

		self.font.glPrint(540.0, 440.0, "FPS: %d" % (self.fps))

		glEnable(GL_LIGHTING)
		glPopMatrix()

	def draw(self, objects):
		global g_fVBOObjects

		#if self.reDraw:
			#self.main.octree.g_EndNodeCount = 0
			#self.main.octree.debug.Clear()
			#self.main.octree.DestroyOctree()
			#self.main.octree.GetSceneDimensions(self.vertices, self.numberOfVertices)
			#self.main.octree.CreateNode(self.vertices, self.numberOfVertices,
			#		self.main.octree.GetCenter(), self.main.octree.GetWidth())
			#self.reDraw = False


		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )
		glLoadIdentity()

		if self.toggleDrawAxes:
			self.drawAxes()

		glClearColor(0.4, 0.4, 0.4, 0.0)

		if self.wireframe:
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
		else:
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)


		glLoadIdentity()

		glRotatef(self.main.input.xrot, 1.0, 0.0, 0.0)
		glRotatef(self.main.input.yrot, 0.0, 1.0, 0.0)

		# SkyDome
		self.skydome.draw()

		if self.spectator:
			glTranslated(-self.main.input.xpos,
					-self.main.input.ypos,
					-self.main.input.zpos)
		else:
			glTranslated(
					-self.main.player.data.position[0]-0.2*math.sin(
						math.radians(self.main.player.data.orientation[1])
						),
					-self.main.player.data.position[1]-2.2,
					-self.main.player.data.position[2]+0.2*math.cos(
						math.radians(self.main.player.data.orientation[1]-180)
						)
					)

		self.g_nFrames += 1

		if self.toggleDrawAxes:
			self.drawAxes()

		# Water
		if not self.main.args['disableWater']:
			self.water.draw()

		glColor3f(1.0, 1.0, 1.0)

		#glClearColor(0.0, 0.0, 0.6, 0.5)
		glFogi(GL_FOG_MODE, GL_LINEAR)
		glFogfv(GL_FOG_COLOR, (0.4, 0.4, 0.4, 0.0))
		glFogf(GL_FOG_DENSITY, 0.1)
		glHint(GL_FOG_HINT, GL_DONT_CARE)
		glFogf(GL_FOG_START, 1.0)
		glFogf(GL_FOG_END, 110.0)
		#glEnable(GL_FOG)

		glEnableClientState(GL_VERTEX_ARRAY)
		glEnableClientState(GL_TEXTURE_COORD_ARRAY)
		glEnableClientState(GL_NORMAL_ARRAY)


		glPushMatrix()
		glColor3f(1.0, 1.0, 1.0)
		#glScalef(10.0, 10.0, 10.0)

		for VBOobject in g_fVBOObjects:
			#glEnable(GL_BLEND)
			#glBlendFunc(GL_ONE, GL_ONE)
			glBindTexture(GL_TEXTURE_2D, VBOobject.textureId)
			glEnable(GL_TEXTURE_2D)


			drawVBO(VBOobject.verticesId, VBOobject.vnormalsId,
					VBOobject.vertexCount, VBOobject.texCoordsId)

			glDisable(GL_TEXTURE_2D)
			#glDisable(GL_BLEND)

		glPopMatrix()


		glDisableClientState(GL_VERTEX_ARRAY)
		glDisableClientState(GL_TEXTURE_COORD_ARRAY)
		glDisableClientState(GL_NORMAL_ARRAY)

		glDisable(GL_FOG)

		if self.main.physics.octree.debugLines:
			# Turn OFF lighting so the debug lines are bright yellow
			glDisable(GL_LIGHTING)

			# Start rendering lines
			glBegin(GL_LINES)

			# Turn the lines yellow
			glColor3ub(255, 255, 0)

			self.main.physics.octree.debug.debugLines = []
			for obj in objects:
				self.main.physics.octree.debug.addDebugRectangle(
						obj.data.position, obj.data.width,
						obj.data.height, obj.data.depth)

			# Go through the whole list of lines stored in the vector debugLines
			for line in self.main.physics.octree.debug.debugLines:
				# Pass in the current point to be rendered as part of a line
				glVertex3f(line[0], line[1], line[2])

			# Stop rendering lines
			glEnd()

			# If we have lighting turned on, turn the lights back on
			glEnable(GL_LIGHTING)


		for obj in objects:
			obj.draw()

		if self.main.input.keys["KEY_TAB"] == 1:
			self.drawPlayerList()

		self.drawFPS()

		glFlush()

		pygame.display.flip()

		err = glGetError()
		if err:
			print "OpenGL Error:",err,"(",gluErrorString(err),")"
Exemplo n.º 29
0
    def initialize_forest(self):
        """Adds initial organisms to the map."""

        directions = list(Direction)
        # Water map
        for pool_size in WATER_POOLS:
            rand_x = random.randint(0, self.width - 1)
            rand_y = random.randint(0, self.height - 1)
            while self.water_map[rand_x][rand_y]:
                rand_x = random.randint(0, self.width - 1)
                rand_y = random.randint(0, self.height - 1)
            water_pools_added = 0
            positions = [(rand_x, rand_y)]
            WATER_POOLS_POSITIONS.append((rand_x, rand_y))
            while water_pools_added < pool_size and positions:
                # Breadth first add water pools around
                x, y = positions.pop(0)
                if not self.water_map[x][y]:
                    water = Water(self, x, y)
                    self.water_map[x][y] = water
                    water_pools_added += 1
                    # Insert all neighbors
                    random.shuffle(
                        directions)  # shuffle for a bit random shapes
                    for dir in directions:
                        new_x = x + dir.value[0]
                        new_y = y + dir.value[1]
                        # Check if out of bounds
                        if new_x < 0 or new_x >= self.width or new_y < 0 or new_y >= self.height:
                            continue
                        if self.water_map[new_x][new_y]:
                            continue
                        positions.append((new_x, new_y))

        # Plant map
        for x in range(self.width):
            for y in range(self.height):
                # check if water
                if self.water_map[x][y]:
                    continue
                if random.random() <= TREE_PERCENTAGE:
                    tree = Tree(self, x, y)
                    self.plant_map[x][y] = tree
                    if random.random() <= HIVES_PER_TREE:
                        hive = Hive(self, x, y)
                        self.animal_map[x][y].append(hive)
                        bee_amount = random.randint(HIVE_BEE_MIN_AMOUNT,
                                                    HIVE_BEE_MAX_AMOUNT)
                        bee = Bee(self,
                                  x,
                                  y,
                                  hive=hive,
                                  scout=True,
                                  age=random.randint(0, 24 * 150))
                        hive.bees.append(bee)
                        self.animal_map[x][y].append(bee)
                        for _ in range(bee_amount):
                            bee = Bee(self,
                                      x,
                                      y,
                                      hive=hive,
                                      scout=False,
                                      age=random.randint(0, 24 * 150))
                            self.animal_map[x][y].append(bee)
                            hive.bees.append(bee)
                elif random.random() <= GRASS_INIT_PERCENTAGE:
                    grass = Grass(self, x, y, random.randint(-80, 100), None,
                                  self.get_initial_water_level(x, y))
                    self.plant_map[x][y] = grass
                else:
                    earth = Earth(self, x, y,
                                  self.get_initial_water_level(x, y))
                    self.plant_map[x][y] = earth

        # Flower map
        from organisms import Type
        for x in range(self.width):
            for y in range(self.height):
                if self.water_map[x][y]:
                    continue
                if random.random() <= FLOWER_PERCENTAGE:
                    if self.plant_map[x][y] and self.plant_map[x][
                            y].type == Type.TREE:
                        continue
                    for _ in range(random.randint(1, 4)):
                        flower = Flower(self,
                                        x,
                                        y,
                                        random.randint(-50, 100),
                                        nectar=random.randint(0, 100),
                                        has_seed=random.choice([True, False]))
                        self.flower_map[x][y].append(flower)

        # Animal map
        import numpy as np
        # Rabbits
        for _ in range(BURROW_AMOUNT):
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            while self.water_map[x][y]:
                x = random.randint(0, self.width - 1)
                y = random.randint(0, self.height - 1)
            burrow = Burrow(self, x, y)
            self.animal_map[x][y].append(burrow)
            rabbit_amount = random.randint(BURROW_RABBIT_MIN_AMOUNT,
                                           BURROW_RABBIT_MAX_AMOUNT)
            for _ in range(rabbit_amount):
                dx = random.randint(-3, 3)
                dy = random.randint(-3, 3)

                if x + dx < 0 or x + dx >= self.width or y + dy < 0 or y + dy >= self.height:
                    continue

                if self.water_map[x + dx][y + dy]:
                    continue

                rabbit = Rabbit(self,
                                x + dx,
                                y + dy,
                                random.choice([True, False]),
                                adult=True,
                                burrow=burrow,
                                age=random.randint(24 * 30, 24 * 30 * 3),
                                reproduction_timer=random.randint(0, 24 * 6),
                                genetics_factor=np.random.normal(1, 0.1))
                self.animal_map[x + dx][y + dy].append(rabbit)

        # Foxes
        for _ in range(FOX_AMOUNT):
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            while self.water_map[x][y]:
                x = random.randint(0, self.width - 1)
                y = random.randint(0, self.height - 1)
            fox = Fox(self,
                      x,
                      y,
                      random.choice([True, False]),
                      adult=True,
                      age=random.randint(24 * 30 * 2, 24 * 30 * 6),
                      genetics_factor=np.random.normal(1, 0.1))
            self.animal_map[x][y].append(fox)