Skip to content

Commit 07120b4

Browse files
committed
Initial commit
0 parents  commit 07120b4

22 files changed

+1296
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# pySQL_API

classExample.py

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
#-*- coding: utf-8 -*-#
2+
from pyORM import orm
3+
import uuid, json
4+
import ast, itertools
5+
from functools import wraps
6+
7+
8+
9+
def updateAfterEvent(func):
10+
'''
11+
This decorator will detect the object-based table schema (PokemonClass, UserClass ...etc)
12+
and will update the database after each return of the function or method
13+
'''
14+
@wraps(func)
15+
def wrapper(*args, **kw):
16+
dbSession = orm(object_= args[0])
17+
try:
18+
res = func(*args, **kw)
19+
finally:
20+
pKey = [k for k,v in res.__dict__.items() if k[0]!="_" and v[2]["PRIMARY KEY"]][0]
21+
updates_ = {k:v[0] for k, v in res.__dict__.items() if k[0]!="_" and '_protected' != k[-10:]}
22+
dbSession.update({pKey: getattr(res, pKey)[0]}, **updates_)
23+
return res
24+
return wrapper
25+
26+
27+
28+
29+
class dummyPokemonClass(object):
30+
31+
__tablename__ = "dummy"
32+
__typesOrderArr__ = ['paper', 'scisor', 'rock', 'some different type that loses in front of all others']
33+
__typesOrder__ = {'paper': [2, 3], 'scisor': [0, 3], 'rock': [1, 3], 'some different type that loses in front of all others': []}
34+
35+
36+
def __init__(self, uuid_=None, name=None, typeArrayStr=None, hp=100):
37+
# It must be specified whether it is a primary key or not, the other elements can be ignored/undefined.
38+
# Order of the attributes must be same as args of __init__
39+
self.id = [uuid_ if uuid_ else str(uuid.uuid4()), "VARCHAR(255)", {"PRIMARY KEY": True, "AUTOINCREMENT": False, "NOT NULL": True, "FOREIGN KEY {} REFERENCES ...etc": False}]
40+
self.name = [name, "VARCHAR(255)", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True}]
41+
42+
deSerial_typeArray = ast.literal_eval(typeArrayStr)
43+
44+
if not [xType in self.__typesOrderArr__ for xType in deSerial_typeArray].count(False):
45+
self.type = [typeArrayStr, "TEXT", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": False}]
46+
else:
47+
raise "The type of pokemon doesn't exist"
48+
49+
self.hp = [hp, "INTEGER", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True,\
50+
"CHECK(hp BETWEEN 0 AND 100)": True}]
51+
52+
@updateAfterEvent
53+
def attack(self, enemyObj):
54+
deSerial_Self = ast.literal_eval(self.type[0])
55+
deSerial_enemyObj = ast.literal_eval(enemyObj.type[0])
56+
superAgainst = list(set(itertools.chain(*[self.__typesOrder__[t] for t in deSerial_Self])))
57+
if len([self.__typesOrderArr__[i] for i in superAgainst if self.__typesOrderArr__[i] in deSerial_enemyObj]):
58+
enemyObj.hp[0] = max(enemyObj.hp[0]-10, 0)
59+
return enemyObj
60+
61+
62+
63+
64+
65+
66+
67+
68+
69+
if __name__ == "__main__":
70+
71+
pika = dummyPokemonClass(name="Pikachu", typeArrayStr=json.dumps(['paper', 'some different type that loses in front of all others']), hp=90)
72+
crocodil = dummyPokemonClass(name="Crocordil", typeArrayStr=json.dumps(['rock']), hp=85)
73+
74+
75+
dbSession = orm(pika)
76+
dbSession.add()
77+
78+
dbSession = orm(crocodil)
79+
if not dbSession.add():
80+
print("{} Added successfully".format(crocodil.name[0]))
81+
82+
83+
84+
#Attack example
85+
print(pika.hp[0], crocodil.hp[0])
86+
crocodil = pika.attack(crocodil)
87+
print(pika.hp[0], crocodil.hp[0])
88+
89+
90+
'''
91+
Extract pokemons attributes and instantiate pokemon object
92+
'''
93+
dbSession = orm()
94+
pokSQL = dbSession.filterBy.get(tablename="dummy", name="Pikachu")[0]
95+
print(pokSQL)
96+
pika = dummyPokemonClass(*pokSQL)
97+
98+
pokSQL = dbSession.filterBy.get(tablename="dummy", name="Crocordil")[0]
99+
crocodil = dummyPokemonClass(*pokSQL)
100+
101+
102+
103+
print(pika.name[0], crocodil.name[0])
104+
105+
print(pika.hp[0], crocodil.hp[0])
106+
crocodil = pika.attack(crocodil)
107+
print(pika.hp[0], crocodil.hp[0])
108+

