game/population.py

72 lines
2.2 KiB
Python

# -*- coding: utf-8 -*-
#
# Copyright © 2024 Simon Forman
#
# This file is part of game
#
# game is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# game is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with game. If not see <http://www.gnu.org/licenses/>.
#
from random import sample
INITIAL_POP = 1000
INITIAL_NUMBER_OF_SENTIENT_PEOPLES = 12
def init_db(conn):
print('Generating population data.')
# Find the not-too-crappy planets.
c = conn.cursor()
c.execute(
'''\
select id, bio, industrial_capacity
from planets
where bio > 10000 and industrial_capacity > 10000
'''
)
# Note that bio is initialized to full capacity whereas industry is 0.
# Select some and set initial population and industry.
home_worlds = sample(list(c.fetchall()), INITIAL_NUMBER_OF_SENTIENT_PEOPLES)
for planet_id, bio, industrial_capacity in home_worlds:
bio -= INITIAL_POP # We know bio is above 10000 from the query above.
ind = min(INITIAL_POP, industrial_capacity)
people_name = get_name_of_planets_star(c, planet_id) + 'ians'
c.execute(
'update planets set bio = ?, industry = ? where id = ?',
(bio, ind, planet_id),
)
c.execute(
'insert into populations(species, pop, planet) values (?, ?, ?)',
(people_name, INITIAL_POP, planet_id),
)
print(planet_id, bio, industrial_capacity)
c.close()
conn.commit()
def get_name_of_planets_star(db_cursor, planet_id):
# My first ever JOIN statement! Squeeeee!
db_cursor.execute(
'''\
select stars.name from stars
join planets
on stars.id = planets.star
and planets.id = ?
''',
(planet_id,),
)
return db_cursor.fetchone()[0]