Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
hi,
 
im havin problems creating a class for first time. The programm is about a dog race, so if you need more explanaitions tell me please.

Here is my class:

 
class Dog
{
   public int RaceLenght =20;
   public int StartPosition = 0;
   public PictureBox IMG;
   public int Position;
   public Random Rnd;
 
   public bool Run(bool status)
   {
      return status;
   }
 
   public void reset()
   {
      Position = StartPosition;
   }
}
 

Here is my form:
 
string[]Arr = new string[4];
Dog Dog1 = new Dog();
Dog Dog2 = new Dog();
Dog Dog3 = new Dog();
Dog Dog4 = new Dog();
int distanz1;
int distanz2;
int distanz3;
int distanz4;

Run Button:

 
Dog1.Run(true)
Dog1.IMG = picturebox1;
Point p = picturebox1.Location;
distanz1 = Dog1.Rnd.Next(1,4);
p.X += distanz1;
Img.Location = p;
 
now i would do this for every object, what stands in the button, for dog2,3 and 4.
 
i think my code isnt the very best..
Posted 15-Oct-12 2:27am
Edited 15-Oct-12 6:34am
v3
Comments
digimanus at 15-Oct-12 7:31am
   
what is your exact problem?
do you get exceptions?
niko_tells at 15-Oct-12 7:34am
   
yes, out of bound at run button: distanz1 = dog1.rnd.Next(1,4) saying that i didnt create an new objekt. But i have -> Dog Dog1 = new Dog(); Also i would prefere dont writing the same for every dog in the runbutton, i would prefere this way more: run button: Dog1.Run(true); Dog2.Run(true);...
n.podbielski at 15-Oct-12 7:47am
   
Did you assigned value to Dog.Rnd at some point? For me this looks like null.
digimanus at 15-Oct-12 7:49am
   
4 dogs so dog[0] till dog[3] so when the randomizer says dog[4] you have a problem

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You haven't created an instance of the Random class within your Dog class:
class Dog
{
public int RaceLenght =20;
public int StartPosition = 0;
public PictureBox IMG;
public int Position;
public Random Rnd;
You could add the new bit:
public Random Rnd = new Random();
But that is a bit of a nuicence, since there is a very good chance that all Dogs will end up with the same sequence of random numbers. Instead, I would create a static random class and use that instead for all instances:
public static Random Rnd = new Random();
 ...
int i = Dog.Rnd.Next(1, 4);
 
BTW: I would strongly suggest that your fields should be properties - it is considered bad practice to expose fields directly, as it means you can't easily change the internals of your class without considering the effects on the outside world.
 

 
"ok im sorry wasting your time, i will now explaining it. its simple, i just want a programm that tells what dog was first on finish line. Every dog has another speed. I want to write it with classes. But now its the problem that all doggs are running, but not at same time.
 
Here is the method:
 
..
public Point p = new Point();
 
public bool run (bool status, int y) //y = y pixels position of images
{
while (status)
{
Position = Rnd.Next(1,4);
p.X +=Position;
p.Y = Y;
IMG.Location = p;
 
if(IMG.Location.X >= RaceLenght)
{
status = false;
}
Thread.Sleep(10);
 

}
return status;
}
"

 

 
Ok. This is going to be a bit difficult to explain, so please bear with me.
First off, we have to move away from your task, into more general Windows type things.
Windows operates differently from "normal" programs such as you might have written before, where flow passes from line to line, and always happens the same way.
In windows nothing happens at all unless an Event occurs to cause it to do somthing in response. That could be the user pressing a button, or a keyboard button, or some other application wanting something done for it.
When that happens, your code it told what event it is, and an event handler is executed to deal with it. If it is a button press, then you might want to close your application, or open a file. But you don't do either until the appropriate event handler is called for you.
 
That probably sounds irrelevant to your little dog race! Laugh | :laugh:
But it isn't. Not at all. Your code has a "run" method, which loops round until the dog reaches the "finish line" - which means that nothing else happens while you are still executing the run method (that's an over simplification, but it'll do for a few weeks). So when you call "run" on one dog, it just loops round until the dog finishes, and then continues with the next dog.
 
So, what to do?
Firstly, I want you to forget you ever saw the Thread.Sleep method. OK? Gone? Good - you don't want it now, you don't need it now, and it is very, very likely that you will never, ever need to use it unless your application is very badly designed! So forget it! OK?
 
What you want to do is move a picture of a dog a random amount forward then move the others, and see if any of them have "won". Which means you need to do it in "human" time, rather than computer time - the race should probably take a couple of seconds, maybe a minute.
To do that, you want an Event which will happen at regular intervals - we call that a Timer Tick event.
 
So, add a private field to your form class:
private Timer raceTimer = new Timer();
Now, in your Form Load event, add the following code:
            raceTimer.Interval = 100;
            raceTimer.Tick += new EventHandler(raceTimer_Tick);
            raceTimer.Start();
That builds a Timer which will call an event every tenth of a second (the 100 is in thousands of a second).
Now create the event handler:
        void raceTimer_Tick(object sender, EventArgs e)
            {
            ...
            }
Every tenth of a second, that method will be called - so change your Dog.Run method and make it do one iteration, one random "step" forward.
Then in the Tick handler call Run for each Dog, then check if any have finished. If they have, you have a winner and can stop the race by calling raceTime.Stop()
 

Sounds complex? It isn't really - try it, and you will see what I mean.
  Permalink  
v2
Comments
niko_tells at 15-Oct-12 10:13am
   
ok i have solved it on my own, but now the problem is, that dog1 runs first, afterwards dog2 runs when dog1 finished running etc.. until dog 4 ends. how do i initialize 4 objekts at the same time?
OriginalGriff at 15-Oct-12 10:27am
   
Depends what you are trying to do, and how you are doing it.
I don't want to explain something that *sounds* like it will solve your problem if it is a concept you have not got to yet, and might well confuse.
 
Why don't you explain what task you are trying to perform, and how you are trying to do it? Then I'll see if I can help at all.
niko_tells at 15-Oct-12 10:34am
   
ok im sorry wasting your time, i will now explaining it. its simple, i just want a programm that tells what dog was first on finish line. Every dog has another speed. I want to write it with classes. But now its the problem that all doggs are running, but not at same time.
 
Here is the method:
 
..public Point p = new Point();
 
public bool run (bool status, int y) //y = y pixels position of images
{
while (status)
{
Position = Rnd.Next(1,4);
p.X +=Position;
p.Y = Y;
IMG.Location = p;
 
if(IMG.Location.X >= RaceLenght)
{
status = false;
}
Thread.Sleep(10);
 

}
return status;
}
OriginalGriff at 15-Oct-12 11:04am
   
Answer updated
Monjurul Habib at 15-Oct-12 16:39pm
   
5!
RaisKazi at 15-Oct-12 20:16pm
   
My 5.
niko_tells at 16-Oct-12 2:03am
   
Never had a better answer, thank you Griff!!!
 
Just one little problem, how to "set a reference to raceTimer in Form1?"
 
Very thanks Griff, give you 5 stars and accept question =]
 

