#๐Ÿ”’ Making a program to calculate resources required (for a game), cant get a specific function to wor

118 messages ยท Page 1 of 1 (latest)

blissful jetty
#

Here is the dictionary i created to utilise for the mod, this has no issues;

obtuse jettyBOT
#

@blissful jetty

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

blissful jetty
obtuse jettyBOT
blissful jetty
obtuse jettyBOT
blissful jetty
#

The problem i have is with the sunlight modifier.

#

The Energy Cells module - base production of 31500

Then this code:
def get_adjusted_energy_cell_production(sunlight_percentage):
"""Calculate adjusted Energy Cell production based on sunlight multiplier."""
if not 0 <= sunlight_percentage <= 400:
raise ValueError("Sunlight percentage must be between 0 and 400.")
sunlight_factor = sunlight_percentage / 100
return modules["Energy Cells"]["produced"] * sunlight_factor

It supposed to multiply it based on the sunlight available.
100% is default so represents 31500

#

--
The program essentially creates a supply chain - then displays how many of each module is required to supply X amount of the user selected module

#

In this case - this is what i mean

#

At 100% Sunlight - it would require 10 energy cell modules - this works fine

#

If i set it to 50% sunlight - it should require 20 - as the amount of modules producing energy cells would need to be doubled

#

This also works fine.

#

However - the issue im having is when i try to use values above 100% sunlight, it doesnt seem to give the correct, intended result:

#

in that example, it returned 9^ instead of the expected 5.

lethal oracle
#

@blissful jetty can u dumb it down this is like a whole essay at this point haha

blissful jetty
#

Working on it

#

About to show only relevant info

#

Create an entry field for sunlight percentage (defaulted to 100)

sunlight_label = tk.Label(frame, text="Sunlight Percentage:", fg="#FFFFFF", bg="#333333", font=('Arial', 12))
sunlight_label.grid(row=4, column=0, padx=10, pady=10)
sunlight_entry = tk.Entry(frame, font=('Arial', 12), bg="#4C4C4C", fg="white")
sunlight_entry.insert(0, "100") # Default value is 100
sunlight_entry.grid(row=4, column=1, padx=10, pady=10)

^^This handles the textbox for the percentage, defaults to 100% and works fine, as far as i can tell

#

Function to calculate the adjusted Energy Cell production

def get_adjusted_energy_cell_production(sunlight_percentage):
"""Calculate adjusted Energy Cell production based on sunlight multiplier."""
if not 0 <= sunlight_percentage <= 400:
raise ValueError("Sunlight percentage must be between 0 and 400.")
sunlight_factor = sunlight_percentage / 100
return modules["Energy Cells"]["produced"] * sunlight_factor

^^ This SHOULD be responsible for directly handling the multiplier applied to the production

lethal oracle
#

seems like u already know what ur doing

#

so what exactly is the problem here

blissful jetty
#

But the core of it is all in here:

Recursive function to process required modules

def process_requirements(module_name, qty):
module_data = modules[module_name]

# Process the needed modules and raw resources
for product, amount in module_data["needed"].items():
    if product in modules:
        # If the product is a module, calculate how many modules are needed
        produced_qty = modules[product]["produced"] if product != "Energy Cells" else 31500 
        
        if product == "Energy Cells":
            # Apply sunlight adjustment multiplier only to Energy Cells
            sunlight_percentage = float(sunlight_entry.get())  # Get the sunlight percentage
            adjusted_qty = math.ceil((amount * qty) / produced_qty) * (100 / sunlight_percentage)  # Adjust by sunlight factor
            
            # Calculate required Energy Cells after adjusting for sunlight percentage
            required_modules[product] = required_modules.get(product, 0) + math.ceil(adjusted_qty)
#

Do not recurse for Energy Cells since it's the final energy source.

        else:
            # For other modules, calculate as usual without sunlight adjustment
            required_modules[product] = required_modules.get(product, 0) + math.ceil((amount * qty) / produced_qty)
        
        # Recurse into the product's requirements for non-Energy Cells
        if product != "Energy Cells":
            process_requirements(product, math.ceil((amount * qty) / produced_qty))
        
    else:
        # If the product is a raw resource, add it directly
        required_resources[product] = required_resources.get(product, 0) + (amount * qty)

# Now check for raw resources that the module itself produces
for raw_resource in module_data["raw_resources"]:
    for resource, amount in raw_resource.items():
        
        # Only treat as raw if it's truly raw (doesn't have a "needed" field)
        if resource not in modules or "needed" not in modules[resource]:
            required_resources[resource] = required_resources.get(resource, 0) + (amount * qty)
lethal oracle
#

do u not know how to write the function

blissful jetty
lethal oracle
#

the logoc

#

logic

blissful jetty
#

The issue is

lethal oracle
#

or

blissful jetty
#

the rest works

lethal oracle
#

is it a bug

blissful jetty
#

i BELIEVE it boils down to this line

#

adjusted_qty = math.ceil((amount * qty) / produced_qty) * (100 / sunlight_percentage) # Adjust by sunlight factor

lethal oracle
#

do you have an error?

blissful jetty
#

Not error - but unexpected result

lethal oracle
#

how so

blissful jetty
#

Base value
100% sunlight

