I'm trying to create a menu system that allows you to go backward and forward while returning the final selected data to the calling method.
Take for example a orderFood() method displays a menu of choices of types of food that can be ordered. If someone selects seafood a seafood() method would run and query what types of seafood is availble to order then display it
if the user selects fishsticks, fishsticks would be returned to the method that called order food. Likewise, this menu system would allow the user to go back to the previous menu.
I'm thinking (Using C#) I'd have to use reflection and unsafe code (pointers) to get this sort of effect but I am positive that there is a simpler way to do this. Any suggestions?
Thanks,
Michael
Instead of thinking about the menus as a stack, try thinking of them like a tree.
If you do this, it should be fairly easy to "walk" up and down the tree as you need to implement your stack approach.
This would be fairly easy to read from a file or database (very easy from XML, in particular), and also shouldn't be too tough to walk up and down.
There isn't really anything in this that should require unsafe code or reflection - it can all be done with standard collections in C#.
You could easily do what you are describing without unsafe code provided you know at compile time, by making it data driven. Instead of thinking of menus as routines that do these things, think of menus as a class of objects that does these things. Ommm.
Even if you don't know everything at compile time (say you need to read the options from a file) you could still do it by building the nest of objects which represent your menus at run time, based on the contents of the file.
Related
So, I'm making myself a small C# library for dialogues to use in an cRPG game.
The idea is, that the Dialogue object and it's fields (like DialogueNode and DialogueOption objects) are created based on an XML file, which I aim to make as simple as possible. The fields, except for lists or objects of types contained within the library, are - at best - string identifiers, to be acquired and parsed by outside means when needed.
I've basic funcionality implemented - XML serialization, running through the dialogue and exiting it - as well as basic, console based application interpreter and a WPF editor to create the dialogues, because writing the dialogue in plain XML is not the most comfortable thing in the world. (the last two are meant to be as much independent from the library as possible, except maybe for implementing what's inside to show/create)
All that being said, I've encountered a problem (actually two, the other one I'll cover in different question when I've the time after my exams).
After giving it some of my unexperienced 'noobish' thought, I've come to think, that I'd like to have some basic predicates stored either in my nodes or options - they would be later checked in game to determine, whether to display the node/option or leave it be (or whatever meddling with those to be honest). For example - an option is displayed if the player character have item X in his inventory, or the node is displayed when player has a certain minimum value of an attribute.
My idea of implementing is so far like that:
Having a field PredicateScript in an object
Having a bool method, that would be executed in runtime by the interpreter like this:
public bool DisplayPredicate(string predicateCode)
{
bool result = FunctionExecutingCSharpCode(predicateCode);
return result;
}
I've read some topics about compiling on the fly very brielfy, but I'm not sure if it's exactly what I want - I'm not sure how it would affect the performance of application (either the interpreter or the game itself), if it would be recompiled every few seconds...
I'm not pasting any code of what I'm trying to do, because either I'm yet to do this (as I'm not writing the code I'm not sure it will work) or it's the library structure which I don't think would be of relevance aside from what I explained I aim to do. ^^
Thanks. ^^
Given the standard .NET framework, there's no such thing as a C# "interpreter" you can feed code that gets executed. You could try to dynamically create C# code and have that compiled on the fly into an in-memory assembly, which you can then use using the .NET compiler services.
And example of this is given here: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime.
I have been working on a project where I need to interface and show a hierarchy from a big database (~100.000 folders, even more files), but it takes 5 minutes to be able to load the data from the database to the project, and I want to reduce it.
My implementation used a tree to represent this data (because it made sense at the beginning), using recursion to navigate down the tree to place new folders and items (which right now are not being used, since I tried to add them but it took so long to populate the tree I just removed them). Are there better structures to hold such hierarchy? Otherwise, is there a better way to transverse the tree (since it seems that most of the time is spent climbing down and up the tree, due to recursion and the fact the database is rather deep)?
I am using C#, but I believe an agnostic answer would be good enough.
You don't need to load everything because you can not see them all in your monitor anyway, you can use:
Lazy loading, load only if user want to, for example if user double click a certain folder
Using Virtualization User Interface or showing only the visible folder
For user interface virtualization example you can read an watch the Video:
Code Canvas
I have a little visual system for generation FSM's where the user can draw a graph using boxes (states) and link them with lines (transitions). This, in the end, generates c# code when user presses the "Generate code" button that defines the FSM in runtime.
I want my users to be able to change things like graph name, transitions names, states names, delete nodes, delete transitions and a bit more after the first save, so, I need a way to handle refactoring.
I'm struggling trying to find a non intrusive way to accomplish this. Have tried to apply a modification of a do/redo algorithm I made some time ago but couldn't be able to get something nice.
Could anyone explain how to create such a system, making it as less intrussive with existent code as possible?
Cheers.
I would suggest keeping the state in your graph datastructure, and generating the C# code anew on changes to the FSM, this is a simple solution that will allow arbitrary modification of the FSM-datastructure without having to worry about applying said modifications to the generated code.
For implementing 'refactorings' of the base FSM-data structure, you could use something like a Command Pattern to encapsulate the refactorings and undo/redo operations.
I have "successfully" implemented a non recombining trinomial tree to price certain fixed-income derivatives. (Something like shown in the picture below - but with three branches that don't reconnect)
Unfortunately it turned out that the number of nodes I can use was severely limited by the available memory. If I build a tree with 20 time-steps this results in 3^19 nodes (so 1,1 Billion nodes)
The nodes of each time step are saved in List<Node> and these arrays are stored in a Dictionary<double,List<Node>>
Each node is instantiated via new Node(...). I also instantiate each of the lists and the dictionary via new Class() Perhaps this is the source of my error.
Also System.OutOfMemoryException isn't thrown because of the Dictionary/List-Object being to large (as is often the case) but because I seem to have too many Nodes - after a while new Node(...) can't allocate any further memory. Eventually the 2GB max List-Capacity will also kick in I think - seeing as how List grows exponentially larger with each time step.
Perhaps my data-structure is too wasteful or not really suited for the task at hand.
A possible solution could be to save the tree to a text-file thus avoiding the memory-problem completely. This however would necessitate a HUGE workaround.
Edit:
To add some more background. I need the tree to price path dependant products. This means that unfortunately I will have to access all the nodes. What is more after the tree has been build I start from the leaves and go backwards in time to determine the price. I also already only generate the nodes I need.
Edit2:
I have given the topic some though and also considered the various responses. Could it be that I just need to serialize the respective tree levels to the hard-drive. So basically - I create one time-step (List<Node>) write it to Disk etc. Later on when I start from the leaves - I will just have to load it in reverse oder.
You basically have two choices. evaluate only the branches you care about (Andrew's yield) and don't store results or build up your tree and save it to disk and implement a custom collection interface on top of it that accesses the right part of the disk. In this case you are still going to keep a minimal amount of data in your process memory and rely on the OS to do proper disk caching to make access fast. If you start working with large data sets the second option is a good tool to have in your tool belt, so you should probably write this with reuse in mind.
What we have here is a classic problem of doing an enormous amount of processing up front... and then storing EVERYTHING into memory to be processed at a later time.
While simple, given harsh enough conditions (like having a billion entries), it will eat up all the memory.
Now, the OP didn't really specify what the intention of the tree was or how it was going to be used... but I would propose that instead of building it all at once... build it as you need it.
Lazy Evaluation with yield
Instead of doing everything all at once and having to store it... it might be ideal to do it ONLY when you actually require it. Check out this post for more info and examples of using yield.
This won't work great though if you need to traverese the tree a bunch of times... but it might still allow you to have deeper depth than you currently do.
I don't think Serializing to disk will help much. One, when you attempt to deserialize the list you will still run out of memory (as, to the best of my knowledge, there is no way to partially deserialize an object).
Have you considered changing your data structure into a relational database model and storing it in a SQLEXPRESS database?
This would give you the added benefit of performing queries with indexes instead of your custom tree traversal logic.
In my application we have multi-lingual language strings which are stored in custom tables, as the user can edit, delete, import new languages etc... via a UI
Currently, what I'm doing is at the beginning of each request is. I'm going off and getting all the language strings (From our database) for the currently selected language and sticking them in a dictionary.
I then have a Html Helper extension method which I use in the razor views (See below), which fishes in the dictionary I got at the beginning of the request to pull out the correct language based on the key supplied in the helper.
Html.LanguageString("MyLanguage.KeyHere")
Now this works fine. However, as the application is getting bigger. We are getting more and more language strings. It's not an issue right now, as its still very fast as there are only around 200 strings to get.
But this also means I'm getting all of them, even if a page has say one on it. I'd ideally like a way of processing the LanguageString("")'s before hand and doing a query to just get those that are needed at the beginning of the request? Or maybe my own linq based language that can be processed and product a more efficient call.
I'm looking for some advice on how to do this. As I'd like the application to be as efficient as possible. Any advice, help, tips are greatly received. Thanks.
I'd suggest caching language strings on the application basis rather than fetching them for every request. For example, this can be done by maintaining a static dictionary and invalidating the cache only when the user makes changes to these strings. This will make your application more responsive as well as save you from implementing (imho) rather more complex and not necessarily efficient technique of loading this data on-demand.
As a side note I'd add the following: it's usually a good practice to address these kinds of problems when they arise (rather than fixing something that is not broken) and focus on more important things. I totally agree that performance implications of a given solution must always be taken into consideration, I'm just saying that premature optimizations are not always a good idea.