Esempio n. 1
0
def costcheck(world, order):
    cost = {
        'geu': 0,
        'duranium': 0,
        'tritanium': 0,
        'adamantium': 0,
        'productionpoints': 0,
    }
    status = cost.copy()
    shipcosts = v.shipcosts(world.sector)
    assets = world.buildcapacity()
    goodtogo = True
    #calculate dem costs
    for ship, amount in order.iteritems():
        if amount > 0:
            for key in cost:
                cost[key] += shipcosts[ship][key] * amount
    #compare to current assets
    for key in assets:
        if assets[key] < cost[key]:
            status[key] = False #not enough of a given resource
            goodtogo = False
        else:
            status[key] = True
    status.update({'status': goodtogo, 'cost': cost})
    return status
Esempio n. 2
0
def costcheck(world, order):
    cost = {
        'geu': 0,
        'duranium': 0,
        'tritanium': 0,
        'adamantium': 0,
        'productionpoints': 0,
    }
    status = cost.copy()
    shipcosts = v.shipcosts(world.sector)
    assets = world.buildcapacity()
    goodtogo = True
    #calculate dem costs
    for ship, amount in order.iteritems():
        if amount > 0:
            for key in cost:
                cost[key] += shipcosts[ship][key] * amount
    #compare to current assets
    for key in assets:
        if assets[key] < cost[key]:
            status[key] = False  #not enough of a given resource
            goodtogo = False
        else:
            status[key] = True
    status.update({'status': goodtogo, 'cost': cost})
    return status
Esempio n. 3
0
 def fuelcost(self):
     fuel = 0
     fuellist = v.shipcosts()
     for field in list(self._meta.fields)[v.fleetindex:]:
         fuel += self.__dict__[field.name] * fuellist[field.name]['fuel']
     if self.flagship:
         fuel += 5
     return fuel
Esempio n. 4
0
 def basepower(self):
     power = 0
     powerlist = v.shipcosts()
     for field in list(self._meta.fields)[v.fleetindex:]:
         power += self.__dict__[field.name] * powerlist[field.name]['firepower']
     if self.flagship:
         power += 50
     return power
Esempio n. 5
0
 def fuelcost(self):
     fuel = 0
     fuellist = v.shipcosts()
     for field in list(self._meta.fields)[v.fleetindex:]:
         fuel += self.__dict__[field.name] * fuellist[field.name]['fuel']
     if self.flagship:
         fuel += 5
     return fuel
Esempio n. 6
0
 def basepower(self):
     power = 0
     powerlist = v.shipcosts()
     for field in list(self._meta.fields)[v.fleetindex:]:
         power += self.__dict__[field.name] * powerlist[
             field.name]['firepower']
     if self.flagship:
         power += 50
     return power
Esempio n. 7
0
def salvage(loss):
    'Creates salvage from a shiplist.'
    totd = tott = tota = 0
    matcosts = v.shipcosts()
    for ship in list(loss._meta.fields)[v.fleetindex:]:
        totd += matcosts[ship.name]['duranium']*loss.__dict__[ship.name]/random.randint(3, 10)
        tott += matcosts[ship.name]['tritanium']*loss.__dict__[ship.name]/random.randint(3, 10)
        tota += matcosts[ship.name]['adamantium']*loss.__dict__[ship.name]/random.randint(3, 10)
    return int(totd), int(tott), int(tota)
Esempio n. 8
0
def salvage(loss):
    'Creates salvage from a shiplist.'
    totd = tott = tota = 0
    matcosts = v.shipcosts()
    for ship in list(loss._meta.fields)[v.fleetindex:]:
        totd += matcosts[ship.name]['duranium'] * loss.__dict__[
            ship.name] / random.randint(3, 10)
        tott += matcosts[ship.name]['tritanium'] * loss.__dict__[
            ship.name] / random.randint(3, 10)
        tota += matcosts[ship.name]['adamantium'] * loss.__dict__[
            ship.name] / random.randint(3, 10)
    return int(totd), int(tott), int(tota)
