game/server.py

96 lines
2.8 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/>.
#
import data
def turn():
conn = data.open_db()
cursor = conn.cursor()
life_grows(cursor)
population_grows(cursor)
industry_produces()
vessels_move()
conn.commit()
data.close_db()
BIO_GROWTH = 0.03
POP_GROWTH = 0.0125
def life_grows(db_cursor):
print('life_grows')
db_cursor.execute('''
select id, bio, bio_capacity from planets
where bio > 0 and bio < bio_capacity
''')
planets = list(db_cursor.fetchall())
# Get all the results before updating some in this loop.
for planet_id, bio, bio_capacity in planets:
# We add at least one unit of population per turn.
new_bio = round(bio * BIO_GROWTH) or 1
available_capacity = bio_capacity - bio
if new_bio > available_capacity:
excess_bio = new_bio - available_capacity
new_bio = available_capacity
else:
excess_bio = 0
bio = bio + new_bio
assert bio <= bio_capacity
print(f'setting planet {planet_id} bio to {bio} increment of {new_bio}, excess_bio {excess_bio}')
db_cursor.execute('update planets set bio = ? where id = ?', (bio, planet_id))
def population_grows(db_cursor):
print('population_grows')
db_cursor.execute('''
select populations.id, populations.pop, planets.id, planets.bio
from populations join planets
on populations.planet = planets.id
''')
pops = list(db_cursor.fetchall())
for pop_id, pop, planet_id, bio in pops:
if pop > bio:
# famine and death! Woe!
pop = bio >> 1
bio //= 10
else:
bio -= pop # Everyone eats.
new_pop = round(pop * POP_GROWTH)
pop += new_pop
print(f'population {pop_id} of planet {planet_id} is now {pop}, bio is {bio}')
db_cursor.execute('update planets set bio = ? where id = ?', (bio, planet_id))
db_cursor.execute('update populations set pop = ? where id = ?', (pop, pop_id))
def industry_produces():
print('industry_produces')
def vessels_move():
print('vessels_move')
if __name__ == '__main__':
turn()