def registration(username, password): try: cursor = db.new_execute( "INSERT INTO {} (username, password) VALUES (%s, %s)".format( User.table_name), (username, password)) user_id = cursor.lastrowid db.new_execute( "INSERT INTO {} (user_id) VALUES (%s)".format( ECONOMY_TABLE_NAME), (user_id, )) return user_id except Exception as e: raise e return False
def load(self): data = tuple( db.new_execute( "SELECT * FROM {} WHERE planet_id = %s".format( PLANET_TABLE_NAME), (self.planet_id, )).fetchone().values()) self.planet_id, self.user_id, self.population, self.increase_rate, self.gdp, self.cpi, self.type, self.radius, self.cost = data
def __init__(self, planet_id=None, type=None): print("INIT", planet_id) if type: # create new planet planet_info = PLANET_TYPE[type] s_range = planet_info['size'] radius = round( random.uniform(s_range[0], s_range[1]) * EARTH_RADIUS) square = round(4 * math.pi * radius**2) population = round((square / EARTH_SQUARE) * EARTH_AC_POPULATION) cost = square * 1000 # 1000$ per km2 print(type, radius, square, population, cost) db.new_execute( "INSERT INTO {} (population,type, radius, cost) VALUES (%s,%s,%s, %s)" .format(Planet.table_name), (population, type, radius, cost)) else: self.planet_id = planet_id self.user_id = self.population = self.increase_rate = self.gdp = self.cpi = self.type = self.radius = self.cost = None self.load()
def login(username, password): # search in db result = db.new_execute( "SELECT user_id FROM {} WHERE username=%s and password=%s".format( User.table_name), (username, password)).fetchone() if result is not None: return User(result['user_id']) else: return None
def own(self, user_id): print(self.planet_id) db.new_execute( "UPDATE {} SET user_id = %s WHERE planet_id = %s".format( PLANET_TABLE_NAME), (user_id, self.planet_id))
def pick(): planet_id = db.new_execute( "SELECT planet_id FROM {} WHERE user_id is NULL ORDER BY RAND() LIMIT 1" .format(PLANET_TABLE_NAME)).fetchone()['planet_id'] print("Gift", planet_id) return Planet(planet_id=planet_id)
def tick(): update_time = datetime.datetime.utcnow() db.new_execute( "update {} as e inner join (select user_id, sum(gdp*population) as increase from {} group by user_id) as p on p.user_id = e.user_id set e.balance = e.balance + p.increase/86400*(TIME_TO_SEC(TIMEDIFF(%s,IFNULL(e.last_paid, %s)))), income = p.increase, last_paid=%s".format(ECONOMY_TABLE_NAME, PLANET_TABLE_NAME), (update_time, update_time, update_time) )
def reload(self): self.balance, self.income = tuple(db.new_execute( "SELECT balance, income FROM {} WHERE user_id = %s".format(ECONOMY_TABLE_NAME), (self.user_id) ).fetchone().values())