Esempio n. 9
0
def milpolicydisplay(world):
    costs = v.shipcosts(world.sector)
    iterlist = ['freighters']
    for element in v.tiers:
        iterlist.append(element.replace(' ', '_').lower() + 's')
        if element == world.techlevel:
            break #max tech level we can produce

    #now assemble a list of dictionaries, not a list of lists
    #because heidi didn't just <td></td><td></td>
    #he absolutely had to add spans and shit
    displaylist = []
    for element in iterlist:
        #human friendly name
        appendage = {
            'name': element.replace('_', ' ').capitalize()[:len(element) - 1],
            'fname': element}
        appendage.update(costs[element])
        displaylist.append(appendage) 
    return displaylist
Esempio n. 10
0
def milpolicydisplay(world):
    costs = v.shipcosts(world.sector)
    iterlist = ['freighters']
    for element in v.tiers:
        iterlist.append(element.replace(' ', '_').lower() + 's')
        if element == world.techlevel:
            break  #max tech level we can produce

    #now assemble a list of dictionaries, not a list of lists
    #because heidi didn't just <td></td><td></td>
    #he absolutely had to add spans and shit
    displaylist = []
    for element in iterlist:
        #human friendly name
        appendage = {
            'name': element.replace('_', ' ').capitalize()[:len(element) - 1],
            'fname': element
        }
        appendage.update(costs[element])
        displaylist.append(appendage)
    return displaylist
Esempio n. 11
0
def war_losses(damage, shiplist):
    'Distributes battle losses among a fleet.'
    reference = fleet()
    reference.merge(shiplist) #we use a reference here
    #and use an atomic transaction for actual fleet manipulation
    lost = fleet() #to be returned and merged with active fleet
    shipinfo = v.shipcosts()
    highest = v.shipindices.index(highesttier(shiplist))
    highest += 1 #take discrepancy between list indexes and whatever into account
    repeat = 0
    while damage > 0:
        shiplost = weighted_choice(reference, highest)
        if shiplost is None: #fleet got decimated
            return lost
        if damage < shipinfo[shiplost]['damage'] and repeat < 20:
            repeat += 1
        elif repeat >= 20:
            break
        else:
            repeat = 0
            reference.__dict__[shiplost] -= 1
            lost.__dict__[shiplost] += 1
            damage -= shipinfo[shiplost]['damage']
    return lost
Esempio n. 12
0
def war_losses(damage, shiplist):
    'Distributes battle losses among a fleet.'
    reference = fleet()
    reference.merge(shiplist)  #we use a reference here
    #and use an atomic transaction for actual fleet manipulation
    lost = fleet()  #to be returned and merged with active fleet
    shipinfo = v.shipcosts()
    highest = v.shipindices.index(highesttier(shiplist))
    highest += 1  #take discrepancy between list indexes and whatever into account
    repeat = 0
    while damage > 0:
        shiplost = weighted_choice(reference, highest)
        if shiplost is None:  #fleet got decimated
            return lost
        if damage < shipinfo[shiplost]['damage'] and repeat < 20:
            repeat += 1
        elif repeat >= 20:
            break
        else:
            repeat = 0
            reference.__dict__[shiplost] -= 1
            lost.__dict__[shiplost] += 1
            damage -= shipinfo[shiplost]['damage']
    return lost