my code now:
private void RUN_Click(object sender, EventArgs e)
{
raceTimer.Start();
raceTimer.Interval = 100;
 
}
 
private void Form1_Load(object sender, EventArgs e)
{
Dog1.IMG = IMG1;......
 

raceTimer.Tick += new EventHandler(raceTimer_Tick);

}
 
void raceTimer_Tick(object sender, EventArgs e)
{

 
if (raceTimer.Interval == 100)
{
Dog1.Run(status,50);
}
 
if (status != true)
{
raceTimer.Stop();
}
}
 
doggs are stil running one after another..
niko_tells at 16-Oct-12 2:45am
   
ah i know i have to recode my run method, cause if the dog gets run, it runs until the end, but i have just to tell with run method, go an rnd step forward, and with every tick event this will be repeated!
OriginalGriff at 16-Oct-12 3:14am
   
Well done! That is exactly what should happen, and what I meant when I said ' so change your Dog.Run method and make it do one iteration, one random "step" forward.'
niko_tells at 16-Oct-12 3:22am
   
Thank you very much griff for that tipps and support! But im trying all time long finding out why my dog objects all gets the same "random speed"
 
class: Random Speed = new Random();
run()
{
Position = Speed.Next(1,4);
}
 
form: Dog Dog1 = new Dog();
 
and i dont understand why i always get the same random speed
OriginalGriff at 16-Oct-12 4:03am
   
AS I said originally, "there is a very good chance that all Dogs will end up with the same sequence of random numbers."
Random number generators are not really random: they are what is called psuedo random sequences, because the sequence values look random, but if they start from the same initialisation seed, they generate the same sequence. Think of it like a "add three" method: each time you call it, it adds three to the last value and returns it. if you call it with a starting value of six every time, then it always generates nine, twelve, fifteen, and so on.
When your create an instance of the Random class, it is initialised effectively using the system clock to start the sequence (this is called a Seed). If two or more Random instances are created close together, there is a very good chance that they will start in the same clock period, and so get the same Seed.
 
So make your Random instance static as I suggested, and the same instance will be used for all Dogs. This means that they just take from different positions within the random stream, instead of the same position in different (but identical) streams.
 
Does that make any sense? It's a little difficult to explain this without diagrams and being able to see when your eyes start to glaze over... :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 240
1 Kamal Rocks 184
2 PIEBALDconsult 150
3 BillWoodruff 148
4 Jochen Arndt 135
0 OriginalGriff 5,695
1 DamithSL 4,506
2 Maciej Los 4,007
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,190


Advertise | Privacy | Mobile
Web01 | 2.8.141216.1 | Last Updated 15 Oct 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100