pokemonApp/api/__init__.py

Whitespace-only changes.

pokemonApp/api/pokAPI.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import requests, json
2+
3+
4+
class ApiClass:
5+
6+
def __init__(self, base_url="https://pokeapi.co/api/v2/"):
7+
self.base_url = base_url
8+
9+
def loadDB(self, limit):
10+
r = requests.get(self.base_url + "/pokemon/?limit={}".format(limit))
11+
respDict = json.loads(r.content)['results']
12+
return respDict
13+
14+
def get_move(self, move_name):
15+
req = requests.get(self.base_url + 'move/' + move_name + '/')
16+
m = req.json()
17+
i=0
18+
while 1:
19+
if move_json["names"][i]["language"]["name"]=="fr":
20+
break
21+
i+=1
22+
dict_move = {'name': move_json["names"][i]["name"], 'accuracy': m["accuracy"]}
23+
return dict_move
24+
25+
def get_pokemon(self, pok_name):
26+
req = requests.get(self.base_url + 'pokemon/' + pok_name + '/')
27+
m = req.json()
28+
list_types=[]
29+
for i in range(len(m["types"])):
30+
list_types.append(m["types"][i]["type"]["name"])
31+
list_moves = []
32+
for i in range(len(m["moves"])):
33+
list_moves.append(m["moves"][i]["move"]["name"])
34+
dict_pok = { 'name': m["name"], 'types': list_types, 'moves': list_moves}
35+
return dict_pok

pokemonApp/business_objects/__init__.py

Whitespace-only changes.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#-*- coding: utf-8 -*-#
2+
from orm.simpleDB import orm
3+
import uuid
4+
import ast, itertools
5+
from mytools.utils import updateAfterEvent
6+
7+
8+
9+
class pokemon(object):
10+
11+
__tablename__ = "pokemon"
12+
__typesOrderArr__ = ['rock', 'fighting', 'ground', 'dark', 'steel', 'electric', 'ghost', 'grass', 'flying', 'fire', 'water', 'fairy', 'dragon', 'normal', 'poison', 'ice', 'bug', 'psychic']
13+
__typesOrder__ = {'rock': [1], 'fighting': [2], 'ground': [3], 'dark': [4], 'steel': [5], 'electric': [6], 'ghost': [7], 'grass': [8], 'flying': [9], 'fire': [10], 'water': [11], 'fairy': [12], 'dragon': [13], 'normal': [14], 'poison': [15], 'ice': [16], 'bug': [17], 'psychic': []}
14+
15+
16+
def __init__(self, uuid_=None,state="Wild", name=None, typeArrayStr=None, movesArrStr=None, xp=None, zone=None, hp=100):
17+
# Seule la clé primaire est obligatoire, les autres éléments peuvent être ignorés et non définis
18+
self.id = [uuid_ if uuid_ else str(uuid.uuid4()), "VARCHAR(255)", {"PRIMARY KEY": True, "AUTOINCREMENT": False, "NOT NULL": True}]
19+
self.state=[state, "VARCHAR(255)", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True}]
20+
self.name = [name, "VARCHAR(255)", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True}]
21+
deSerial_typeArray = ast.literal_eval(typeArrayStr)
22+
23+
if not [xType in self.__typesOrderArr__ for xType in deSerial_typeArray].count(False):
24+
self.type = [typeArrayStr, "TEXT", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": False}]
25+
else:
26+
raise "The type of pokemon doesn't exist"
27+
self.moves = [movesArrStr, "TEXT", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True}]
28+
self.xp = [xp, "INTEGER", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True}]
29+
self.zone = [zone, "INTEGER", {"PRIMARY KEY": False, "NOT NULL": False, "CHECK((zone BETWEEN 1 AND 11) OR (zone IS NULL))": True}]
30+
self.hp = [hp, "INTEGER", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True,\
31+
"CHECK(hp BETWEEN 0 AND 100)": True}]
32+
33+
@updateAfterEvent
34+
def attack(self, enemyObj):
35+
deSerial_Self = ast.literal_eval(self.type[0])
36+
deSerial_enemyObj = ast.literal_eval(enemyObj.type[0])
37+
superAgainst = list(set(itertools.chain(*[self.__typesOrder__[t] for t in deSerial_Self])))
38+
if len([self.__typesOrderArr__[i] for i in superAgainst if self.__typesOrderArr__[i] in deSerial_enemyObj]):
39+
enemyObj.hp[0] = max(enemyObj.hp[0]-10, 0)
40+
elif self.xp and enemyObj.xp:
41+
if self.xp[0] > enemyObj.xp[0]:
42+
enemyObj.hp[0] = max(enemyObj.hp[0]-7, 0)
43+
else:
44+
enemyObj.hp[0] = max(enemyObj.hp[0]-5, 0)
45+
return enemyObj
46+
47+

