I'm new to programming and have therefore a rather simple question.
I guess it should be possible to show two different pictures 50 times. Let’s say two different colored circles, in an random order for a second or until the user presses a certain key, but I have no idea how to start. Is there an easy way?
Maybe it's easier to start with a list of actions (either showing circle a or showing circle b) and randomly choosing one of it like the following modified code from a different question:
class Program
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
actions.Add(() => Program.circleA());
actions.Add(() => Program.circleB());
Random random = new Random();
int selectedAction = random.Next(0, actions.Count()); // What does this line do?
actions[selectedAction].Invoke(); // And this one?
}
Afterwards I have to define what Program.circleA and Program.circleB does, right?
Should I implement this in a loop? If yes, how do I specify that each circle has to be shown 50 times before the breakout criteria is met?
I've search the Internet for similar problems, but I couldn't find a solution or maybe just couldn't understand them, so that's why I'm asking you guys and girls :)
If I understood your question correctly, your question is basically "How can I call a random action/method?" and "Is my logic of doing that okay?".
Starting with the second one (because it's easier), the answer will be the same as the answer to this simple question: "Is it doing its job?". Meaning if your logic is behaving like you wanted to, the answer is yes. If it doesn't, then no.
With the first one... It's a bit trickier because you can have many different solutions. You can use Reflection, Action, Func, custom delegates ...
(IMHO) So the "easy" way (if you have sh.. ton of methods) would be to use reflection and custom attributes, like so:
public class RandomCircleMethodAttribute : Attribute
{
public RandomCircleMethodAttribute() : base() { }
}
And then assign this Attribute to methods you want to call. Then using reflection, just get MethodInfo pointing to these methods and call them like so:
public class RandomCircleMethods
{
[RandomCircleMethod]
public void circleA() { //.. your logic here
}
[RandomCircleMethod]
public void circleB() { //.. your logic here
}
// add as many as you want
}
Then inside your EntryPoint ( Main(string[] args) ) :
List<MethodInfo> methods = typeof(RandomCircleMethods).GetMethods().Where(method => Attribute.IsDefined(method, typeof(RandomCircleMethod))).ToList();
int selectedAction = new Random().Next(0, methods.Count);
methods[selectedAction].Invoke(new RandomCircleMethods(), null);
This way you don't have to create list of Action. But this is as good as your current way of making the job done.
I would stick to your current logic though, because it's less confusing than using reflection.
Related
Please help me with this question. I'm coding come ability system in Unity3D 2019.4.1 (if you might want to know) and have had created "Roller" class for some random numbers. There is
public static Func<Creature, int> OnNumberRolled;
in "Roller" class. Some of abilities in my game must know about these random numbers and when they are rolled, they invoke some mess.
Here is an ability class:
public class ListenerEffect : Effect
{
public int OnRolledOne(Creature creature)
{
...
}
public override void CastEffect(ITargetable caster, ITargetable target)
{
Creature localCasterCreature = caster as Creature;
Roller.OnNumberRolled += OnRolledOne(localTargetCreature);
}
}
At this moment
Roller.OnNumberRolled += OnRolledOne(localTargetCreature);
error occurs. It says that it can't convert "int" into "System.Func<Creature, int>". Both classes are using System. What should I do?
Just use the name of the function. Otherwise, you are calling the function and are using the returned value.
Roller.OnNumberRolled += OnRolledOne;
If you add several handlers, keep in mind that the return values will be lost (but the last one) on invocation as OnNumberRolled().
You might have the handlers to add their results to a list or something like that, but we would need more insight on your use cases to design a satisfactory solution.
You can also iterate on handlers like this:
var handlers = OnNumberRolled.GetInvocationList();
foreach (var handler in handlers)
{
// invoke and handle each handlers'result here
Debug.Log(handler());
}
I'm trying to wrap my head around different concepts in Csharp by trying different things. A create a generic function that takes in an action. The action has one input parameter and returns void. I create a simple action that is linked to a lambda function (returns void has one parameter x). I am able to run the action but when I pass the function to my generic function I am not sure how to add the input parameter. act("Some Int") doesn't work.
How do I pass in a value to an action?
public MainWindow()
{
InitializeComponent();
Action<int> myAction = (x) => Console.WriteLine(x);
myAction(13);
test(myAction);
}
private static void test<T>(Action<T> act)
{
act(); // How do i pass in an int Here?
}
Simply calling act("Some Int") as you have just required the Action act to be a genric function. Therefore you cannot specifically invoke it with one fixed variable type. You can solve your problem by modifying the test-method
private static void test<T>(Action<T> act, T value)
{
act(value); // How do i pass in an int Here?
}
...
test(myAction,integerValue);
Now you can call the Action with a given intvalue.
I can see what you are trying to do, and just wanted to throw this pattern up, since we often do this when we have to use closures and the parameters could be wildly different.
In those cases, rather than define an Action<T> which kind of ties you down from being able to use closures, you would just simply define your method as Action. So test would look like this:
private static void test(Action act)
{
act(); // yup, that's all there is to it!
}
So how would you pass in the parameter(s)? Simple: use closures. Like this:
public MainWindow()
{
InitializeComponent();
var x = 13; // this defined outside now...
Action myAction = () => Console.WriteLine(x); // you're basically using the closure here.
myAction();
test(myAction);
}
We often use this sort of approach when we're context switching (aka thread jumping), and need the thread continuation to pick up one or more variable values at the point it executes. That's just one example, there's quite a few other valid use cases as well.
Your experimental example, if I'm reading it correctly, could also qualify as a situation where closures could be a good fit.
this is the best way I can think of doing this. Could you give me so hints as to whether this is the correct way or if there is a more efficient way of doing it.
My situation is:
Each time the frame is Update()'ed (Like in XNA) I want to check if something has happened.. Like if the timer for that screen has been running for over 2000 milliseconds. But I only want it to fire once, not every time the frame is updated. This would cause a problem:
if(totalMilliseconds > 2000)
{
this.Fader.FadeIn();
}
So I came up with this method that I have implemented in the GameScreen class that looks like this:
public bool RunOnce(string Alias, bool IsTrue)
{
if (!this.Bools.ContainsKey(Alias))
this.Bools.Add(Alias, false);
if (IsTrue && !this.Bools[Alias])
{
this.Bools[Alias] = true;
return true;
}
else
return false;
}
This basically checks if the passed if statement boolean is true, if it is then it fires once and not again unless the Bool["Alias"] is set back to false. I use it like this:
if(this.RunOnce("fadeInStarted", totalMilliseconds > 2000))
{
this.Fader.FadeIn();
}
This will then only run one time and I think is quite easily readable code-wise.
The reason I have posted this is for two reasons.. Firstly because I wanted to show how I have overcome the problem as it may be of some help to others who had the same problem.. And secondly to see if I have missed an obvious way of doing this without creating a manual method for it, or if it could be done more efficiently.
Your method is interesting, I don't see a problem with it, you've essentially created a new programming construct.
I haven't encountered this situation a lot so what I have done in this situation is always start with the untidy approach:
bool _hasFadedIn = false;
.
if(totalMilliseconds > 2000 && !_hasFadedIn)
{
this.Fader.FadeIn();
_hasFadedIn = true;
}
And 90% of the time I leave it like that. I only change things if the class starts growing too big. What I would do then is this:
_faderControl.Update(totalMilliseconds);
Put the logic for fader control into a separate class, so:
class FaderControl
{
bool _hasFadedIn=false;
public void Update(int totalMilliseconds)
{
if (_hasFadedIn)
return;
if (totalMilliseconds <= 2000)
return;
this.Fader.FadeIn();
_hasFadedIn=true;
}
}
It can be modified to make it configurable, like reseting, setting "start", "end", fadein time, or also controlling fadeout too.
Here's how I would approach this problem.
These are your requirements:
You have arbitrary pieces of logic which you want to execute inside of your Update().
The logic in question has a predicate associated with it which determines whether the action is ready to execute.
The action should execute at most once.
The core concept here is "action with an associated predicate," so create a data structure which represents that concept:
public class ConditionalAction
{
public ConditionalAction(Action action, Func<Boolean> predicate)
{
this.Action = action;
this.Predicate = predicate;
}
public Action Action { get; private set; }
public Func<Boolean> Predicate { get; private set; }
}
So now, your example becomes
var action = new ConditionalAction(
() => this.Fader.FadeIn(),
() => totalMilliseconds > 2000);
In your Update() you need something that can execute these conditional actions:
public void Update(GameTime time)
{
// for each conditional action that hasn't run yet:
// check the action's predicate
// if true:
// execute action
// remove action from list of pending actions
}
Because their predicates are probably unrelated, actions don't necessarily run in order. So this isn't a simple queue of actions. It's a list of actions from which actions can be removed in arbitrary order.
I'm going to implement this as a linked list in order to demonstrate the concept, but that's probably not the best way to implement this in production code. Linked lists allocate memory on the managed heap, which is generally something to be avoided in XNA. However, coming up with a better data structure for this purpose is an exercise best left for another day.
private readonly LinkedList<ConditionalAction> pendingConditionalActions =
new LinkedList<ConditionalAction>();
public void Update(GameTime time)
{
for (var current = pendingConditionalActions.First; current != null; current = current.Next)
{
if (current.Value.Predicate())
{
current.Value.Action();
pendingConditionalActions.Remove(current);
}
}
}
public void RegisterConditionalAction(ConditionalAction action)
{
pendingConditionalActions.AddLast(action);
}
Registered actions will wait until their predicates become true, at which point they will be executed and removed from the list of pending actions, ensuring that they only run once.
I've got a class defined like this (relevant methods shown):
class ShaderProgram : IDisposable
{
private HashSet<Shader> _shaders = new HashSet<Shader>();
public void AttachShader(Shader shader)
{
GL.AttachShader(Handle, shader.Handle);
_shaders.Add(shader);
}
public void DetachShader(Shader shader)
{
GL.DetachShader(Handle, shader.Handle);
_shaders.Remove(shader);
}
}
Now I'm trying to figure out how to write the Dispose method, I thought I could do it like this:
public void Dispose()
{
foreach(var shader in _shaders)
DetachShader(shader);
GL.DeleteProgram(Handle);
}
But now I suspect that's unsafe because I'm iterating over a set and deleting from it at the same time... if it were a queue or stack Id just say "while not empty, pop one off and delete it", but since it's a HashSet... I'm not sure what the best approach is. How should I handle this?
Edit: The point is to avoid code duplication; I want to call ShaderProgram.DetachShader for each element. I know I can repeat the code inside that function and then clear the whole set at the end -- that's not what I want to do.
Occurs to me now, that I don't really have to empty the HashSet at all, do I? The ShaderProgram object is about to be destroyed anyway, all I need to do is clean up any unmanaged resources, and the C# GC can clean up the rest, right?
public void Dispose()
{
foreach (var shader in _shaders)
GL.DetachShader(Handle, shader.Handle);
GL.DeleteProgram(Handle);
}
That said, I still want answers to the original question. My goal here is not to solve a very simple problem, but to learn the best approach to this class of problem.
There's no problem in doing this, but maybe you should consider to iterate your set, detach your shader from your GL variable and then just clear your HashSet. If you don't want to duplicate code that's in your own detach method you should split that one up and let it be called from those 2 places.
How about some LINQ:
while (_shaders.Any()) {
DetachShader(_shaders.First());
}
This wouldn't work in general, though, because you could end up calling the function on the same element multiple times. It only makes sense if the function is removing the element from the underlying collection.
In the general case, where the function doesn't modify the collection, you could use something like this:
while (hashset.Any()) {
var item = hashset.First();
Process(item);
hashset.Remove(item);
}
Or this:
foreach (var item in hashset) {
Process(item);
}
hashset.Clear();
Update: As pointed out by #SLaks in the comments, calling First() for every element in the hash set as it's emptied is O(n^2). This doesn't matter for tiny collections, but could make a world of difference if you have a large collection.
I do not understand how come someone with 17k reputation is asking this. Am I missing something?
public void Dispose()
{
foreach(var shader in _shaders)
GL.DetachShader( Handle, shader.Handle );
_shaders.Clear();
}
If your collection is very small I would use:
foreach (var item in set.ToArray())
set.Remove(item);
Another solution would be the RemoveWhere() method:
set.RemoveWhere(item =>
{
Console.WriteLine(item);
return true;
});
Does anyone have any examples or ideas on how / what is the best way to implement a Stack class in C#? I understand that there is already a Stack class, but I need to understand how to actually implement a Stack class.
I also need advice on how to use Contracts in C# to specify preconditions, postconditions, and invariants for this class. I think I have used something similar before when creating models in the ASP.NET MVC architecture, but I'm not entirely sure if it is the same thing and works the same way. (I'm a bit lost on the preconditions/postconditions/invariants, if you couldn't already tell - so please bear with me.)
My main question - could someone give me advice on properly using Contracts for a class such as a Stack.
Yes, I have laid out effort:
public interface IStack
{
void Push(Object e);
Object Pop();
Object Top();
void EnsureCapacity();
}
}
public class Stack : IStack
{
private Object[] elements;
private int size = 0;
public Stack()
{
elements = new Object[0];
}
public void Push(Object e)
{
// check if this array capacity has been reached and increase if needed
EnsureCapacity();
elements[size++] = e;
}
public Object Pop()
{
// check if the method call is invalid for the object's current state
if (size == 0) throw new InvalidOperationException("Stack.Pop");
Object result = elements[--size];
elements[size] = null;
return result;
}
public Object Top()
{
// check if the method call is invalid for the object's current state
if (size == 0) throw new InvalidOperationException("Stack.top");
return elements[(size - 1)];
}
private void EnsureCapacity()
{
if (elements.Length == size)
{
Object[] oldElements = elements;
elements = new Object[(2 * size + 1)];
}
}
}
If you want, for getting started using Microsoft Code Contracts, I made a blog post about it once. That post covers the very basic of preconditions, post-conditions, and invariants.
As a summary of the concepts, you can think of them as follows:
Precondition is what must be true prior to a method being executed -- what clients promise your method.
Invariant is what must remain publicly true at all times as far as clients of your class are concerned.
Postcondition is what must be true following a method execution -- what your method promises to clients.
So, off the top of my head, for a stack, an easy thing to think of might be an invariant. If you're modeling the stack with an array, you might declare an invariant on the class that the array is never set to null, for example you'd define the invariant method:
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(elements != null);
}
It looks like you've already got a precondition on your pop method - you want to say that it's incumbent on the user to make sure that the stack is not empty when he executes a pop. So, at the beginning of the pop method, you'd have:
Contract.Requires(size > 0);
And finally, you might specifiy a post-condition on pop, that size will always be less than it was before the pop operation (you could get more specific if you like):
Contract.Ensures(Contract.OldValue<int>(size) > size);
Good luck with it -- contracts are cool and useful. It's a very clean way to code.
Many of collections implemented in c# are based on arrays. You could use array and add elements to the end, keep index of a top elemnet and increase it while new elements are pushed, of course array will "have to be extended" ( replaced by new one ) dynamically when new objects appear and there is no place for them in current array.
code contracts have pretty good documentation available at http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf