Head First C# method issue - c#

I have this weird issue occuring everytime I run my game "Day at the Races" in Visual Studio. So basically I'm working with Forms. I have 4 PictureBoxes, with dog photos. Dogs info are stored in an array. After each race I want to put these Pictures back on the starting line. So I have made a method:
public void SetToStartingPosition()
{
for (int j=0; j < GreyhoundArray.Length; j++)
{
GreyhoundArray[j].MyPictureBox.Left = 0;
}
}
I run this method every time the race is finished and here's what happens:
All 4 PictureBoxes goes back to starting position (x=0) as intended, then the MessageBox pops up, and when I press "OK" to close it, a random number from 1 to 3 of PictureBoxes(Dogs) goes back to the right position(x=600)... I just have no idea why closing this MessageBox has such weird influence, I don't see any connection between these two, also no other methods have anything to do with PictureBox.Left. Any ideas of what's happening would be very appreciated.
public void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i <GreyhoundArray.Length; i++)
{
GreyhoundArray[i].Run(); //method making PictureBoxes move to the right
if (GreyhoundArray[i].Run() == true) //GreyhoundArray[i].Run() is true when the race is finished
{
timer1.Stop();
**SetToStartingPosition();**
winDog = i;
MessageBox.Show("Dog number " + (winDog + 1) + " has won!");
groupBox1.Enabled = true;
button1.Text = "RESTART!";
for (int k =0; k < GuysArray.Length; k++)
{
if (GuysArray[k].MyBet != null)
{
GuysArray[k].Collect(winDog);
GuysArray[k].ClearBet();
GuysArray[k].UpdateLabels();
}
}
break;
}
}
}
Edit:
Oh wow, you just gave ma a clue whats wrong, so there actually was PictureBox location changing line in Run() method, which I was sure would stop when one of the dogs win the race, but I didnt break the loop, so it was still going, and setting dogs back on their position. All I had to do was adding 'break;' in the end of the loop. And just for your and some others info:
` public bool Run()
{
if (MyPictureBox.Left > 600 - MyPictureBox.Width)
{
return true;
}
else
{
Location += MyRandom.Next(1, 4);
MyPictureBox.Left = StartingPosition + Location;
return false;
} `
Thanks for help tho, thats a bad and ambarrasing start of my Stack Overflow "carrer" :(

Related

Tiles not following input in a branching board game path

I'm making a board game in Unity with multiple branching paths where the players can decide which one to follow. (Think the Mario Part game board) But the player input on which path to follow isn't working.
So I have a script that has the tokens follow a set path and (Linked List for the path) with a for loop to have the tokens move their allocated amount. Within the loop, I have an If statement that checks how many paths the tile has and if there are more than one if runs a separate script that pauses the game and offers a menu prompt for the players to pick one path or the other.
I've tried tossing in a few contitions for continuing the game within the loop but they either ignore the player input, are an input behind or just break the code.
`for (int i = 0; i < spacesToMove; i++)
{
if (final_Waypoint == null)
{
final_Waypoint = Starting_Waypoint;
}
else
{
if (final_Waypoint.Next_Waypoint == null || final_Waypoint.Next_Waypoint.Length == 0)
{
//we are overshooting the final waypoint, so just return some nulls in the array
//just break and we'll return the array, which is going to have nulls at the end.
Debug.Log(Current_Waypoint);
break;
}
else if (final_Waypoint.Next_Waypoint.Length > 1) // && if playerID == 0 so it only appears for players.
{
menu.Pause_for_Choice();
//if (menu.ButtonPress == true)
final_Waypoint = final_Waypoint.Next_Waypoint[menu.choice_int];
//***There's a bug here. It calls menu as per normal, and the game pauses.
//But when I click 'no', choice_int isn't updated first: this function finishes first,
//so this function gets old choice_int. THEN the button function executes.
Debug.Log("test 3 " + menu.choice_int);
}
else
{
final_Waypoint = final_Waypoint.Next_Waypoint[0];
}
}
listOfWaypoints[i] = final_Waypoint;
Debug.Log("i:" + i);
}
return listOfWaypoints;
}`
`{
public GameObject choice_Menu;
public bool isPaused = true;
public int choice_int=0;
public int choice_placeholder = 0;
public void Pause_for_Choice()
{
isPaused = true;
choice_Menu.SetActive(true);
Time.timeScale = 0;
}
public void Yes()
{
choice_placeholder = 0;
UnPause_Game();
}
public void No()
{
choice_placeholder = 1;
UnPause_Game();
}
public void UnPause_Game()
{
isPaused = false;
choice_Menu.SetActive(false);
Time.timeScale = 1;
}
}`

How to delete multiple lines in console mode C#

I'm coding a game and I am struggling in deleting my stickman before I draw another one.
I could just use Console.Clear() but it clears the whole console and I only need to delete the previous stickman.
I'm trying to use:
private static string path = #"c:..\..\characters\";
private string file;
private int xpast = 0;
private int ypast = 0;
private int LinhasSeparacao;
public Graphics()
{
}
public Graphics(string file)
{
this.file = file;
StreamReader sr = new StreamReader(path + file);
LinhasSeparacao = 0;
do
{
LinhasSeparacao++;
}
while (sr.ReadLine() != "separar");
sr.Close();
}
public void Draw(int x, int y,bool forma = true)
{
string[] persona = File.ReadAllLines(path + file);
LimparAnterior(forma,persona,x,y);
//Console.Clear();
if (forma)
{
for (int i = 0; i < LinhasSeparacao - 1; i++)
{
Console.SetCursorPosition(x, y + i);
Console.Write(persona[i]);
}
}
else
{
int j= 0;
for (int i = LinhasSeparacao; i <persona.Length-1; i++)
{
Console.SetCursorPosition(x, y + j);
Console.Write(persona[i]);
j++;
}
}
xpast = x;
ypast = y;
}
private void LimparAnterior(bool forma,string[] persona, int xlive, int ylive)
{
int i = 0;
for (i = 0 ; i < LinhasSeparacao; i++)
{
Console.SetCursorPosition(xpast > 0? xpast -1:xpast,ypast + i);
Console.Write(" ",persona[i].Length);
}
}
This is my class to draw the new character, it needs x and y coordinates. I use a file to the drawing and put all the line into a array called persona. I'm drawing after someone press the arrows to make the little guy move.
If you need more information, say something. Here is the link to github:
https://github.com/digaso/Wizardoft
The code isn't necessarily your problem, if you look at the hero.txt file you'll notice that there is no space to the right of the hero's sword...
_A_
0
/|\/
/ \
separar
_A_
0
\/|\X
/ \
separar
See where I put the 'X' character? When you hero is facing right there is a sword there. But when you move him left there is no space to overwrite the cell where the sword was.
You either need to alter your hero.txt file so that it has spaces in strategic locations or update your drawing code so that it erases the area where your stickman was, then update his position and draw in the new position.
Since this seems to be a casual learning experience this is fine but if you do decide to get more adventurous you'll want to use a library specifically designed for this kind of thing or redesign your code so that it "composes" the scene by drawing each character to a buffer and then taking the finished buffer to the physical screen. Have fun!

c# Windows Forms adding pictureBoxes to an Array

I need to add PictureBox's (pictureBox11 to pictureBox30) to an array.
So instead of adding PictureBox's like this:
PictureBox[] Coins = new PictureBox[20];
Coins[0] = pictureBox11;
...
Coins[19] = pictureBox30;
I wrote a for cycle like this (DOESN'T WORK) :
for (int i = 11; i < 31; i++)
{
for (int j = 0; j < Coins.Length; j++)
{
Coins[j] = (PictureBox)Controls.Find(
"pictureBox" + i.ToString(), true)[0];
}
}
There might be a small stupid mistake somewhere because I use the same cycle for another thing and it works, idk, maybe I'm just blind and cant see the mistake.
Maybe it is relevant, so I will include the code I am assigning for the array elements:
for (int i = 0; i < Coins.Length; i++)
{
if (player.Bounds.IntersectsWith(Coins[i].Bounds))
{
Coins[i].Visible = false;
}
}
EVERYTHING works fine if I add them as shown in first code, but it is not very practical.
Why isn't the second code (the for cycle) I wrote working for me?
Is there a better way to add multiple pictureboxes to an array?
I am guessing you are making this more complicated than it has to be. To try and understand better, I assume that when you say I need to add pictureboxes (pictureBox11 to pictureBox30) to an array. that you mean there are 30+ PictureBoxs on your form and each PictureBox uses a naming convention such that each is named “pictureBoxX” where “X” is 1,2,3…30,31. Then you want to get a (consecutive?) group of “PictureBoxes” on the form to make invisible. I hope this is correct.
To simply make the picture boxes invisible, I do not think an array is needed. Simply loop through the picture boxes and make it invisible if the name matches a string of the form “pictureBoxX “. I used IndexsAreValid method to validate the start and end indexes. It is also used in the code for an array implementation below this code.
Make PictureBoxes invisible without an array
private void SetPictureBoxesInvisible(int start, int end) {
int size = -1;
string targetString = "";
if (IndexsAreValid(start, end, out size)) {
for (int i = start; i < end + 1; i++) {
try {
targetString = "pictureBox" + i;
PictureBox target = (PictureBox)Controls.Find(targetString, true)[0];
if (target != null) {
target.Visible = false;
}
}
catch (IndexOutOfRangeException e) {
return;
}
}
}
}
If you must have a PictureBox array returned, then the code below should work.
First, to get an array of PictureBoxs as you want you need an array to store them. But first you need to know how big to make it. From your posted code it appears that you want to get picture boxes 11-30 and put them in an array. So we can get the size from these numbers… i.e. 30-11=19 +1 = 20. That’s about all you need. Simply create the array and loop through all the picture boxes and grab pictureBox11-pictureBox30. When done we can use this array to make these `PictureBoxes” invisible.
I created a method IsValidPic similar to a tryParse to validate if the given index (1,2,3..30) is valid. If it is out of range, I simply ignore that value. This gives you the ability to grab an individual picture box in case the desired picture boxes are not contiguous. I used a few buttons to test the methods.
Hope this helps.
private PictureBox[] GetPictureBoxes(int start, int end) {
int size = - 1;
if (IndexsAreValid(start, end, out size)) {
PictureBox curPic = null;
PictureBox[] allPics = new PictureBox[size];
int index = 0;
for (int i = start; i <= end; i++) {
if (IsValidPic(i, out curPic)) {
allPics[index] = curPic;
index++;
}
}
return allPics;
}
else {
return new PictureBox[0];
}
}
private Boolean IndexsAreValid(int start, int end, out int size) {
if (start < 1 || end < 1) {
size = -1;
return false;
}
if (start > end) {
size = -1;
return false;
}
size = end - start + 1;
return true;
}
private Boolean IsValidPic(int index, out PictureBox picture) {
string targetName = "pictureBox" + index;
try {
PictureBox target = (PictureBox)Controls.Find(targetName, true)[0];
if (target != null) {
picture = target;
return true;
}
picture = null;
return false;
}
catch (IndexOutOfRangeException e) {
picture = null;
return false;
}
}
private void ResetAll() {
foreach (PictureBox pb in this.Controls.OfType<PictureBox>()) {
pb.Visible = true;
}
}
private void button1_Click(object sender, EventArgs e) {
TurnInvisible(2, 3);
}
private void button3_Click(object sender, EventArgs e) {
TurnInvisible(11, 30);
}
private void button4_Click(object sender, EventArgs e) {
TurnInvisible(1,7);
}
private void TurnInvisible(int start, int end) {
PictureBox[] pictureBoxesToChange = GetPictureBoxes(start, end);
foreach (PictureBox pb in pictureBoxesToChange) {
if (pb != null)
pb.Visible = false;
}
}
private void button2_Click(object sender, EventArgs e) {
ResetAll();
}

Windows Form App for loop not working

int i = 0;
private void button1_Click(object sender, EventArgs e)
{
for (int j = 10; j < 1000; j = j + 1)
{
string y = i.ToString();
webBrowser1.Document.GetElementById("lst-ib").SetAttribute("value", y);
i++;
}
}
This is the section of code I'm working with in a windows form application
I want it to input the value and show it going up however it just jumps to the end and puts the last output instead of counting up.
Some people said to use timers but I haven't been able to get them to work.
Any ideas?
You're locking up the UI thread with your loop, so that it doesn't update the control until it's done with its work. You end up only seeing the final value, when the loop is complete and the UI refreshes.
Take a look at using a Timer control instead. You can tell it to raise an event at regular intervals, and it'll allow your UI to be updated correctly.
Add a Timer to your Form and then insert the following code into your constructor to try it out. Currently, it updates your element every 1 ms (in reality, it won't be that fast).
int i = 0;
int j = 10;
timer1.Interval = 1;
timer1.Tick += (s, e) =>
{
string y = i.ToString();
webBrowser1.Document.GetElementById("lst-ib").SetAttribute("value", y);
i++;
j++;
if (j > 1000)
timer1.Stop();
};
timer1.Start();

C# WMPLib Duration of a mp3

Im using WMPLib to make an easy mp3player in C#. Im almost done but theres one more thing I want to do.
I Would like to how far gone the song is and also, how much is left of the song.
using for example the progressbar.
thanks
Adam
private void timer1_Tick(object sender, EventArgs e)
{
double percent = 0;
if (mp.Length != 0)
percent = ((double) wplayer.controls.currentPosition / wplayer.controls.currentItem.duration);
progressBar1.Value = (int)(percent * progressBar1.Maximum);
}
I have an Idea , just try to add statusStrip to your Project Form , and try to add a ToolStripStatusLabel and ToolStripProgressBar to it, and then you can use this simple code , it Works 100% :
public void Sound_Progress(ToolStripStatusLabel l1, ToolStripProgressBar psb)
{
//NASSIM LOUCHANI
int i = Convert.ToInt32(Player.controls.currentItem.duration);
int j = Convert.ToInt32(Player.controls.currentPosition);
int Defrence = (i-j);
l1.Text = Player.controls.currentPositionString + " | " + Player.controls.currentItem.durationString;
psb.Maximum = i;
psb.Minimum = 0;
if (Defrence == i)
psb.Value = i;
else if (Defrence != i)
psb.Value = Defrence;
else if (Defrence == 0)
l1.Text = "";
}
And don't forget to add a Timer to your Project Form and put the Sound_Progress(your ToolStripStatusLabel, your ToolStripProgressBar) into your Timer_Tick() Event .
Thank you !

Categories