gives expected result

#

50% sunlight

#

gives expected result

#

at 200% sunlight - doesnt give expected result, at all

#

if i change (100 / sunlight_percentage)
to (sunlight_percentage / 100)

#

I have the same problem - in reverse

#

And i dont see an easy way to find the middle ground without rewriting half of what ive done

#

Came here to see if i forgot something obvious

#

essentially comes down to - im not the best at math

lethal oracle
#

okay so

#

what is each parameter

blissful jetty
#

that pertains to what im trying to do;

sunlight_percentage = value that will act as a multiplier to the production of energy cells in my initial dictionary

module_name = dictionary entry pulled from

product = the product each dictionary entry creates (in this case, Energy Cells)

adjusted_qty = adjusted requirement of energy cells

produced_qty = amount produced by module in dictionary

qty = number of modules user wants to produce (in the test cases, was 6 by default)

amount = total number required to meet target needed in the chain (can be any resource)

#

The dictionary entry, relevant here is;
"Energy Cells": {
"produced": 31500,
"needed": {},
"raw_resources": [],
},

#

--
Here is a simple breakdown of what the program is MEANT to do, then what the problem is:

Program is meant to - Receive User input of module they want and how many of them.
Program then calculates based on resource requirement of that module - and the production of modules that produce what it needs to develop a supply chain - to figure out how many of each is needed to sustain what the user wants.

It all works fine.

#

Eg - to make 1 Medical Supply Module, it needed 6 energy cells, 1 spice, 3 water, 1 agri goods module

#

The issue comes around when scaling for sunlight percentage - Which only impacts energy cells

#

at 50% - production per module should halve, meaning twice the modules are needed

#

However - at 200% - it should need half the modules total, but it's this which doesnt work;

#

Relevant calculations are here:
the highlighted line is what handles most of it.

#

In that line, the parameters are as follows:

amount = amount of resources needed (eg, amount of energy cells needed for production)

qty = quantity of target modules

produced quantity: amount produced per module (by default, is 31500 in the test case, for energy cells)

sunlight_percentage (the multiplier to scale by)

lethal oracle
#

okay so

blissful jetty
#

Hopefully that helps you understand my issue

lethal oracle
#

lets take out sunlight percentage

#

thats just multiplications

#

outside of that, what is the behavior that you want for those paramters

blissful jetty
#

Well, my perception of what ive gone for here is that its either the math wrong, or it's something wrong with how im handling the produced_qty parameter

lethal oracle
#

okay so lets first know the issue then haha

blissful jetty
#

Because with default values from the energy cell module, the line essentially translates to this:

total = math.ceil((resources needed * target module count) / 31500) * ( 100/ 200)

lethal oracle
#

btw idk why u use the math library seems kinda chatgpt ngl

blissful jetty
#

Most of the information required is pulled directly from user input, or from the dictionary at the top

lethal oracle
#

us normal people just do int(x) + 1

blissful jetty
#

ive only been at my college for a few months now so im still very new

lethal oracle
#

how do u know if its ur input or ur math

blissful jetty
#

I believe it's the math

#

because i can reverse the issue by reversing the equation

#

give me a sec i got an idea

lethal oracle
#

okay so ur doing resources needed * target module

#

what r we doing there

blissful jetty
#

let me run a test case which doesnt include a lot of modules so i can give a proper breakdown

#

give me a sec

dusky kernel
blissful jetty
#

Okay - this module has two inputs, energy and raw resources

This works fine

In the equation, it's essentially doing this:
total = math.ceil((resources needed * target module count) / 31500) * ( 100/ 200)
total = math.ceil(( (6480 x 15) / 31500) * ( 100/ 100)

#

which comes to 3.086 - but for this scenario it HAS to round up, so the answer of 4 required is correct

lethal oracle
blissful jetty
#

No - thats a working case at 100%

lethal oracle
#

i think ur problen is that ur coding for 5 hours or so ngl

blissful jetty
#

The problem is when i try to scale sunlight up

#

okay wait wtf

#

for this one it works fine

#

naw this means ive gone wrong somewhere else

#

somewhere in the recursion for doing longer chains

lethal oracle
#

okay how long have u beeen coding

mild verge
#

Might want to consider writing some tests so you can automate checking these things

blissful jetty
#

its 1am lol

#

i will run an intermediary test case

lethal oracle
#

@blissful jetty ok lol go to sleep

blissful jetty
#

Okay yes

#

its a recursion issue

lethal oracle
#

ngl this is the most relatable shit ive ever had

blissful jetty
#

doesnt work on modules with more than a single preceeding module in its chain

#

eg if it goes from

raw - product
yay working

raw - product 1 - product 2
bad no worky

lethal oracle
#

ok but

#

r u rll coding still

#

or r u moving shit around and hoping it works

blissful jetty
#

trying to move stuff around to avoid rewriting

lethal oracle
#

so go to sleep haha

blissful jetty
#

but i think i need to rewrite the section where i handle moving from one part of the chain to the next

lethal oracle
#

trust me ur gonna wake up and the first thing tmrw u likely already know the solution

blissful jetty
#

i will try for a lil bit longer, i think i know where im focusing

#

i will lock this chat

#

ty

obtuse jettyBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.