Esempio n. 13
0
def policies_military(request):

    # variable setup, stuff needed to process POST data
    world = request.user.world
    result = indefwar = rumsodmsg = None
    shipdata = v.shipcosts(world.sector)
    rebelfuelcost = 0
    if request.method == 'POST':
        form = request.POST
        actions = False  #if the n***a wants to build ships
        if 'build' in form:
            shiptype = form['build']
            form = shipbuildform(world, data={shiptype: form[shiptype]})
            if form.is_valid():
                amount = form.cleaned_data[shiptype]
                ship = (shiptype if amount > 1 else shiptype[:-1]
                        )  #shipname, if >1 then plural
                if amount == 0:
                    result = "Can't build 0 %s!" % ship.replace('_', ' ')
                else:
                    #make sure he can (or she) can afford it
                    results = utilities.costcheck(world, form.cleaned_data)
                    if results['status'] is True:  #player can afford it
                        actions = {
                            'budget': {
                                'action': 'subtract',
                                'amount': D(results['cost']['geu'])
                            },
                            'duranium': {
                                'action': 'subtract',
                                'amount': results['cost']['duranium']
                            },
                            'tritanium': {
                                'action': 'subtract',
                                'amount': results['cost']['tritanium']
                            },
                            'adamantium': {
                                'action': 'subtract',
                                'amount': results['cost']['adamantium']
                            },
                            'productionpoints': {
                                'action': 'subtract',
                                'amount': results['cost']['productionpoints']
                            }
                        }
                        #queue merges with build fleet at turn change
                        queue = shipqueue(world=world,
                                          fleet=world.preferences.buildfleet)
                        queue.__dict__[shiptype] = amount
                        current_time = v.now()
                        if current_time.hour > 12:
                            hours = 24 - current_time.hour - 1
                            minutes = 60 - current_time.minute
                        else:
                            hours = 12 - current_time.hour - 1
                            minutes = 60 - current_time.minute
                        outcometime = current_time + time.timedelta(
                            hours=hours, minutes=minutes)
                        ship = ship.replace('_', ' ')
                        task = Task.objects.create(target=world,
                                                   content=taskdata.buildship(
                                                       ship, amount),
                                                   datetime=outcometime)
                        queue.task = task
                        queue.save()
                        result = "%s %s are building" % (amount, ship)
                    else:
                        result = "You can't afford to build %s %s!" % (
                            amount, ship.replace('_', ' '))

        if "research" in form:
            form = ResearchForm(request.POST)
            if form.is_valid():
                next_tier = v.tiers[v.tiers.index(world.techlevel) + 1]
                rdcost = shipdata[next_tier.replace(' ', '_').lower() +
                                  's']['research']
                durcost = rdcost['duranium']
                try:
                    tritcost = rdcost['tritanium']
                except:
                    tritcost = 0
                try:
                    adamcost = rdcost['adamantium']
                except:
                    adamcost = 0
                data = form.cleaned_data
                amount = data['researchamount']
                if amount < 0:
                    result = 'Enter a positive integer.'
                elif world.techlevel == "dreadnought":
                    result = 'You have researched all ship types already!'
                elif world.budget < amount:
                    result = outcomes.nomoney()
                elif durcost > world.duranium:
                    result = outcomes.research('NoDur')
                elif tritcost > world.tritanium:
                    result = outcomes.research('NoTrit')
                elif adamcost > world.adamantium:
                    result = outcomes.research('NoAdam')
                elif world.turnresearched:
                    result = outcomes.research('TooSoon')
                elif amount > 3 * world.gdp:
                    result = outcomes.research('TooMuch')
                else:
                    actions = {
                        'budget': {
                            'action': 'subtract',
                            'amount': amount
                        },
                        'duranium': {
                            'action': 'subtract',
                            'amount': durcost
                        },
                        'tritanium': {
                            'action': 'subtract',
                            'amount': tritcost
                        },
                        'adamantium': {
                            'action': 'subtract',
                            'amount': adamcost
                        },
                        'turnresearched': {
                            'action': 'set',
                            'amount': True
                        },
                        'budget': {
                            'action': 'subtract',
                            'amount': amount
                        },
                    }
                    if world.sector == 'draco':
                        amount = int(amount * 1.25)
                    message = outcomes.researchtext(world, amount)
                    actions.update(
                        {'millevel': {
                            'action': 'add',
                            'amount': amount
                        }})
                    result = outcomes.research('Success', result=message)

        if "moveship" in form:
            form = fleetwarpform(world, request.POST)
            if form.is_valid(
            ):  #form checks practically everything but warpcost
                warpfleet = fleet.objects.get(pk=form.cleaned_data['fleet'])
                if warpfleet.enoughfuel():
                    tgtsector = form.cleaned_data['destination']
                    actions = {
                        'warpfuel': {
                            'action': 'subtract',
                            'amount': warpfleet.fuelcost()
                        }
                    }
                    taskcontent = taskdata.warpfleet(warpfleet.name,
                                                     warpfleet.sector,
                                                     tgtsector)
                    delay = (4 if tgtsector == warpfleet.sector else 8)
                    outcometime = v.now() + time.timedelta(minutes=2)
                    task = Task.objects.create(target=world,
                                               content=taskcontent,
                                               datetime=outcometime)
                    newtask.fleet_warp.apply_async(args=(warpfleet.pk,
                                                         warpfleet.name,
                                                         tgtsector, task.pk),
                                                   eta=outcometime)
                    result = "%s bugs out and is warping to %s" % (
                        warpfleet.name, tgtsector)
                    #actually altering data goes last
                    utilities.atomic_fleet(warpfleet.pk, ['warp'])
                else:
                    result = "Not enough warpfuel, %s needs %s more warpfuel to warp!" % \
                        (warpfleet.name, (warpfleet.fuelcost() - world.warpfuel))

        if "train" in form:
            form = trainfleetform(world, form)
            if form.is_valid():
                targetfleet = form.cleaned_data['fleet']
                if world.budget < targetfleet.trainingcost():
                    result = outcomes.nomoney()
                elif targetfleet.training >= targetfleet.maxtraining():
                    result = outcomes.training('AtMax')
                else:
                    actions = {
                        'budget': {
                            'action': 'subtract',
                            'amount': targetfleet.trainingcost()
                        },
                    }
                    utilities.atomic_fleet(targetfleet.pk, {'train': True})

        if "buildshipyard" in form:
            if world.budget < 500:
                result = outcomes.nomoney()
            elif world.duranium < 5:
                result = outcomes.notenoughduranium()
            else:
                actions = {
                    'budget': {
                        'action': 'subtract',
                        'amount': 500
                    },
                    'duranium': {
                        'action': 'subtract',
                        'amount': 1
                    },
                    'shipyards': {
                        'action': 'add',
                        'amount': 1
                    },
                }
                result = outcomes.shipyards('Success')

        if "attackrebels" in form:
            fleets = world.controlled_fleets.all()
            worldpower = utilities.militarypower(world, world.sector)
            fuelcost = int(0.1 * utilities.warpfuelcost(worldlist))
            if world.budget < 10:
                result = outcomes.nomoney()
            elif world.rebels == 0:
                result = outcomes.norebels()
            elif world.warpfuel < fuelcost:
                result = 'You do not have enough warpfuel to hunt down the rebels!'
            elif worldpower == 0:
                result = 'You do not have a fleet to attack the rebels with!'
            else:
                world.budget = F('budget') - 10
                world.warpfuel = F('warpfuel') - fuelcost

                totworldpower = utilities.powerallmodifiers(
                    world, world.sector)

                rebelpower = 0
                for f in fleets:
                    rebelpower += f.basepower()  # sum of total fleet power

                outcome = random.randint(1, 100)
                if (1 <= outcome < 5) or (30 < outcome <= 100):
                    if 1 <= world.rebels < 20:
                        rebelpower = 0.01 * rebelpower
                    elif 20 <= world.rebels < 40:
                        rebelpower = 0.02 * rebelpower
                    elif 40 <= world.rebels < 60:
                        rebelpower = 0.03 * rebelpower
                    elif 60 <= world.rebels < 80:
                        rebelpower = 0.04 * rebelpower
                    elif world.rebels >= 80:
                        rebelpower = 0.05 * rebelpower
                    dmg = utilities.war_result(rebelpower, totworldpower,
                                               worldpower)
                    utilities.warloss_byregion(world, world.sector, deflosses)

                if 30 < outcome <= 100:
                    utilities.rebelschange(world, -5)
                elif 1 <= outcome <= 5:
                    utilities.rebelschange(world, 5)

                utilities.wearinesschange(world, world.sector, -2)

                world.save(update_fields=['budget', 'warpfuel'])

                result = news.rebelresult(outcome, deflosses)

        if "rumsodmil" in form:
            targetname = form['targetname']
            try:
                target = World.objects.get(world_name=targetname)
            except ObjectDoesNotExist:
                result = 'There is no such world by that name!'
            else:
                if world.rumsoddium != 4:
                    result = 'You do not have enough rumsoddium for the ritual!'
                else:
                    target.gdp = F('gdp') - int(target.gdp / 2)
                    target.budget = F('budget') - D(target.budget / 2)
                    target.warpfuel = F('warpfuel') - int(target.warpfuel / 2)
                    target.duranium = F('duranium') - int(target.duranium / 2)
                    target.tritanium = F('tritanium') - int(
                        target.tritanium / 2)
                    target.adamantium = F('adamantium') - int(
                        target.adamantium / 2)
                    world.rumsoddium = 0
                    world.save(update_fields=['rumsoddium'])
                    target.save(update_fields=[
                        'gdp', 'budget', 'warpfuel', 'duranium', 'tritanium',
                        'adamantium'
                    ])
                    rumsodmsg = v.rumsodmilitary
                    htmldata = news.rumsodmilitaryreceive(world)
                    NewsItem.objects.create(target=target, content=htmldata)
                    utilities.rumsoddiumhandout()

        if "buildflagship" in form:
            form = PersonalShipForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                shiptype = data['shiptype']
                if world.flagshiptype != 0:
                    result = outcomes.personalship('Already')
                elif shiptype not in [1, 2, 3]:
                    result = 'Invalid shiptype selected!'
                elif world.budget < 500:
                    result = outcomes.nomoney()
                elif (world.shipyards - world.shipyardsinuse) < 5:
                    result = outcomes.notenoughshipyards()
                elif world.duranium < 20:
                    result = outcomes.notenoughduranium()
                else:
                    current_time = v.now()
                    if current_time.hour > 12:
                        hours = 24 - current_time.hour - 1
                        minutes = 60 - current_time.minute
                    else:
                        hours = 12 - current_time - 1
                        minutes = 60 - current_time.minute
                    outcometime = v.now() + time.timedelta(hours=hours,
                                                           minutes=minutes)
                    world.budget = F('budget') - D(500)
                    world.duranium = F('duranium') - 20
                    world.productionpoints = F('shipyardsinuse') + 25
                    world.flagshipbuild = True
                    world.save(update_fields=[
                        'budget', 'duranium', 'productionpoints',
                        'flagshipbuild'
                    ])
                    taskdetails = taskdata.buildpersonalship(shiptype)
                    task = Task(target=world,
                                content=taskdetails,
                                datetime=outcometime)
                    task.save()

                    newtask.buildpersonalship.apply_async(args=(world.pk,
                                                                task.pk,
                                                                shiptype),
                                                          eta=outcometime)
                    result = outcomes.personalship('Success', shiptype)

        if "scuttleflagship" in form:
            if world.flagshiptype == 0:
                result = 'You do not have a flagship to scuttle!'
            else:
                utilities.flagshipreset(world)
                result = 'You scuttled your flagship.'

        elif "setfleetprefs" in form:
            form = buildlocationform(world, request.POST)
            if form.is_valid():
                prefs = world.preferences
                prefs.buildfleet = form.cleaned_data['buildchoice']
                prefs.recievefleet = form.cleaned_data['recievechoice']
                prefs.save()
                result = "Fleet preferences successfully updated"

        if actions:
            utilities.atomic_world(world.pk, actions)
            world.refresh_from_db()
    if world.wardefender.count() > 0:
        indefwar = True
    #create context dictionary with needed variables instead of fuckhuge return dict
    costs = []
    ids = []
    for f in world.fleets.all().filter(sector=world.sector):
        costs.append(f.trainingcost())
        ids.append(f.pk)

    context = {
        'costs':
        costs,
        'ids':
        ids,
        'result':
        result,
        'researchform':
        ResearchForm(),
        'buildtoform':
        buildlocationform(world,
                          initial={
                              'buildchoice': world.preferences.buildfleet.pk,
                              'recievechoice':
                              world.preferences.recievefleet.pk
                          }),
        'moveform':
        fleetwarpform(world),
        'prefs':
        world.shipsortprefs,
        'buildlist':
        display.milpolicydisplay(world),
        'rumpolicy': (True if world.rumsoddium == 4 else None),
        'rumsodmsg':
        rumsodmsg,
        'indefwar': (True if world.wardefender.count() > 0 else False),
        'rebelfuelcost':
        rebelfuelcost,
        'displayresearch':
        (True if v.tiers.index(world.techlevel) is len(v.tiers) else False),
        'result':
        result,
        'rumsodmsg':
        rumsodmsg,
        'world':
        world,
        'trainform':
        trainfleetform(world),
    }
    if world.techlevel != "Dreadnought":
        next_tier = v.tiers[v.tiers.index(world.techlevel) + 1]
        rdcost = shipdata[next_tier.replace(' ', '_').lower() +
                          's']['research']
        context.update({'costmsg': rdcost, 'shiptext': next_tier})

    return render(request, 'policies_military.html', context)