def try_deplete_resources(user_id, food, water, aluminum, copper, silicon, oil):
    current = sql.query("SELECT * FROM `resource_status` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
    current = current[0]
    if current["food"] < food:
        return False
    if current["water"] < water:
        return False
    if current["aluminum"] < aluminum:
        return False
    if current["copper"] < copper:
        return False
    if current["oil"] < oil:
        return False

    sql.query(
        "UPDATE `resource_status` SET "
        + ", ".join(
            [
                "`food` = `food` - " + str(food),
                "`water` = `water` - " + str(water),
                "`aluminum` = `aluminum` - " + str(aluminum),
                "`copper` = `copper` - " + str(copper),
                "`silicon` = `silicon` - " + str(silicon),
                "`oil` = `oil` - " + str(oil),
            ]
        )
        + " WHERE `user_id` = "
        + str(user_id)
        + " LIMIT 1"
    )
    return True
Example #2
0
def get_user(raw_id_list):
    if raw_id_list != None:
        raw_ids = raw_id_list.split(',')
        user_lookup = {}
        ids = []
        for id in raw_ids:
            id = util.parseInt(id)
            if id > 0:
                ids.append(str(id))

        if len(ids) > 0:
            if len(ids) == 1:
                users_db = sql.query(
                    "SELECT `name`, `user_id` FROM `user` WHERE `user_id` = %s LIMIT 1",
                    (ids[0], ))
            else:
                users_db = sql.query(
                    "SELECT `name`, `user_id` FROM `user` WHERE `user_id` IN ("
                    + ', '.join(ids) + ")")
            output = []
            for user in users_db:
                name = user['name']
                id = user['user_id']
                output.append((id, name))
            return {'success': True, 'users': output}
    return {'success': False, 'message': "User ID list is blank"}
def dispatch(user_id):
    counts = get_count(user_id)

    sql.query(
        "UPDATE `bots` SET `type_a` = 0, `type_b` = 0, `type_c` = 0 WHERE `user_id` = "
        + str(user_id) + " LIMIT 1")

    return counts
def do_build(user_id, client_token, last_id, sector, loc, type, poll_afterwards=True):
    sector = util.tsanitize(sector)
    loc = util.tsanitize(loc)
    last_id = util.parseInt(last_id)

    verify_position = sql.query("SELECT `hq_sector` FROM `user` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
    if verify_position[0]["hq_sector"] == sector:

        if client_token:
            duplicate = sql.query("SELECT `client_token` FROM `event` WHERE `client_token` = %s", (client_token,))
            if not duplicate and validate_building(type, sector, loc):

                error = verify_placement(type, sector, loc)
                if error == None:

                    if type == "hq" or try_deplete_resources(
                        user_id,
                        settings.building_cost[type][0],
                        settings.building_cost[type][1],
                        settings.building_cost[type][2],
                        settings.building_cost[type][3],
                        settings.building_cost[type][4],
                        settings.building_cost[type][5],
                    ):

                        data = "Build:%s,%s" % (type, loc)
                        event_id = sql.insert(
                            "INSERT INTO `event` (`client_token`, `sector_xy`, `user_id`, `data`) VALUES (%s, %s, %s, %s)",
                            (client_token, sector, user_id, data),
                        )
                        quarry_data = ""
                        if type == "quarry":
                            resources = "a c s".split(" ")
                            distribution = [int(random.random() * 101)]
                            rdist = int(random.random() * (100 - distribution[0] + 1))
                            distribution.append(rdist)
                            distribution.append(100 - sum(distribution))
                            random.shuffle(distribution)

                            quarry_data = (
                                "a" + str(distribution[0]) + "c" + str(distribution[1]) + "s" + str(distribution[2])
                            )
                        sql.insert(
                            "INSERT INTO `structure` (`type`, `sector_xy`, `loc_xy`, `user_id`, `event_id`, `data`) VALUES (%s, %s, %s, %s, %s, %s)",
                            (type, sector, loc, user_id, event_id, quarry_data),
                        )
                    else:
                        return {"success": False, "message": "Insufficient resources"}
                else:
                    return {"success": False, "message": error}
            if poll_afterwards:
                return poll.do_poll(user_id, str(last_id) + "^" + sector)
        else:
            return {"success": False, "message": "missing client token"}
    else:
        return {"success": False, "message": "Cannot build this far from your HQ"}
def heavy_authenticate(user, password, register_if_new=False, is_new=False):
    failure_message = {
        'success': False,
        'message': "Invalid username/password."
    }
    login_id = util.alphanums(user)
    result = sql.query(
        "SELECT `user_id`, `password`, `hq_sector`, `hq_loc`, `research` FROM `user` WHERE `login_id`=%s LIMIT 1",
        (login_id, ))
    if len(result) == 0:
        if register_if_new:
            user_id = add_user(user, password)
            if user_id == 0:
                return {
                    'success':
                    False,
                    'message':
                    "Could not register account. Usernames must have at least 1 alphanumeric character"
                }
            return heavy_authenticate(user, password, False, True)
        return failure_message

    data = result[0]

    user_id = data['user_id']
    buildings_db = sql.query(
        "SELECT `type` FROM `research_unlocked` WHERE `user_id` = " +
        str(user_id))
    buildings = []
    for building in buildings_db:
        buildings.append(building['type'])

    bots_db = sql.query("SELECT * FROM `bots` WHERE `user_id` = " +
                        str(user_id) + " LIMIT 1")
    if len(bots_db) == 0:
        bots = [0, 0, 0]
    else:
        row = bots_db[0]
        bots = [row['type_a'], row['type_b'], row['type_c']]

    if data['password'] == password:
        return {
            'success': True,
            'user_id': data['user_id'],
            'hq': (data['hq_sector'], data['hq_loc']),
            'is_new': is_new,
            'research': data['research'],
            'buildings': buildings,
            'bots': bots
        }
    else:
        return failure_message
def apply_research(user_id, type):
	bytes_known = sql.query("SELECT `research` FROM `user` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	bytes_known = bytes_known[0]['research']
	cost = settings.building_research.get(type, None)
	if cost == None:
		return { 'success': False, 'message': "Invalid building type" }
	if bytes_known < cost:
		return { 'success': False, 'message': "Insufficient Data" }
	
	already = sql.query("SELECT `user_id` FROM `research_unlocked` WHERE `user_id` = " + str(user_id)  + " AND `type` = '" + str(type) + "' LIMIT 1")
	if len(already) == 0:
		sql.query("INSERT INTO `research_unlocked` (`user_id`, `type`) VALUES (" + str(user_id) + ", '" + str(type) + "')")
	return { 'success': True }
	
def do_build(user_id, client_token, last_id, sector, loc, type, poll_afterwards=True):
	sector = util.tsanitize(sector)
	loc = util.tsanitize(loc)
	last_id = util.parseInt(last_id)
	
	verify_position = sql.query("SELECT `hq_sector` FROM `user` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	if verify_position[0]['hq_sector'] == sector:
		
		if client_token:
			duplicate = sql.query(
				'SELECT `client_token` FROM `event` WHERE `client_token` = %s', (client_token,))
			if not duplicate and validate_building(type, sector, loc):
				
				error = verify_placement(type, sector, loc)
				if error == None:
					
					if type == 'hq' or try_deplete_resources(
						user_id,
						settings.building_cost[type][0],
						settings.building_cost[type][1],
						settings.building_cost[type][2],
						settings.building_cost[type][3],
						settings.building_cost[type][4],
						settings.building_cost[type][5]):
						
						data = 'Build:%s,%s' % (type, loc)
						event_id = sql.insert(
							'INSERT INTO `event` (`client_token`, `sector_xy`, `user_id`, `data`) VALUES (%s, %s, %s, %s)', (client_token, sector, user_id, data))
						quarry_data = ''
						if type == 'quarry':
							resources = 'a c s'.split(' ')
							distribution = [int(random.random() * 101)]
							rdist = int(random.random() * (100 - distribution[0] + 1))
							distribution.append(rdist)
							distribution.append(100 - sum(distribution))
							random.shuffle(distribution)
							
							quarry_data = 'a' + str(distribution[0]) + 'c' + str(distribution[1]) + 's' + str(distribution[2])
						sql.insert('INSERT INTO `structure` (`type`, `sector_xy`, `loc_xy`, `user_id`, `event_id`, `data`) VALUES (%s, %s, %s, %s, %s, %s)', (type, sector, loc, user_id, event_id, quarry_data))
					else:
						return { 'success': False, 'message': "Insufficient resources" }
				else:
					return { 'success': False, 'message': error }
			if poll_afterwards:
				return poll.do_poll(user_id, str(last_id) + '^' + sector)
		else:
			return { 'success':False, 'message': "missing client token" }
	else:
		return { 'success': False, 'message': "Cannot build this far from your HQ" }
def get_quarry_data(user_id, sector, xy):
	if sector == None or xy == None:
		return { 'success': False, 'message': "Invalid args" }
	
	buildings = sql.query("SELECT `type`, `sector_xy`, `loc_xy`, `user_id`, `data` FROM `structure` WHERE `user_id` = " + str(user_id))
	quarry = None
	for building in buildings:
		if building['type'] == 'quarry':
			if building['sector_xy'] == sector and building['loc_xy'] == xy:
				quarry = building
				break
	
	if quarry == None:
		return { 'success': False, 'message': "Quarry Not Found" }
	
	data = quarry['data']
	
	x = data.split('c')
	a = int(x[0][1:])
	x = x[1].split('s')
	c = int(x[0])
	s = int(x[1])
	
	return { 'success': True, 'a': a, 'c': c, 's': s }
	
	
Example #9
0
def get_quarry_data(user_id, sector, xy):
    if sector == None or xy == None:
        return {'success': False, 'message': "Invalid args"}

    buildings = sql.query(
        "SELECT `type`, `sector_xy`, `loc_xy`, `user_id`, `data` FROM `structure` WHERE `user_id` = "
        + str(user_id))
    quarry = None
    for building in buildings:
        if building['type'] == 'quarry':
            if building['sector_xy'] == sector and building['loc_xy'] == xy:
                quarry = building
                break

    if quarry == None:
        return {'success': False, 'message': "Quarry Not Found"}

    data = quarry['data']

    x = data.split('c')
    a = int(x[0][1:])
    x = x[1].split('s')
    c = int(x[0])
    s = int(x[1])

    return {'success': True, 'a': a, 'c': c, 's': s}
def light_authenticate(user_id, password):
    result = sql.query(
        "SELECT `user_id`, `password` FROM `user` WHERE `user_id`=%s LIMIT 1",
        (user_id, ))
    if len(result) == 0:
        return False
    return result[0]['password'] == password
def verify_placement(type, sector, loc):
    too_close = "Cannot place building next to another building"
    edge_of_sector = "Cannot build this far from your HQ"

    sx, sy = map(int, sector.split("^"))
    x, y = map(int, loc.split("^"))

    if x >= 59 or y >= 59:
        return edge_of_sector

    size = settings.building_size[type]

    occupied_tiles = {}

    existing = sql.query("SELECT `type`, `loc_xy` FROM `structure` WHERE `sector_xy` = %s", (sector,))
    for existingb in existing:
        bx, by = map(int, existingb["loc_xy"].split("^"))
        bs = settings.building_size[existingb["type"]]

        for px in range(bx - 1, bx + bs + 1):
            for py in range(by - 1, by + bs + 1):
                occupied_tiles[(px, py)] = True

    for px in range(x, x + size):
        for py in range(y, y + size):
            if occupied_tiles.get((px, py), None) != None:
                return too_close

    return None
def verify_placement(type, sector, loc):
	too_close = "Cannot place building next to another building"
	edge_of_sector = "Cannot build this far from your HQ"
	
	sx, sy = map(int, sector.split('^'))
	x, y = map(int, loc.split('^'))
	
	if x >= 59 or y >= 59: return edge_of_sector
	
	size = settings.building_size[type]
	
	occupied_tiles = {}
	
	existing = sql.query("SELECT `type`, `loc_xy` FROM `structure` WHERE `sector_xy` = %s", (sector,))
	for existingb in existing:
		bx, by = map(int, existingb['loc_xy'].split('^'))
		bs = settings.building_size[existingb['type']]
		
		for px in range(bx - 1, bx + bs + 1):
			for py in range(by - 1, by + bs + 1):
				occupied_tiles[(px, py)] = True
	
	for px in range(x, x + size):
		for py in range(y, y + size):
			if occupied_tiles.get((px, py), None) != None:
				return too_close
	
	return None
	
def try_deplete_resources(user_id, food, water, aluminum, copper, silicon, oil):
	current = sql.query("SELECT * FROM `resource_status` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	current = current[0]
	if current['food'] < food: return False
	if current['water'] < water: return False
	if current['aluminum'] < aluminum: return False
	if current['copper'] < copper: return False
	if current['oil'] < oil: return False
	
	sql.query("UPDATE `resource_status` SET " + ', '.join([
		"`food` = `food` - " + str(food),
		"`water` = `water` - " + str(water),
		"`aluminum` = `aluminum` - " + str(aluminum),
		"`copper` = `copper` - " + str(copper),
		"`silicon` = `silicon` - " + str(silicon),
		"`oil` = `oil` - " + str(oil)]) + " WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	return True
def award_resources(user_id, alien_type):
	if not alien_type in ('1', '2', '3'):
		return { 'success': False, 'message': "Invalid args" }
	
	if alien_type == '1':
		award = settings.ALIEN_DROPS[0]
	elif alien_type == '2':
		award = settings.ALIEN_DROPS[1]
	else: #elif alien_type == '3':
		award = settings.ALIEN_DROPS[2]
	
	updates = []
	for key in award.keys():
		updates.append("`" + key + "` = `" + key + "` + " + str(award[key]))
	sql.query("UPDATE `resource_status` SET " + ', '.join(updates) + " WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	
	return { 'success': True }
def award_resources(user_id, alien_type):
    if not alien_type in ('1', '2', '3'):
        return {'success': False, 'message': "Invalid args"}

    if alien_type == '1':
        award = settings.ALIEN_DROPS[0]
    elif alien_type == '2':
        award = settings.ALIEN_DROPS[1]
    else:  #elif alien_type == '3':
        award = settings.ALIEN_DROPS[2]

    updates = []
    for key in award.keys():
        updates.append("`" + key + "` = `" + key + "` + " + str(award[key]))
    sql.query("UPDATE `resource_status` SET " + ', '.join(updates) +
              " WHERE `user_id` = " + str(user_id) + " LIMIT 1")

    return {'success': True}
def award_bytes(user_id, attacked_id, num_bytes):
	attacked_id = util.parseInt(attacked_id)
	num_bytes = util.parseInt(num_bytes)
	if attacked_id <= 0 or num_bytes <= 0:
		return { 'success': False, 'message': "Invalid args" }
	
	user_exists = sql.query("SELECT `user_id` FROM `user` WHERE `user_id` = " + str(attacked_id) + " LIMIT 1")
	if len(user_exists) == 0:
		return { 'success': False, 'message': "User doesn't exist. Are you a l33t hax0r?" }
	
	
	sql.query("UPDATE `user` SET `research` = `research` + " + str(num_bytes) + " WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	
	new_research = sql.query("SELECT `research` FROM `user` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	
	return { 'success': True, 'research': new_research[0]['research'] }
	
		
def apply_research(user_id, type):
    bytes_known = sql.query(
        "SELECT `research` FROM `user` WHERE `user_id` = " + str(user_id) +
        " LIMIT 1")
    bytes_known = bytes_known[0]['research']
    cost = settings.building_research.get(type, None)
    if cost == None:
        return {'success': False, 'message': "Invalid building type"}
    if bytes_known < cost:
        return {'success': False, 'message': "Insufficient Data"}

    already = sql.query(
        "SELECT `user_id` FROM `research_unlocked` WHERE `user_id` = " +
        str(user_id) + " AND `type` = '" + str(type) + "' LIMIT 1")
    if len(already) == 0:
        sql.query(
            "INSERT INTO `research_unlocked` (`user_id`, `type`) VALUES (" +
            str(user_id) + ", '" + str(type) + "')")
    return {'success': True}
def get_sector():
    while True:
        start_locs = sql.query("SELECT `hq_sector` AS 'sector' FROM `user`")
        bad_locs = sql.query("SELECT `sector` FROM `bad_start_location`")
        exhausted = {}

        for loc in start_locs + bad_locs:
            exhausted[loc['sector']] = True

        vacant = []
        i = 1
        while True:
            r = range(-i, i + 1)
            for dy in r:
                for dx in r:
                    sector = str(dx) + '^' + str(dy)
                    if not exhausted.get(sector, False):
                        vacant.append(sector)

            if len(vacant) > 5:
                break
            else:
                vacant = []
                i += 1

        random.shuffle(vacant)

        for sector in vacant:
            sx, sy = map(int, sector.split('^'))
            for point in get_inner_coords():
                px, py = point

                ax = sx * 60 + px
                ay = sy * 60 + py

                rx, ry = terrain.toCenterRender(ax, ay)

                if terrain.validstart(rx, ry):

                    return (sx, sy, px, py)

            sql.query("INSERT INTO `bad_start_location` (`sector`) VALUES ('" +
                      sector + "')")
def get_sector():
	while True:
		start_locs = sql.query("SELECT `hq_sector` AS 'sector' FROM `user`")
		bad_locs = sql.query("SELECT `sector` FROM `bad_start_location`")
		exhausted = {}
		
		for loc in start_locs + bad_locs:
			exhausted[loc['sector']] = True
		
		vacant = []
		i = 1
		while True:
			r = range(-i, i + 1)
			for dy in r:
				for dx in r:
					sector = str(dx) + '^' + str(dy)
					if not exhausted.get(sector, False):
						vacant.append(sector)
			
			if len(vacant) > 5:
				break
			else:
				vacant = []
				i += 1
		
		random.shuffle(vacant)
		
		for sector in vacant:
			sx, sy = map(int, sector.split('^'))
			for point in get_inner_coords():
				px, py = point
				
				ax = sx * 60 + px
				ay = sy * 60 + py
				
				rx, ry = terrain.toCenterRender(ax, ay)
				
				if terrain.validstart(rx, ry):
					
					return (sx, sy, px, py)
		
			sql.query("INSERT INTO `bad_start_location` (`sector`) VALUES ('" + sector + "')")
def get_count(user_id):
    counts = sql.query("SELECT * FROM `bots` WHERE `user_id` = " +
                       str(user_id) + " LIMIT 1")
    if len(counts) == 0:
        return {'success': True, 'a': 0, 'b': 0, 'c': 0}
    c = counts[0]
    return {
        'success': True,
        'a': c['type_a'],
        'b': c['type_b'],
        'c': c['type_c']
    }
def validate_building(type, sector, coordinate):
    # for now, having those is enough
    if type and sector and coordinate:
        if type in settings.building_cost.keys():
            x, y = map(int, coordinate.split("^"))
            others = sql.query("SELECT * FROM `structure` WHERE `sector_xy` = %s", (sector,))
            for other in others:
                ox, oy = map(int, other["loc_xy"].split("^"))
                otype = other["type"]
                # TODO: make sure that x,y,type does not conflict geographically with ox,oy,otype
                # Buildings cannot be placed next to each other.
            return True
    return False
def heavy_authenticate(user, password, register_if_new=False, is_new=False):
	failure_message = { 'success': False, 'message': "Invalid username/password." }
	login_id = util.alphanums(user)
	result = sql.query("SELECT `user_id`, `password`, `hq_sector`, `hq_loc`, `research` FROM `user` WHERE `login_id`=%s LIMIT 1",(login_id,) )
	if len(result) == 0:
		if register_if_new:
			user_id = add_user(user, password)
			if user_id == 0:
				return { 'success': False, 'message': "Could not register account. Usernames must have at least 1 alphanumeric character" }
			return heavy_authenticate(user, password, False, True)
		return failure_message
	
	data = result[0]
	
	user_id = data['user_id']
	buildings_db = sql.query("SELECT `type` FROM `research_unlocked` WHERE `user_id` = " + str(user_id))
	buildings = []
	for building in buildings_db:
		buildings.append(building['type'])
	
	bots_db = sql.query("SELECT * FROM `bots` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	if len(bots_db) == 0:
		bots = [0, 0, 0]
	else:
		row = bots_db[0]
		bots = [row['type_a'], row['type_b'], row['type_c']]
	
	if data['password'] == password:
		return {
			'success': True,
			'user_id': data['user_id'],
			'hq': (data['hq_sector'], data['hq_loc']),
			'is_new': is_new,
			'research': data['research'],
			'buildings': buildings,
			'bots': bots
		}
	else:
		return failure_message
def validate_building(type, sector, coordinate):
	#for now, having those is enough
	if type and sector and coordinate:
		if type in settings.building_cost.keys():
			x,y = map(int, coordinate.split('^'))
			others = sql.query("SELECT * FROM `structure` WHERE `sector_xy` = %s", (sector,))
			for other in others:
				ox,oy = map(int, other['loc_xy'].split('^'))
				otype = other['type']
				# TODO: make sure that x,y,type does not conflict geographically with ox,oy,otype
				# Buildings cannot be placed next to each other. 
			return True
	return False
def award_bytes(user_id, attacked_id, num_bytes):
    attacked_id = util.parseInt(attacked_id)
    num_bytes = util.parseInt(num_bytes)
    if attacked_id <= 0 or num_bytes <= 0:
        return {'success': False, 'message': "Invalid args"}

    user_exists = sql.query("SELECT `user_id` FROM `user` WHERE `user_id` = " +
                            str(attacked_id) + " LIMIT 1")
    if len(user_exists) == 0:
        return {
            'success': False,
            'message': "User doesn't exist. Are you a l33t hax0r?"
        }

    sql.query("UPDATE `user` SET `research` = `research` + " + str(num_bytes) +
              " WHERE `user_id` = " + str(user_id) + " LIMIT 1")

    new_research = sql.query(
        "SELECT `research` FROM `user` WHERE `user_id` = " + str(user_id) +
        " LIMIT 1")

    return {'success': True, 'research': new_research[0]['research']}
Example #25
0
def find_neighbors(user_id, rx, ry):
	failure = { 'success': False, 'message': "The radar seems to be broken." }
	if rx == None or ry == None:
		return failure
	
	rx = int(rx)
	ry = int(ry)
	
	players = sql.query("SELECT `user_id`, `name`, `hq_sector`, `hq_loc` FROM `user`")
	data = []
	
	youx, youy = None, None
	for player in players:
	
		sx, sy = map(int, player['hq_sector'].split('^'))
		px, py = map(int, player['hq_loc'].split('^'))
		
		x = sx * 60 + px
		y = sy * 60 + py
		
		data.append(
			[player['name'], x, y, 99999, player['user_id']])
	i = 0
	while i < len(data):
		datum = data[i]
		dx = rx - datum[1]
		dy = ry - datum[2]
		
		d = (dx * dx + dy * dy) ** .5
		datum[3] = d
		i += 1
	
	
	data.sort(key=lambda item:item[3])
	
	output = []
	
	data = data[:11]
	
	
	
	return {
		'success': True,
		'neighbors': data
	}
def produce_bot(user_id, type):
	s = 0
	if type in '123':
		s = int(type)
	
	if s < 1 or s > 3:
		return { 'success': False, 'message': "Invalid args" }
	
	structures = sql.query("SELECT `type` FROM `structure` WHERE `user_id` = " + str(user_id))
	desired_type = [None, 'foundry', 'machinerylab', 'sciencelab'][s]
	total = 0
	for structure in structures:
		if structure['type'] == desired_type:
			total += 1
	
	current = sql.query("SELECT `type_a`, `type_b`, `type_c` FROM `bots` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	if len(current) == 0:
		current = [None, 0, 0, 0]
		sql.query("INSERT INTO `bots` (`user_id`) VALUES (" + str(user_id) + ")")
	else:
		current = current[0]
		current = [None,
			current['type_a'],
			current['type_b'],
			current['type_c']]
	
	max = total * 3
	
	if current[s] < max:
		cost = [None, settings.BOT_COST_1, settings.BOT_COST_2, settings.BOT_COST_3][s]
		if build.try_deplete_resources(
			user_id,
			cost['food'],
			cost['water'],
			cost['aluminum'],
			cost['copper'],
			cost['silicon'],
			cost['oil']):
			
			letter = ' abc'[s]
			sql.query("UPDATE `bots` SET `type_" + letter + "` = `type_" + letter + "` + 1 WHERE `user_id` = " + str(user_id) + " LIMIT 1")
			
			current[s] += 1
			return { 'success': True, 'a': current[1], 'b': current[2], 'c': current[3] }
		else:
			return { 'success': False, 'message': "You do not have enough resources", 'error': 'resources' }
		
	else:
		return { 'success': False, 'message': "You cannot produce more bots of this type", 'err': 'capacity' }
Example #27
0
def do_poll(user_id, sector_args):
	output = { 'success': True }
	sectors = []
	for sector in sector_args.split(','):
		parts = sector.split('^')
		if len(parts) == 3: # ignore malformed input. They're probably hacking and don't really deserve a neatly formatted response.
			last_id = int(parts[0])
			sector_x = int(parts[1])
			sector_y = int(parts[2])
			sector_id = str(sector_x) + '^' + str(sector_y)
			sector_data = { 'id': sector_id }
			
			if last_id == 0:
				# need a full history, just get all structures
				sector_data['all'] = True
				structures_db = sql.query("SELECT `structure_id`,`type`,`loc_xy`,`user_id`,`event_id` FROM `structure` WHERE `sector_xy` = %s", (sector_id,))
				structures = []
				sector_data['structures'] = structures
				max_id = 1 # not a mistake
				for structure in structures_db:
					structures.append([
						structure['structure_id'],
						structure['type'],
						structure['loc_xy'],
						structure['user_id'],
						structure['event_id']])
					if max_id < structure['event_id']:
						max_id = structure['event_id']
				structures.sort(key=lambda x:x[4])
				sector_data['valid_through'] = max_id
			else:
				# need recent history, get all events after a certain point
				sector_data['all'] = False
				all_events = []
				sector_data['events'] = all_events
				events_db = sql.query("SELECT `event_id`, `client_token`, `user_id`, `data` FROM `event` WHERE `sector_xy` = %s AND `event_id` > " + str(last_id), (sector_id,))
				for event in events_db:
					data = event['data']
					client_token = event['client_token'] if event['user_id'] == user_id else None
					e = [event['event_id'], client_token, event['user_id'], data]
					all_events.append(e)
			sectors.append(sector_data)
	output['sectors'] = sectors
	
	your_buildings = sql.query("SELECT `type`, `data` FROM `structure` WHERE `user_id` = " + str(user_id))
	resources = { 'water': 0.1, 'food': 0.1, 'oil': 0.0, 'aluminum': 0.0, 'copper': 0.0, 'silicon': 0 }
	for building in your_buildings:
		if building['type'] == 'farm':
			resources['food'] += 10
		elif building['type'] == 'hq':
			pass   # No need since you can kill aliens for these
		elif building['type'] == 'resevoir':
			resources['water'] += 10
		elif building['type'] == 'greenhouse':
			resources['food'] += 3
			resources['water'] += 3
		elif building['type'] == 'drill':
			resources['oil'] += 5
		elif building['type'] == 'quarry':
			data = building['data']
			# horrible hack
			x = data.split('c')
			a = int(x[0][1:])
			x = x[1].split('s')
			c = int(x[0])
			s = int(x[1])
			resources['aluminum'] += a / 1.0
			resources['copper'] += c / 2.0
			resources['silicon'] += s / 4.0
	
	import time
	now = int(time.time())
	current = sql.query("SELECT * FROM `resource_status` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	current = current[0]
	
	diff = now - current['last_poll']
	
	if diff > 20: diff = 20 # don't let them collect resources while they're not playing
	
	setters = []
	
	for key in resources.keys():
		resources[key] *= diff / 10.0
		resources[key] += current[key]
		if resources[key] > 10000:
			resources[key] = 10000
		setters.append("`" + key + "` = " + str(resources[key]))
	
	setters.append("`last_poll` = " + str(now))
	
	sql.query("UPDATE `resource_status` SET " + ', '.join(setters) + " WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	
	output['resources'] = resources
	
	return output
def DEBUG_resources(user_id):
	sql.query("UPDATE `resource_status` SET `food` = `food` + 9999, `water` = `water` + 9999, `aluminum` = `aluminum` + 9999, `copper` = `copper` + 9999, `silicon` = `silicon` + 9999, `oil` = `oil` + 9999 WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	return { 'success': True }
def dispatch(user_id):
	counts = get_count(user_id)
	
	sql.query("UPDATE `bots` SET `type_a` = 0, `type_b` = 0, `type_c` = 0 WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	
	return counts
def get_count(user_id):
	counts = sql.query("SELECT * FROM `bots` WHERE `user_id` = " + str(user_id) + " LIMIT 1")
	if len(counts) == 0:
		return { 'success': True, 'a': 0, 'b': 0, 'c': 0 }
	c = counts[0]
	return { 'success': True, 'a': c['type_a'], 'b': c['type_b'], 'c': c['type_c'] }
def DEBUG_resources(user_id):
    sql.query(
        "UPDATE `resource_status` SET `food` = `food` + 9999, `water` = `water` + 9999, `aluminum` = `aluminum` + 9999, `copper` = `copper` + 9999, `silicon` = `silicon` + 9999, `oil` = `oil` + 9999 WHERE `user_id` = "
        + str(user_id) + " LIMIT 1")
    return {'success': True}
Example #32
0
def do_poll(user_id, sector_args):
    output = {'success': True}
    sectors = []
    for sector in sector_args.split(','):
        parts = sector.split('^')
        if len(
                parts
        ) == 3:  # ignore malformed input. They're probably hacking and don't really deserve a neatly formatted response.
            last_id = int(parts[0])
            sector_x = int(parts[1])
            sector_y = int(parts[2])
            sector_id = str(sector_x) + '^' + str(sector_y)
            sector_data = {'id': sector_id}

            if last_id == 0:
                # need a full history, just get all structures
                sector_data['all'] = True
                structures_db = sql.query(
                    "SELECT `structure_id`,`type`,`loc_xy`,`user_id`,`event_id` FROM `structure` WHERE `sector_xy` = %s",
                    (sector_id, ))
                structures = []
                sector_data['structures'] = structures
                max_id = 1  # not a mistake
                for structure in structures_db:
                    structures.append([
                        structure['structure_id'], structure['type'],
                        structure['loc_xy'], structure['user_id'],
                        structure['event_id']
                    ])
                    if max_id < structure['event_id']:
                        max_id = structure['event_id']
                structures.sort(key=lambda x: x[4])
                sector_data['valid_through'] = max_id
            else:
                # need recent history, get all events after a certain point
                sector_data['all'] = False
                all_events = []
                sector_data['events'] = all_events
                events_db = sql.query(
                    "SELECT `event_id`, `client_token`, `user_id`, `data` FROM `event` WHERE `sector_xy` = %s AND `event_id` > "
                    + str(last_id), (sector_id, ))
                for event in events_db:
                    data = event['data']
                    client_token = event['client_token'] if event[
                        'user_id'] == user_id else None
                    e = [
                        event['event_id'], client_token, event['user_id'], data
                    ]
                    all_events.append(e)
            sectors.append(sector_data)
    output['sectors'] = sectors

    your_buildings = sql.query(
        "SELECT `type`, `data` FROM `structure` WHERE `user_id` = " +
        str(user_id))
    resources = {
        'water': 0.1,
        'food': 0.1,
        'oil': 0.0,
        'aluminum': 0.0,
        'copper': 0.0,
        'silicon': 0
    }
    for building in your_buildings:
        if building['type'] == 'farm':
            resources['food'] += 10
        elif building['type'] == 'hq':
            pass  # No need since you can kill aliens for these
        elif building['type'] == 'resevoir':
            resources['water'] += 10
        elif building['type'] == 'greenhouse':
            resources['food'] += 3
            resources['water'] += 3
        elif building['type'] == 'drill':
            resources['oil'] += 5
        elif building['type'] == 'quarry':
            data = building['data']
            # horrible hack
            x = data.split('c')
            a = int(x[0][1:])
            x = x[1].split('s')
            c = int(x[0])
            s = int(x[1])
            resources['aluminum'] += a / 1.0
            resources['copper'] += c / 2.0
            resources['silicon'] += s / 4.0

    import time
    now = int(time.time())
    current = sql.query("SELECT * FROM `resource_status` WHERE `user_id` = " +
                        str(user_id) + " LIMIT 1")
    current = current[0]

    diff = now - current['last_poll']

    if diff > 20:
        diff = 20  # don't let them collect resources while they're not playing

    setters = []

    for key in resources.keys():
        resources[key] *= diff / 10.0
        resources[key] += current[key]
        if resources[key] > 10000:
            resources[key] = 10000
        setters.append("`" + key + "` = " + str(resources[key]))

    setters.append("`last_poll` = " + str(now))

    sql.query("UPDATE `resource_status` SET " + ', '.join(setters) +
              " WHERE `user_id` = " + str(user_id) + " LIMIT 1")

    output['resources'] = resources

    return output
def produce_bot(user_id, type):
    s = 0
    if type in '123':
        s = int(type)

    if s < 1 or s > 3:
        return {'success': False, 'message': "Invalid args"}

    structures = sql.query(
        "SELECT `type` FROM `structure` WHERE `user_id` = " + str(user_id))
    desired_type = [None, 'foundry', 'machinerylab', 'sciencelab'][s]
    total = 0
    for structure in structures:
        if structure['type'] == desired_type:
            total += 1

    current = sql.query(
        "SELECT `type_a`, `type_b`, `type_c` FROM `bots` WHERE `user_id` = " +
        str(user_id) + " LIMIT 1")
    if len(current) == 0:
        current = [None, 0, 0, 0]
        sql.query("INSERT INTO `bots` (`user_id`) VALUES (" + str(user_id) +
                  ")")
    else:
        current = current[0]
        current = [
            None, current['type_a'], current['type_b'], current['type_c']
        ]

    max = total * 3

    if current[s] < max:
        cost = [
            None, settings.BOT_COST_1, settings.BOT_COST_2, settings.BOT_COST_3
        ][s]
        if build.try_deplete_resources(user_id, cost['food'], cost['water'],
                                       cost['aluminum'], cost['copper'],
                                       cost['silicon'], cost['oil']):

            letter = ' abc'[s]
            sql.query("UPDATE `bots` SET `type_" + letter + "` = `type_" +
                      letter + "` + 1 WHERE `user_id` = " + str(user_id) +
                      " LIMIT 1")

            current[s] += 1
            return {
                'success': True,
                'a': current[1],
                'b': current[2],
                'c': current[3]
            }
        else:
            return {
                'success': False,
                'message': "You do not have enough resources",
                'error': 'resources'
            }

    else:
        return {
            'success': False,
            'message': "You cannot produce more bots of this type",
            'err': 'capacity'
        }
def do_demolish(user_id, last_id, sector, loc, client_token):
	#last_id = util.parseInt(last_id)
	if sector == None or loc == None: return { 'success': False, "message": "Malformed input" }
	if client_token == None: return { 'success': False, 'message': "Missing client token" }
	sx, sy = util.tuple_from_coord(sector)
	x, y = util.tuple_from_coord(loc)
	poll_afterwards = last_id > 0
	
	# TODO: distinguish between involuntary demolition and damage
	
	# get building data
	
	target = -1
	buildings = sql.query("SELECT * FROM `structure` WHERE `user_id` = " + str(user_id))
	
	for building in buildings:
		bx, by = util.tuple_from_coord(building['loc_xy'])
		bsx, bsy = util.tuple_from_coord(building['sector_xy'])
		type = building['type']
		id = building['structure_id']
		
		if type == 'hq': continue
		
		size = util.get_structure_size(type)
		
		for px in range(bx, bx + size):
			tsx = bsx + px // 60
			px = px % 60
			for py in range(by, by + size):
				tsy = bsy + py // 60
				py = py % 60
				if px == x and py == y and sx == tsx and sy == tsy:
					target = id
	
					# convert coordinates to be north corner
					sx = bsx
					sy = bsy
					x = bx
					y = by
					break
			if target != -1: break
		
		if target != -1: break
	
	if target == -1:
		return { 'success': False, 'message': "Invalid target" }
	
	building_id = target
	
	
	
	
	sector = str(sx) + '^' + str(sy)
	loc = str(x) + '^' + str(y)
	data = "Demolish:" + loc
	
	token_exists = sql.query("SELECT `event_id` FROM `event` WHERE `client_token` = %s LIMIT 1", (client_token,))
	if token_exists:
		pass
	else:
		event_id = sql.insert(' '.join([
			"INSERT INTO `event`",
			"(`sector_xy`,`client_token`,`user_id`,`data`)",
			"VALUES",
			"(%s, %s, " + str(user_id) + ", %s)"]),
			(sector, client_token, data))
		
		sql.query("DELETE FROM `structure` WHERE `structure_id` = " + str(building_id) + " LIMIT 1")
		# no polling, I guess. This gets really complex since the target can be in a different
		# sector than the original request. Let updates come through the normal polling pipeline
	return { 'success': True }
		
Example #35
0
def get_user_info():
	return sql.query("SELECT `user_id` AS 'id',`name`, `research` AS 'bytes', `hq_sector`, `hq_loc` FROM `user`")
	
	
Example #36
0
def do_demolish(user_id, last_id, sector, loc, client_token):
    #last_id = util.parseInt(last_id)
    if sector == None or loc == None:
        return {'success': False, "message": "Malformed input"}
    if client_token == None:
        return {'success': False, 'message': "Missing client token"}
    sx, sy = util.tuple_from_coord(sector)
    x, y = util.tuple_from_coord(loc)
    poll_afterwards = last_id > 0

    # TODO: distinguish between involuntary demolition and damage

    # get building data

    target = -1
    buildings = sql.query("SELECT * FROM `structure` WHERE `user_id` = " +
                          str(user_id))

    for building in buildings:
        bx, by = util.tuple_from_coord(building['loc_xy'])
        bsx, bsy = util.tuple_from_coord(building['sector_xy'])
        type = building['type']
        id = building['structure_id']

        if type == 'hq': continue

        size = util.get_structure_size(type)

        for px in range(bx, bx + size):
            tsx = bsx + px // 60
            px = px % 60
            for py in range(by, by + size):
                tsy = bsy + py // 60
                py = py % 60
                if px == x and py == y and sx == tsx and sy == tsy:
                    target = id

                    # convert coordinates to be north corner
                    sx = bsx
                    sy = bsy
                    x = bx
                    y = by
                    break
            if target != -1: break

        if target != -1: break

    if target == -1:
        return {'success': False, 'message': "Invalid target"}

    building_id = target

    sector = str(sx) + '^' + str(sy)
    loc = str(x) + '^' + str(y)
    data = "Demolish:" + loc

    token_exists = sql.query(
        "SELECT `event_id` FROM `event` WHERE `client_token` = %s LIMIT 1",
        (client_token, ))
    if token_exists:
        pass
    else:
        event_id = sql.insert(
            ' '.join([
                "INSERT INTO `event`",
                "(`sector_xy`,`client_token`,`user_id`,`data`)", "VALUES",
                "(%s, %s, " + str(user_id) + ", %s)"
            ]), (sector, client_token, data))

        sql.query("DELETE FROM `structure` WHERE `structure_id` = " +
                  str(building_id) + " LIMIT 1")
        # no polling, I guess. This gets really complex since the target can be in a different
        # sector than the original request. Let updates come through the normal polling pipeline
    return {'success': True}
def light_authenticate(user_id, password):
	result = sql.query("SELECT `user_id`, `password` FROM `user` WHERE `user_id`=%s LIMIT 1",(user_id,) )
	if len(result) == 0:
		return False
	return result[0]['password'] == password