I'm new to coding. I have some experience years ago with other languages, but I'm essentially starting fresh with C#. I'm trying to make a series of logic-driven random generators that will help me with my writing. The part about it being logic-driven is the kick in the pants. I've got an HTML/Javascript version working but I want to do it in C# and I'm stuck.
Essentially, the generator will randomly generate the first trait of whatever it is that I'm making. For example, maybe I'm running my random creature generator and the "Creature Type" is "Avian" (Birdlike). Based on THAT result, other features and traits would randomly generate. For example, it wouldn't say that the skin type is "membrane" for an Avian creature. If the creature has pointed teeth, it wouldn't show up with a diet of "vegetarian".
I was able to make a very basic random generator, however, I'm not sure this is the best way to go about it. Should I make this a List? An Array? Something else? Everything that I've searched online is explaining how to build a random number generator, which isn't what I need, or it's a simple list with no dependency logic built in. Aside from having an idea of what it should do, I don't know enough C# to get it. I'm not even sure I'm searching google with the right terms.
Thanks in advance.
All right, let's go step-by-step.
Based on THAT result, other features and traits would randomly generate.
OK, so you need a function: ISet<T> Choices(T instance); responsible for providing a set (i.e. list with no duplicated elements and internal implementation optimised for checks like bool Contains(T instance)) of next possible options. The options provided must take into consideration the essence of given T instance and provide only valid options such that predator won't be a vegetarian.
Then you need T AnyOf(IEnumerable<T> options) function that randonly picks up any element contained within a given IEnumerable<T>. Obviously, it gonna model non-determenism.
Eventually, you have to match those such that they form a chain T Generate() that is self-sufficient to make a fresh valid instance.
Please note, generally you'll deal with different T's. There is no implicit assumption that all of them are interrelated. It's up to you to model your instances richly enough to be able to apply the sketch I drew above.
Good luck.
Related
I'm making a little game in unity and right now I'm trying to build the quest system.
This game is going to be a simulation, so there's a huge amount of different data classes / systems the quests are going to have to interact with.
I can just make a bunch of utility classes... or even make a fake "database" to handle data calls... but that's inelegant.
Surely there's gotta be a way where I can just denote actual code from a string?
Example:
String questText = Hello player.getFullName();, how are you?
questResults<String>[1] = player.inventory.add(GameObjectBuilder.Create(new WhateverObject()));
I am using Unity's ScriptableObject to make quests, so that I can fill in text data via the editor rather than do it on IDE side (especially since unity doesn't support interpolated & composite strings as far as I know).
I know Java has an API called "Reflection" which from what I understand does something like this, but I was never able to fully wrap my head around it.
So how do I convert elements from a string into runnable code?
If that is possible, will that cause preformance issues with an indefinate amount of objects that might be encountering scripts that need to be converted?
Are there any other alternative methods that achieve a similar goal? (this one is just a curiosity)
As an alternative method, you can use a keyword that you search for and replace, rather than write the actual code directly into your string. I would suggest using this approach as it's cleaner to read and easier to maintain. I have used this approach in a similar system.
It works well if there is only a small number of possibilities that you will need to resolve (or you don't mind adding 'handlers' for all keywords., you can include a sort of keyword in your text, that you can pass through a method before using it.
For example..
Hello {PLAYER_NAME}, how are you? - this is the raw string.
public string ParseQuestText(string input)
{
if(input.contains("{PLAYER_NAME}")
input.Replace("{PLAYER_NAME}",player.getFullName());
/Add other replacers here
return input;
}
Need assistance in structuring my code with design patterns.
So I have a single method in service class that looks like this. The constructor loads a json file into a List<Option> of Option class instances. Finally when the service method is called it does some logic to find the Option match based on the parameter values and returns a new instance of 'Tool' class with the configured "options".
public Tool BestOptionFinderService.FindBestMatch(string value 1, int value2, int value3, .. bool value20, etc...) {..}
I'm not sure if I a "service" class is correct for this versus a "factory" or something else. I would appreciate your thoughts and suggestions on how you would design your code for this problem or similar.
I would say, having single method with ~20 params is awful by itself, without even considering OOP patterns. Let's try to do better; more than that, let's try not to reinvent the wheel.
Important yet obvious observation: whatever matching logic one has, any object either matches or nor, and never both. Thus it makes sense to stick with Boolean algebra and signatures like predicate: t -> bool or bool Predicate<T>(T obj). The other thing we know about predicates, is that one can easily reduce arbitrary two into a single one: there are different ways to do it, however you're obviously interested in the and or && operator.
Thus, instead of having 20 parameters, you could have had twenty different simple, clear, self-describing predicates, later on "reduced" into a single instance. Linq.Aggregate() could help you out to not only beautify your code, but make it parallel (if necessary) as well. Then you could map your input to an sufficient (it's up to you to decide whether you do need more, or don't) number of flags, representing a "fitness" of a particular object you're examining.
Such an approach would indeed be better because:
1) You stick to well-known Boolean algebra,
1.A) which, actually, forms a monoid under various operation, including and, which, in turn, makes it
1.B) easily distributable over any computation cluster
1.C) compact, expressive, self-explanatory.
2) Your code tells much more story: simple predicates are easy to read, maintain, unit-test and refactor, which is never the case for 20-params methods.
3) You clearly separate your primitives from a compositions - more complex structures, built up from somewhat known primitives. That's the way math goes and thus the only known reliable, proven by thousands of years way to tackle down the complexity and not get enslaved by it at some point.
4) There are more advantages, but I tired to type ;)
So I may have coded myself into a corner, and I want to know the best way out.
I have this document editor I'm writing, and one property of the documents being edited is a list of structures. The document is stored as XML, so each of these structures is an XML node and its properties. My Document class exposes these structures as an IEnumerable.
In my editor, I want to literally highlight these structures when the mouse is nearby. I've already done the task of identifying one close to the cursor. But now I have to be able to refer to that instance of the structure, and store that somewhere. Finding the closest one just iterates through the IEnumerable, and returns the structure itself. I suppose that I could use the structure itself as the reference, but then I'm going to wind up saying in my display code if (thing == nearestThing) and it's going to do a hash code comparison or something, right?
That feels like the wrong way to do it, but I don't have a proper ID for these structures either. Suggestions?
There is no problem with that way. Keep in mind though, you should make sure that == (and to a greater extend, Equals and GetHashcode) reliably produce the same results for the same inputs.
I have a couple of generic lists with completely different types of data.
In my generic lists I have created methods to do all the processing that makes sense from that level - that is I have the member function perform a summary and return a value or set of values. One of my reasoning for basing this calculation in the generic list is that it made reading the code in my opinion easier to read and maintain...but that’s subjective I guess.
Anyways I am at a point that some of the data in list_A needs to be shared with the List in List_B and vice-versa and I am stuck as to what would be the proper way to do this. My first consideration was to give List_B the location of List_A and so on.
or...is there something that I have totally missed is there some pattern that I should be using.
Thanks for any direction you can provide.
EDIT: Perhaps a few more words.
concider that List_A is a list of time collections for various equipment, the list would contain values for events during the day like : amount of time producing (ProductionTime) product 'X' or amount of time that equip was down for an unscheduled event like a breakage or the amount of time that fred the operator spent in the washroom and so on.
Now concider that List_B was a container for a history of equipment components that had been repaired.
In industry there are standard performance indicators like the mean time between failure(MTBF) and so on.
Anyways the definition for MTBF is ProductionTime / Sum of failures.
so...List_B is tasked with determing MTBF for equip_x and in order to do so it needs some information from List_A.
I have housed the calculation for MTBF as a member function in List_B but it still needs som info from List_A...
List_B is tasked with determing MTBF for equip_x
And that is where you start to go wrong I think. List_B should be doing List things, ie storing stuff and producing it when asked.
Calculations should be done in another part of your code (another layer). And then it is just a matter of creating the appropriate Join between List_A and List_B.
Single Responsibility, Coherency and all that.
It sounds like you're looking for something like the "friend" keyword in C++. That is, you'd like one type to be able to access the protected and private members of another type. There's no easy way to do this in C# because the "friend" keyword does not exist. See this related question for more details:
Why does C# not provide the C++ style 'friend' keyword?
Without the "friend" keyword, I think your best option is to define an Interface that provides the functionality you want each type to have and let each define that Interface.
I'm a web developer with no formal computing background behind me, I've been writing code now some years now, but every time I need to create a new class / function / variable, I spend about two minutes just deciding on a name and then how to type it.
For instance, if I write a function to sum up a bunch of numbers. Should I call it
Sum()
GetSum()
getSum()
get_sum()
AddNumbersReturnTotal()
I know there is a right way to do this, and a link to a good definitive source is all I ask :D
Closed as a duplicate of c# Coding standard / Best practices
You're looking for StyleCop.
Classes should be in camel notation with the first letter capitalized
public class MyClass
Functions and Methods in C# should act in a similar fashion except for private methods
public void MyMethod()
private void myPrivateMethod()
Variables I tend to do a little differently:
Member Variables
private int _count;
Local variables
int count;
I agree on the calculate vs get distinction: get() should be used for values that are already calculated or otherwise trivial to retrieve.
Additionally, I would suggest in many cases adding a noun to the name, so that it's obvious exactly what sum you are calculating. Unless, of course, the noun you would add is the class name or type itself.
All of the above.
I believe the official C# guidelines would say call it calculateSum() as getSum() would be used if the sum was an instance variable. But it depends on the coding style used and how any existing code in the project is written.
Luckily enough I don't believe there is a standardized way this is done. I pick the one that I like, which consequently also seems to be the standard all other source code I've seen uses, and run with it.
Sum() if it's public and does the work itself.
GetSum() if it's public and it retrieves the information from somewhere else.
sum() / getSum() as above, but for internal/private methods.
(Hmm... That's a bit vague, since you shift the meaning of "Sum" there slightly. So, let try this again.
XXX if xxx is a process (summing values).
GetXXX if xxx is a thing. (the sum of the values)
Method names are verbs. Class, field and property names are nouns. In this case, Sum could pass as either a verb or a noun...
AddNumbersReturnTotal fits the above definition, but it's a little long. Out of kindness to the guy who gets to maintain my code (usually me!) I try and avoid including redundant words in identifiers, and I try to avoid words that are easy to make typos on.