5f1e010c by Barry

Changes for pankration

1 parent 3c3cad9f
......@@ -157,6 +157,46 @@ def db_get_messages():
msg_conn.close()
return db_messages
def db_add_joke(joke):
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
conn.commit()
conn.close()
def db_get_fortune():
try:
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
# TODO: Move this shit to data
return c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
finally:
conn.close()
def db_get_joke():
try:
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
return c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
finally:
conn.close()
def db_add_fortune(fortune, date_added):
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
conn.commit()
conn.close()
def db_get_fortune():
try:
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
# TODO: Move this shit to data
return c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
finally:
conn.close()
def db_get_whoplayed(game_name):
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
......@@ -272,25 +312,32 @@ def db_add_soul_plate(member_id, soul_plate):
def db_remove_soul_plate(member_id, idx):
pan_record = db_get_pankration_record(member_id)
log("{}".format(member_id))
log("Removing Soul Plate: {}".format(member_id))
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
db_state = c.execute("SELECT soul_plates, member_id FROM pankration WHERE member_id = ?;", (member_id,)).fetchone()
if not db_state:
log("Invalid remove request for reflector: {}".format(idx,))
return False
else:
log(db_state)
else:
if db_state[0] and len(db_state[0]) > 0:
inv = str(db_state[0])
soul_plates = pickle.loads(inv)
try:
log("\nFirst: {}\n\n".format(db_state[0]))
inv = str(db_state[0])
soul_plates = pickle.loads(inv)
log("\n\nPlates: \n{}".format(soul_plates))
except Exception as e:
log("Failed! {}".format(e))
else:
log("Invalid remove request for reflector: {}".format(idx,))
return False
log("\n\nPlates: \n{}".format(soul_plates))
del soul_plates[idx]
c.execute("""UPDATE pankration SET soul_plates = ?
WHERE member_id = ?;""", (pickle.dumps(soul_plates), member_id))
conn.commit()
return True
def db_add_reflector(member_id, reflector):
pan_record = db_get_pankration_record(member_id)
......@@ -304,7 +351,7 @@ def db_add_reflector(member_id, reflector):
VALUES(?, ?, ?, ?);""", (member_id, 0, 0, pickle.dumps([reflector])))
conn.commit()
else:
log(db_state)
#log(db_state)
if db_state[0] and len(db_state[0]) > 0:
inv = str(db_state[0])
reflectors = pickle.loads(inv)
......@@ -314,6 +361,7 @@ def db_add_reflector(member_id, reflector):
c.execute("""UPDATE pankration SET reflectors = ?
WHERE member_id = ?;""", (pickle.dumps(reflectors), member_id))
conn.commit()
return True
def db_remove_reflector(member_id, idx):
pan_record = db_get_pankration_record(member_id)
......@@ -372,9 +420,39 @@ def db_register_battle(member_id, reflector, idx, target_member=None):
db_remove_reflector(member_id, idx)
return
def db_complete_battle(battle_id, primary_member_id, primary_reflector, secondary_member_id,
secondary_reflector):
pass
secondary_reflector, winner):
log('Completing battle')
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
c.execute("""UPDATE pankration_arena SET battle_status = 'finished', battle_end = ?
WHERE battle_id = ?;""", (datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), battle_id))
conn.commit()
log('Completing battle - finished')
# TODO: Settle any wagers
reflectors = pickle.loads(str(db_get_pankration_record(primary_member_id)['reflectors']))
reflectors.append(primary_reflector)
log('Completing battle - Primary')
if winner == 1:
c.execute("""UPDATE pankration SET reflectors = ?, wins = wins + 1
WHERE member_id = ?;""", (pickle.dumps(reflectors), primary_member_id))
else:
c.execute("""UPDATE pankration SET reflectors = ?, losses = losses + 1
WHERE member_id = ?;""", (pickle.dumps(reflectors), primary_member_id))
reflectors = pickle.loads(str(db_get_pankration_record(secondary_member_id)['reflectors']))
reflectors.append(secondary_reflector)
log('Completing battle - secondary')
if winner == 2:
c.execute("""UPDATE pankration SET reflectors = ?, wins = wins + 1
WHERE member_id = ?;""", (pickle.dumps(reflectors), secondary_member_id))
else:
c.execute("""UPDATE pankration SET reflectors = ?, losses = losses + 1
WHERE member_id = ?;""", (pickle.dumps(reflectors), secondary_member_id))
conn.commit()
conn.close()
log('Completing battle - done')
def db_start_battle(battle_id):
......@@ -393,7 +471,7 @@ def db_get_battle_queue():
results = []
for row in result:
results.append(dict_factory(c, row))
return results
......
No preview for this file type
......@@ -580,10 +580,8 @@ def do_buyticket(client, message_parts, message):
member = data.db_get_member(message.author.id)
log("Member: {}".format(member,))
if not member:
log("there")
send_message(client, message.author, "There was a problem looking up your information.")
else:
log("here")
log("Buying Ticket for: {}".format(byteify(member['member_name'])))
result, response = data.db_buy_ticket(member['member_id'], 1)
log("Buy Result: {} - {}".format(result, response))
......@@ -601,7 +599,11 @@ def do_balance(client, message_parts, message):
if not member:
send_message(client, message.author, "There was a problem looking up your information.")
else:
send_message(client, message.author, "Credits: {}\nTickets: {}".format(member['credits'], member['tickets']))
pankration_data = data.db_get_pankration_record(member['member_id'])
if pankration_data and 'wins' in pankration_data:
send_message(client, message.author, "Credits: {}\nTickets: {}\nPankration Wins: {}\nPankration Losses: {}".format(member['credits'], member['tickets'], pankration_data['wins'], pankration_data['losses']))
else:
send_message(client, message.author, "Credits: {}\nTickets: {}".format(member['credits'], member['tickets']))
return
......@@ -897,14 +899,12 @@ def do_msg(client, message_parts, message):
def do_addfortune(client, message_parts, message):
try:
fortune = message.content[9:]
fortune = message.content[11:]
if 'aa737a5846' in fortune:
send_message(client, message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
return
date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
c = conn.cursor()
c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
conn.commit()
data.db_add_fortune(fortune, date_added)
log("Added fortune")
except Exception as e:
log(e.message)
......@@ -917,9 +917,7 @@ def do_addfortune(client, message_parts, message):
def do_fortune(client, message_parts, message):
fortune = None
try:
c = conn.cursor()
# TODO: Move this shit to data
fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
fortune = data.db_get_fortune()
log(fortune)
except Exception as e:
log(e)
......@@ -963,13 +961,11 @@ def do_question(client, message_parts, message):
def do_addjoke(client, message_parts, message):
try:
joke = message.content[9:]
joke = message.content[8:]
if 'aa737a5846' in joke:
send_message(client, message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
return
c = conn.cursor()
c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
conn.commit()
data.db_add_joke(joke)
log("Added joke")
except Exception as e:
log(e.message)
......@@ -982,8 +978,7 @@ def do_addjoke(client, message_parts, message):
def do_joke(client, message_parts, message):
joke = None
try:
c = conn.cursor()
joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
joke = data.db_get_joke()
log(joke)
except Exception as e:
log(e)
......@@ -1129,9 +1124,12 @@ def do_list_soul_plates(client, message_parts, message):
member = data.db_get_member(message.author.id)
pankration_data = data.db_get_pankration_record(member['member_id'])
if pankration_data and pankration_data['soul_plates']:
if pankration_data and 'soul_plates' in pankration_data:
soul_plates = pickle.loads(str(pankration_data['soul_plates']))
send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(soul_plate.get_soul_plate_description())) for idx, soul_plate in enumerate(soul_plates)))
if len(soul_plates) > 0:
send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(soul_plate.get_soul_plate_description())) for idx, soul_plate in enumerate(soul_plates)))
else:
send_message(client, message.channel, 'You have no soul plates.')
else:
send_message(client, message.channel, 'You have no soul plates.')
......@@ -1142,7 +1140,10 @@ def do_list_reflectors(client, message_parts, message):
pankration_data = data.db_get_pankration_record(member['member_id'])
if pankration_data and pankration_data['reflectors']:
reflectors = pickle.loads(str(pankration_data['reflectors']))
send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(reflector)) for idx, reflector in enumerate(reflectors)))
if len(reflectors) > 0:
send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(reflector)) for idx, reflector in enumerate(reflectors)))
else:
send_message(client, message.channel, 'You have no reflectors.')
else:
send_message(client, message.channel, 'You have no reflectors.')
......@@ -1160,6 +1161,22 @@ def do_list_feral_skills(client, message_parts, message):
def do_hunt_monster(client, message_parts, message):
p = Pankration()
zone = ' '.join(message_parts)
cost = p.get_zone_cost(zone)
if cost == False:
send_message(client, message.channel, 'The zone was not found.')
return
else:
member = data.db_get_member(message.author.id)
if not member:
send_message(client, message.author, "There was a problem looking up your information.")
return
result, error_message = data.db_update_credit(member['member_id'], -cost)
if not result:
send_message(client, message.author, error_message)
return
send_message(client, message.channel, 'Soul Plate purchased for {} credits\n Hunting in {}'.format(cost, zone))
time.sleep(3)
hunt_response = p.hunt_monster(' '.join(message_parts))
str_out = hunt_response.message + "\n\n"
if hunt_response.result == HuntResponse.SUCCESS:
......@@ -1172,7 +1189,13 @@ def do_hunt_monster(client, message_parts, message):
def do_list_zones(client, message_parts, message):
p = Pankration()
send_message(client, message.channel, ', '.join(p.list_zones()))
zones = p.list_zones()
# out_str = ""
# for zone_name, zone in zones.iteritems():
# out_str += "{} - {}\n".format(zones[idx]['cost'], idx)
# send_message(client, message.channel, out_str)
out_str = 'Credit Cost - Zone Name\n--------------------------------\n' + '\n'.join(["{} - {}".format(zone['cost'], zone_name.title()) for zone_name, zone in zones.iteritems()])
send_message(client, message.channel, out_str)
return
......@@ -1214,6 +1237,7 @@ def check_arena():
battle_arena = p.start_battle(monster, monster2, "not used")
fighting = True
winner = 1
while fighting:
actions = battle_arena.step()
time.sleep(4)
......@@ -1224,15 +1248,34 @@ def check_arena():
if isinstance(action, AttackAction):
out_str += "{} {} {} for {}.\n".format(action.attacker.monster_type, action.message, action.target.monster_type, int(action.damage))
if isinstance(action, DefeatAction):
out_str += "\n\n**{}** {}. {} gains {} xp.\n\n".format(action.target.monster_type, action.message, action.attacker.monster_type, action.xp)
fighting = False
if action.attacker == monster:
result, xp_msg = monster.add_xp(action.xp)
if result:
out_str += xp_msg
winner = 1
monster.wins += 1
monster2.losses += 1
else:
result, xp_msg = monster2.add_xp(action.xp)
if result:
out_str += xp_msg
winner = 2
monster2.wins += 1
monster.losses += 1
break
out_str += "\n{} {}% - {} {}%\n".format(monster.monster_type, monster.get_hp_percent(), monster2.monster_type, monster2.get_hp_percent())
log(out_str)
send_message(client, arena_channel, byteify(out_str))
# Heal the monsters before they are returned to the player inventory
monster.hp = monster.get_hp()
monster2.hp = monster2.get_hp()
data.db_complete_battle(battle['battle_id'], battle['primary_member_id'], monster, battle['secondary_member_id'], monster2, winner)
#wait after each match before starting a new fight.
time.sleep(30)
except Exception as e:
log("{} - {}".format(format_exception(e), e.message))
finally:
......
......@@ -2,6 +2,14 @@ import random
import time
import pickle
import math
import collections
import logging
def log(message):
try:
logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
except:
pass
FIND_PERCENTAGE = 100
SKILL_PERCENT = 80
......@@ -218,21 +226,41 @@ Families = {
Monsters = {
'Mechanical Menace': {
'initial_level': 9,
'family': 'acrolith',
'zone': 'Abyssea - Uleguerand',
'zone': ['abyssea - uleguerand'],
'hp': 20,
'weapon_base_damage': 14
},
'Floating Eye': {
'initial_level': 10,
'family': 'ahriman',
'zone': 'Ranguemont Pass',
'zone': ['ranguemont pass'],
'hp': 15,
'weapon_base_damage': 15
},
'Bat Eye': {
'family': 'ahriman',
'zone': ['ranguemont pass', 'beaucedine glacier'],
'hp': 15,
'weapon_base_damage': 15
},
'Evil Eye': {
'family': 'ahriman',
'zone': ['castle zvahl baileys', 'castle zvahl keep', 'xarcabard'],
'hp': 15,
'weapon_base_damage': 15
}
}
UnsortedZones = {
'abyssea - uleguerand': {'cost': 10, 'find_percent': 50},
'beaucedine glacier': {'cost': 10, 'find_percent': 50},
'castle zvahl baileys': {'cost': 10, 'find_percent': 50},
'castle zvahl keep': {'cost': 10, 'find_percent': 50},
'ranguemont pass': {'cost': 10, 'find_percent': 50},
'xarcabard': {'cost': 10, 'find_percent': 50},
}
Zones = collections.OrderedDict(sorted(UnsortedZones.items()))
class Pankration:
def __init__(self):
......@@ -244,21 +272,27 @@ class Pankration:
return battle
def list_zones(self):
zone_list = []
for monster in Monsters.itervalues():
if monster['zone'] not in zone_list:
zone_list.append(monster['zone'])
return zone_list
return Zones
def get_monsters(self, zone):
monster_list = []
for monster_name, monster in Monsters.iteritems():
if monster['zone'] == zone:
if zone.lower() in monster['zone']:
monster_list.append(monster_name)
return monster_list
def get_zone_cost(self, zone):
zone = zone.lower()
if zone in Zones:
return Zones[zone]['cost']
else:
return False
def hunt_monster(self, zone):
if random.randint(1, 100) < FIND_PERCENTAGE:
zone = zone.lower()
if not zone in Zones:
return HuntResponse(HuntResponse.FAILURE, "The zone was not found. {} - {}".format(zone, Zones), None)
if random.randint(1, 100) < Zones[zone]['find_percent']:
monster_name = random.choice(self.get_monsters(zone))
monster_data = Monsters[monster_name]
hp = monster_data['hp']
......@@ -266,7 +300,7 @@ class Pankration:
print("Monster: {} Data: {}".format(monster_name, monster_data))
family_name = monster_data['family']
family = Families[family_name]
level = monster_data['initial_level']
level = 1
main_job = random.choice(family['available_main_job'])
support_job = random.choice(family['available_support_job'])
while support_job == main_job:
......@@ -356,13 +390,14 @@ class Monster:
def add_xp(self, exp_to_add):
self.exp += exp_to_add
for i in range(self.level, 51):
if self.exp > exp_to_level[i]:
if self.exp > 200 * i:
if i > self.level:
# We leveled up!
self.level = i
#print("Start level: {} New Level: {}".format(self.level, i))
return (True, "Start level: {} New Level: {}".format(self.level, i))
else:
break
return (False,)
def get_current_posture(self):
return TemperamentPosture[self.temperament_posture]
......@@ -652,8 +687,11 @@ if __name__ == "__main__":
print("{} {} {} for {}.".format(action.attacker.monster_type, action.message, action.target.monster_type, action.damage))
if isinstance(action, DefeatAction):
print("{} {}. {} gains {} xp.".format(action.target.monster_type, action.message, action.attacker.monster_type, action.xp))
action.attacker.hp = 500
print("{} {}".format(action.target.hp, action.attacker.hp))
fighting = False
break
print("\n\nhp: {} {}\n\n".format(monster.hp, monster2.hp))
print("\n{} {}% - {} {}%\n".format(monster.monster_type, monster.get_hp_percent(), monster2.monster_type, monster2.get_hp_percent()))
......