100 lines
2.4 KiB
Python
100 lines
2.4 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 randint, expovariate, seed
|
|
import sqlite3
|
|
from poisson import poisson
|
|
|
|
|
|
FILENAME = './game.sqlite'
|
|
MINIMUM_DISTANCE_BETWEEN_STARS = 160
|
|
WIDTH, HEIGHT = 10240, 7680
|
|
|
|
|
|
CREATE_TABLES = '''\
|
|
create table stars (x INTEGER, y INTEGER, radius INTEGER)
|
|
'''.splitlines(False)
|
|
|
|
conn = None
|
|
|
|
|
|
def initialize_db(filename):
|
|
conn = open_db(filename)
|
|
c = conn.cursor()
|
|
for statement in CREATE_TABLES:
|
|
c.execute(statement)
|
|
c.close()
|
|
conn.commit()
|
|
return conn
|
|
|
|
|
|
def close_db():
|
|
if conn:
|
|
conn.close()
|
|
conn = None
|
|
else:
|
|
raise RuntimeError('db connection already closed')
|
|
|
|
|
|
def open_db(filename=FILENAME):
|
|
global conn
|
|
if conn is not None:
|
|
raise RuntimeError('db connection already open')
|
|
conn = sqlite3.connect(filename)
|
|
return conn
|
|
|
|
|
|
def generate_stars(width, height, minimum_distance_between_stars):
|
|
for x, y in poisson(width, height, minimum_distance_between_stars):
|
|
yield x, y, round(1 + expovariate(1))
|
|
|
|
|
|
def main(filename):
|
|
print('Initializing db file', filename)
|
|
conn = initialize_db(filename)
|
|
|
|
print('Generating data.')
|
|
seed(23)
|
|
c = conn.cursor()
|
|
for values in generate_stars(
|
|
WIDTH,
|
|
HEIGHT,
|
|
MINIMUM_DISTANCE_BETWEEN_STARS,
|
|
):
|
|
c.execute('insert into stars values (?, ?, ?)', values)
|
|
c.close()
|
|
conn.commit()
|
|
|
|
|
|
def stars():
|
|
global conn
|
|
c = conn.cursor()
|
|
c.execute('select x, y, radius from stars')
|
|
yield from c.fetchall()
|
|
c.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
import pathlib
|
|
|
|
if not pathlib.Path(FILENAME).exists():
|
|
main(FILENAME)
|
|
else:
|
|
print(FILENAME, 'already exists! Not overwriting.')
|