pokemonApp/business_objects/user.py

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
#-*- coding: utf-8 -*-#
2+
from orm.simpleDB import orm
3+
import json
4+
import ast
5+
import hashlib, random
6+
from mytools.utils import *
7+
8+
9+
10+
11+
class utilisateur(object):
12+
"""
13+
La classe utilisateur définit les informations et les méthodes propres au joueur.
14+
Seule la clé primaire est obligatoire, les autres éléments peuvent être ignorés et non définis.
15+
"""
16+
17+
__tablename__ = "user"
18+
__const_prices__ = {'pokeball':10, 'Baies': 10}
19+
20+
def __init__(self, username, passwd, coin=100, zone=1, xp=0, pokeball=5, berry=2, pokCollectionStr='[]',pokedex='[]'):
21+
22+
"""
23+
Attributs
24+
25+
:param username: Pseudonyme du joueur
26+
:type username: str
27+
:param passwd : Mot de passe du joueur
28+
:type passwd: str
29+
:param coin : argent du joueur
30+
:type coin : int
31+
:param zone : zone dans laquelle se situe le joueur
32+
:type zone : int
33+
:param xp : expérience du joueur
34+
:type xp : int
35+
:param pokeball : nombre de pokeball du joueur
36+
:type pokeball : int
37+
:param berry : nombre de baies du joueur
38+
:type berry : int
39+
:param pokCollectionStr : liste des pokemons capturés par le joueur
40+
:type pokCollectionStr : list
41+
"""
42+
self.username = [username, "VARCHAR(255)", {"PRIMARY KEY": True, "AUTOINCREMENT": False, "NOT NULL": True}]
43+
self.hashed_pass_protected = [hashlib.sha1(passwd.encode('utf8')).hexdigest(), "VARCHAR(40)", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": True}]
44+
self.coin = [coin, "INTEGER", {"PRIMARY KEY": False, "NOT NULL": True,"CHECK(coin >= 0)": True}]
45+
self.zone = [zone, "INTEGER", {"PRIMARY KEY": False,"NOT NULL": True, "CHECK(zone BETWEEN 1 AND 11)": True}]
46+
self.xp = [xp, "INTEGER", {"PRIMARY KEY": False,"NOT NULL": True, "CHECK(xp BETWEEN 1 AND 2000)": True}]
47+
self.pokeball = [pokeball, "INTEGER", {"PRIMARY KEY": False,"NOT NULL": True, "CHECK(pokeball BETWEEN 0 AND 20)": True}]
48+
self.berry = [berry, "INTEGER", {"PRIMARY KEY": False,"NOT NULL": True, "CHECK(berry BETWEEN 0 AND 20)": True}]
49+
self.pokCollection = [pokCollectionStr, "TEXT", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": False}]
50+
self.pokedex=[pokedex, "TEXT", {"PRIMARY KEY": False, "AUTOINCREMENT": False, "NOT NULL": False}]
51+
52+
53+
54+
def setPokemon(self, pokemon_uuid):
55+
""" Méthode permettant de définir un identifiant unique universel (UUID) à chaque Pokemon.
56+
57+
:param pokemon_uuid: UUID du Pokemon
58+
:type pokemon_uuid : str
59+
"""
60+
deSerial_pokArray = ast.literal_eval(self.pokCollection[0])
61+
if pokemon_uuid in deSerial_pokArray:
62+
self._setPokemon = pokemon_uuid
63+
64+
65+
@staticmethod
66+
def retirer(pokObj):
67+
""" Méthode permettant de retirer de la base un Pokemon.
68+
69+
:param pokObj: objet Pokemon
70+
:type pokObj: str
71+
:return: table Pokemon filtrée du Pokemon retiré
72+
"""
73+
dbSession = orm()
74+
return dbSession.filterBy.delete(tablename="pokemon", id=pokObj.id[0])
75+
76+
77+
@updateAfterEvent
78+
def shop(self, num_pokebal=0, num_berry=0):
79+
""" Méthode permettant d'acheter des Pokeball et des baies
80+
81+
:param num_pokebal: nombre de pokeball
82+
:type num_pokebal: int
83+
:param num_berry: nombre de baies
84+
:type num_berry: int
85+
:return: informations du joueur
86+
"""
87+
cost_ = num_pokebal*self.__const_prices__['pokeball'] + num_berry*self.__const_prices__['Baies']
88+
if cost_ <= self.coin[0]:
89+
self.coin[0] -= cost_
90+
self.pokeball[0] += num_pokebal
91+
self.berry[0] += num_berry
92+
print('Achat effectué')
93+
else:
94+
print('Solde insuffisant')
95+
return self
96+
97+
98+
@updateAfterEvent
99+
def Capture(self, pokeObj):
100+
""" Méthode permettant de Capture de nouveaux Pokemon
101+
102+
:param pokeObj: objet Pokemon
103+
:type pokeObj: str
104+
:return: informations du joueur
105+
"""
106+
xp_diff = int((pokeObj.xp[0]-self.xp[0])/100)
107+
xp_diff = int(min((20-xp_diff)/20, 1) * 10)
108+
ifeelLucky = random.choice([False]*xp_diff+[True]*(10-xp_diff))
109+
ifeelLucky = True
110+
if self.pokeball[0]<=0:
111+
print("Vous n'avez plus de pokeballs")
112+
elif ifeelLucky:
113+
deSerial_pokArray = ast.literal_eval(self.pokCollection[0])
114+
deSerial_pokArray.append(pokeObj.id[0])
115+
self.pokCollection[0] = json.dumps(deSerial_pokArray)
116+
pokeObj.state[0] = 'Not Wild'
117+
self.pokeball[0] -= 1
118+
updateObj(pokeObj)
119+
print(pokeObj.name[0]+" est capturé")
120+
else:
121+
print(pokeObj.name[0]+"n'a pas été capturé")
122+
123+
return self
124+
125+
@updateAfterEvent
126+
def move(self, targetZone):
127+
""" Méthode permettant de naviguer dans les différentes zones du jeu
128+
129+
:param targetZone: zone dans laquelle le joueur souhaite aller
130+
:type targetZone: int
131+
:return: informations du joueur
132+
"""
133+
self.zone[0] = targetZone
134+
return self
135+
136+
137+
@updateAfterEvent
138+
def heal(self,pokeObj):
139+
""" Méthode permettant de soigner des Pokemons
140+
141+
:param pokeObj: objet Pokemon
142+
:type pokeObj: str
143+
:return: informations du joueur
144+
"""
145+
if self.berry[0]<=0:
146+
print("Vous n'avez plus de baies")
147+
else :
148+
pokeObj.hp[0] = 100
149+
self.berry[0] = max(1, self.berry[0]-1)
150+
print(pokeObj.name[0]+' est soigné')
151+
updateObj(pokeObj)
152+
return self

pokemonApp/combat/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)