-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovince.py
448 lines (328 loc) · 15 KB
/
province.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
from flask import request, render_template, session, redirect
from helpers import login_required, error
import psycopg2
from app import app
from dotenv import load_dotenv
import os
import variables
from tasks import energy_info
from helpers import get_date
from upgrades import get_upgrades
from psycopg2.extras import RealDictCursor
import math
load_dotenv()
@app.route("/provinces", methods=["GET"])
@login_required
def provinces():
connection = psycopg2.connect(
database=os.getenv("PG_DATABASE"),
user=os.getenv("PG_USER"),
password=os.getenv("PG_PASSWORD"),
host=os.getenv("PG_HOST"),
port=os.getenv("PG_PORT"))
db = connection.cursor()
cId = session["user_id"]
db.execute("""SELECT cityCount, population, provinceName, id, land, happiness, productivity, energy
FROM provinces WHERE userId=(%s) ORDER BY id ASC""", (cId,))
provinces = db.fetchall()
connection.close()
return render_template("provinces.html", provinces=provinces)
@app.route("/province/<pId>", methods=["GET"])
@login_required
def province(pId):
connection = psycopg2.connect(
database=os.getenv("PG_DATABASE"),
user=os.getenv("PG_USER"),
password=os.getenv("PG_PASSWORD"),
host=os.getenv("PG_HOST"),
port=os.getenv("PG_PORT"),
cursor_factory=RealDictCursor)
db = connection.cursor()
cId = session["user_id"]
upgrades = get_upgrades(cId)
# Object under which the data about a province is stored
try:
db.execute("""SELECT id, userId AS user, provinceName AS name, population, pollution, happiness, productivity,
consumer_spending, cityCount, land, energy AS electricity FROM provinces WHERE id=(%s)""", (pId,))
province = dict(db.fetchone())
except:
return error(404, "Province doesn't exist")
db.execute("SELECT location FROM stats WHERE id=%s", (cId,))
province["location"] = dict(db.fetchone())["location"]
province["free_cityCount"] = province["citycount"] - get_free_slots(pId, "city")
province["free_land"] = province["land"] - get_free_slots(pId, "land")
province["own"] = province["user"] == cId
# Selects values for province buildings from the database and assigns them to vars
db.execute("""SELECT * FROM proInfra WHERE id=%s""", (pId,))
units = dict(db.fetchone())
def has_enough_cg(user_id):
db.execute("SELECT consumer_goods FROM resources WHERE id=%s", (user_id,))
consumer_goods = dict(db.fetchone())["consumer_goods"]
max_cg = math.ceil(province["population"] / variables.CONSUMER_GOODS_PER)
return consumer_goods >= max_cg
enough_consumer_goods = has_enough_cg(province["user"])
def has_enough_rations(user_id):
db.execute("SELECT rations FROM resources WHERE id=%s", (user_id,))
rations = dict(db.fetchone())["rations"]
rations_minus = province["population"] // variables.RATIONS_PER
return rations - rations_minus > 1
def has_enough_power(province_id):
db.execute("SELECT energy FROM provinces WHERE id=%s", (province_id,))
energy = (dict(db.fetchone()))["energy"]
return energy > 0
enough_rations = has_enough_rations(province["user"])
energy = {}
energy["consumption"], energy["production"] = energy_info(pId)
has_power = has_enough_power(pId)
infra = variables.INFRA
new_infra = variables.NEW_INFRA
prices = variables.PROVINCE_UNIT_PRICES
connection.close()
return render_template("province.html", province=province, units=units,
enough_consumer_goods=enough_consumer_goods, enough_rations=enough_rations, has_power=has_power,
energy=energy, infra=infra, upgrades=upgrades, prices=prices, new_infra=new_infra)
def get_province_price(user_id):
connection = psycopg2.connect(
database=os.getenv("PG_DATABASE"),
user=os.getenv("PG_USER"),
password=os.getenv("PG_PASSWORD"),
host=os.getenv("PG_HOST"),
port=os.getenv("PG_PORT"))
db = connection.cursor()
db.execute("SELECT COUNT(id) FROM provinces WHERE userId=(%s)", (user_id,))
current_province_amount = db.fetchone()[0]
multiplier = 1 + (0.16 * current_province_amount)
price = int(8000000 * multiplier)
return price
@app.route("/createprovince", methods=["GET", "POST"])
@login_required
def createprovince():
cId = session["user_id"]
connection = psycopg2.connect(
database=os.getenv("PG_DATABASE"),
user=os.getenv("PG_USER"),
password=os.getenv("PG_PASSWORD"),
host=os.getenv("PG_HOST"),
port=os.getenv("PG_PORT"))
db = connection.cursor()
if request.method == "POST":
pName = request.form.get("name")
db.execute("SELECT gold FROM stats WHERE id=(%s)", (cId,))
current_user_money = int(db.fetchone()[0])
province_price = get_province_price(cId)
if province_price > current_user_money:
return error(400, "You don't have enough money.")
db.execute("INSERT INTO provinces (userId, provinceName) VALUES (%s, %s) RETURNING id", (cId, pName))
province_id = db.fetchone()[0]
db.execute("INSERT INTO proInfra (id) VALUES (%s)", (province_id,))
new_user_money = current_user_money - province_price
db.execute("UPDATE stats SET gold=(%s) WHERE id=(%s)", (new_user_money, cId))
connection.commit()
connection.close()
return redirect("/provinces")
else:
price = get_province_price(cId)
return render_template("createprovince.html", price=price)
def get_free_slots(pId, slot_type): # pId = province id
connection = psycopg2.connect(
database=os.getenv("PG_DATABASE"),
user=os.getenv("PG_USER"),
password=os.getenv("PG_PASSWORD"),
host=os.getenv("PG_HOST"),
port=os.getenv("PG_PORT"))
db = connection.cursor()
if slot_type == "city":
db.execute(
"""
SELECT
coal_burners + oil_burners + hydro_dams + nuclear_reactors + solar_fields +
gas_stations + general_stores + farmers_markets + malls + banks +
city_parks + hospitals + libraries + universities + monorails
FROM proInfra WHERE id=%s
""", (pId,))
used_slots = int(db.fetchone()[0])
db.execute("SELECT cityCount FROM provinces WHERE id=%s", (pId,))
all_slots = int(db.fetchone()[0])
free_slots = all_slots - used_slots
elif slot_type == "land":
db.execute(
"""
SELECT
army_bases + harbours + aerodomes + admin_buildings + silos +
farms + pumpjacks + coal_mines + bauxite_mines +
copper_mines + uranium_mines + lead_mines + iron_mines +
lumber_mills + component_factories + steel_mills + ammunition_factories +
aluminium_refineries + oil_refineries FROM proInfra WHERE id=%s
""", (pId,))
used_slots = int(db.fetchone()[0])
db.execute("SELECT land FROM provinces WHERE id=%s", (pId,))
all_slots = int(db.fetchone()[0])
free_slots = all_slots - used_slots
return free_slots
@app.route("/<way>/<units>/<province_id>", methods=["POST"])
@login_required
def province_sell_buy(way, units, province_id):
cId = session["user_id"]
connection = psycopg2.connect(
database=os.getenv("PG_DATABASE"),
user=os.getenv("PG_USER"),
password=os.getenv("PG_PASSWORD"),
host=os.getenv("PG_HOST"),
port=os.getenv("PG_PORT"))
db = connection.cursor()
try:
db.execute("SELECT id FROM provinces WHERE id=%s AND userId=%s", (province_id, cId,))
ownProvince = db.fetchone()[0]
ownProvince = True
except TypeError:
ownProvince = False
if not ownProvince:
return error(400, "You don't own this province")
allUnits = [
"land", "cityCount",
"coal_burners", "oil_burners", "hydro_dams", "nuclear_reactors", "solar_fields",
"gas_stations", "general_stores", "farmers_markets", "malls", "banks",
"city_parks", "hospitals", "libraries", "universities", "monorails",
"army_bases", "harbours", "aerodomes", "admin_buildings", "silos",
"farms", "pumpjacks", "coal_mines", "bauxite_mines",
"copper_mines", "uranium_mines", "lead_mines", "iron_mines",
"lumber_mills",
"component_factories", "steel_mills", "ammunition_factories",
"aluminium_refineries", "oil_refineries"
]
city_units = [
"coal_burners", "oil_burners", "hydro_dams", "nuclear_reactors", "solar_fields",
"gas_stations", "general_stores", "farmers_markets", "malls", "banks",
"city_parks", "hospitals", "libraries", "universities", "monorails",
]
land_units = [
"army_bases", "harbours", "aerodomes", "admin_buildings", "silos",
"farms", "pumpjacks", "coal_mines", "bauxite_mines",
"copper_mines", "uranium_mines", "lead_mines", "iron_mines",
"lumber_mills", "component_factories", "steel_mills",
"ammunition_factories", "aluminium_refineries", "oil_refineries"
]
db.execute("SELECT gold FROM stats WHERE id=(%s)", (cId,))
gold = db.fetchone()[0]
try:
wantedUnits = int(request.form.get(units))
except:
return error(400, "You have to enter a unit amount")
if wantedUnits < 1:
return error(400, "Units cannot be less than 1")
def sum_cost_exp(starting_value, rate_of_growth, current_owned, num_purchased):
M = (starting_value * (1 - pow(rate_of_growth, (current_owned + num_purchased)))) / (1 - rate_of_growth)
N = (starting_value * (1 - pow(rate_of_growth, (current_owned)))) / (1 - rate_of_growth)
total_cost = M - N
return round(total_cost)
if units == "cityCount":
db.execute("SELECT cityCount FROM provinces WHERE id=(%s)", (province_id,))
current_cityCount = db.fetchone()[0]
cityCount_price = sum_cost_exp(750000, 1.09, current_cityCount, wantedUnits)
else:
cityCount_price = 0
if units == "land":
db.execute("SELECT land FROM provinces WHERE id=(%s)", (province_id,))
current_land = db.fetchone()[0]
land_price = sum_cost_exp(520000, 1.07, current_land, wantedUnits)
else:
land_price = 0
# All the unit prices in this format:
"""
unit_price: <the of the unit>,
unit_resource (optional): {resource_name: amount} (how many of what resources it takes to build)
unit_resource2 (optional): same as one, just for second resource
"""
# TODO: change the unit_resource and unit_resource2 into list based system
unit_prices = variables.PROVINCE_UNIT_PRICES
unit_prices["land_price"] = land_price
unit_prices["cityCount_price"] = cityCount_price
if units not in allUnits:
return error("No such unit exists.", 400)
table = "proInfra"
if units in ["land", "cityCount"]:
table = "provinces"
price = unit_prices[f"{units}_price"]
try:
db.execute("SELECT education FROM policies WHERE user_id=%s", (cId,))
policies = db.fetchone()[0]
except:
policies = []
if 2 in policies:
price *= 0.96
if 6 in policies and units == "universities":
price *= 0.93
if 1 in policies and units == "universities":
price *= 1.14
if units not in ["cityCount", "land"]:
totalPrice = wantedUnits * price
else:
totalPrice = price
print(totalPrice, wantedUnits, price)
try:
resources_data = unit_prices[f'{units}_resource'].items()
except KeyError:
resources_data = {}
curUnStat = f"SELECT {units} FROM {table} " + "WHERE id=%s"
db.execute(curUnStat, (province_id,))
currentUnits = db.fetchone()[0]
if units in city_units: slot_type = "city"
elif units in land_units: slot_type = "land"
else: # If unit is cityCount or land
free_slots = 0
slot_type = None
if slot_type is not None:
free_slots = get_free_slots(province_id, slot_type)
def resource_stuff(resources_data, way):
for resource, amount in resources_data:
if way == "buy":
current_resource_stat = f"SELECT {resource} FROM resources" + " WHERE id=%s"
db.execute(current_resource_stat, (cId,))
current_resource = int(db.fetchone()[0])
new_resource = current_resource - (amount * wantedUnits)
if new_resource < 0:
return {
"fail": True,
"resource": resource,
"current_amount": current_resource,
"difference": current_resource - (amount * wantedUnits)
}
resource_update_stat = f"UPDATE resources SET {resource}=" + "%s WHERE id=%s"
db.execute(resource_update_stat, (new_resource, cId,))
elif way == "sell":
current_resource_stat = f"SELECT {resource} FROM resources" + " WHERE id=%s"
db.execute(current_resource_stat, (cId,))
current_resource = db.fetchone()[0]
new_resource = current_resource + (amount * wantedUnits)
resource_update_stat = f"UPDATE resources SET {resource}=" + "%s WHERE id=%s"
db.execute(resource_update_stat, (new_resource, cId,))
if way == "sell":
if wantedUnits > currentUnits: # Checks if user has enough units to sell
return error("You don't have enough units.", 400)
unitUpd = f"UPDATE {table} SET {units}" + "=%s WHERE id=%s"
db.execute(unitUpd, ((currentUnits - wantedUnits), province_id))
new_money = gold + (wantedUnits * price)
db.execute("UPDATE stats SET gold=(%s) WHERE id=(%s)", (new_money, cId))
resource_stuff(resources_data, way)
elif way == "buy":
if totalPrice > gold: # Checks if user wants to buy more units than he has gold
return error("You don't have enough money.", 400)
print(totalPrice)
if free_slots < wantedUnits and units not in ["cityCount", "land"]:
return error(400, f"You don't have enough {slot_type} to buy {wantedUnits} units. Buy more {slot_type} to fix this problem")
res_error = resource_stuff(resources_data, way)
if res_error:
print(res_error)
return error(400, f"Not enough resources. Missing {res_error['difference']*-1} {res_error['resource']}.")
db.execute("UPDATE stats SET gold=gold-%s WHERE id=(%s)", (totalPrice, cId,))
updStat = f"UPDATE {table} SET {units}" + "=%s WHERE id=%s"
db.execute(updStat, ((currentUnits + wantedUnits), province_id))
if way == "buy": rev_type = "expense"
elif way == "sell": rev_type = "revenue"
name = f"{way.capitalize()}ing {wantedUnits} {units} in a province."
description = ""
db.execute("INSERT INTO revenue (user_id, type, name, description, date, resource, amount) VALUES (%s, %s, %s, %s, %s, %s, %s)",
(cId, rev_type, name, description, get_date(), units, wantedUnits,))
connection.commit()
connection.close()
return redirect(f"/province/{province_id}")