Restarting while loop in C# - c#

I am a beginner in C# and creating a small game in where the user gets to throw a ball with a certain gravity, speed and random wind. The ball is supposed to hit a goal, give the user points (when it hits) and then go back to start position for user to throw it again. I have got everything working except the matter of getting the ball back into start position. Any help would be greatly appreciated!
Here is some parts of my code:
private void goButton_Click(object sender, EventArgs e)
{
if (running == true)
{
b1.Location = new Point(0, 300);
b1.speedX = (double)upDownX.Value;
b1.speedY = (double)upDownY.Value;
running = false;
b1.Start();
return;
}
running = true;
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(RunMe); worker.RunWorkerAsync();
}
public void RunMe(object sender, DoWorkEventArgs e)
{
while (running)
{
if (b1.speedY > 0 && b1.Location.Y > panel.Size.Height - b1.Size.Height)
{
b1.posY = panel.Size.Height - b1.Size.Height;
addPoints();
running = false;
BeginInvoke((MethodInvoker)delegate
{
b1.Location = new Point(0, 300);
});
}
if (b1.speedX > 0 && b1.Location.X > panel.Size.Width - b1.Size.Width)
{
running = false;
if (b1.Location.Y < 290 && b1.Location.Y > 150 && b1.Location.X > 430)
{
if (diffValue.Text == "Normal")
{
Ball.score += 10;
}
if (diffValue.Text == "Easy")
{
Ball.score += 7;
}
}
else if (b1.Location.Y < 390 && b1.Location.Y > 60 && b1.Location.X > 430)
{
if (diffValue.Text == "Normal")
{
Ball.score += 5;
}
if (diffValue.Text == "Easy")
{
Ball.score += 3;
}
}
addPoints();
b1.BounceX();
goto restart;
}
if (b1.speedX < 0 && b1.Location.X < 0)
{
b1.BounceX();
}
this.Invoke(new MoveBallCallback(MoveBall), b1);
Thread.Sleep(10);
}
}
public void addPoints()
{
if (Ball.tries >= 1)
{
Ball.tries -= 1;
string triesLeft = Ball.tries.ToString();
this.Invoke(new Action(() => this.shotsLeft.Text = triesLeft));
string score = Ball.score.ToString();
this.Invoke(new Action(() => this.scores.Text = score));
Normal();
BeginInvoke((MethodInvoker)delegate
{
b1.Location = new Point(0, 300);
});
}
else
{
MessageBox.Show("No shots left!");
string currentHighscore = System.IO.File.ReadAllText(#"highscore.txt");
this.highscoreValue.Text = currentHighscore;
int Highscore = Convert.ToInt32(currentHighscore);
string score = Ball.score.ToString();
this.Invoke(new Action(() => this.scores.Text = score));
int Score = Convert.ToInt32(Ball.score);
if (Score > Highscore)
{
MessageBox.Show("New highscore!");
string highScore = score;
System.IO.File.WriteAllText(#"highscore.txt", highScore);
string highscore = Highscore.ToString();
this.Invoke(new Action(() => this.highscoreValue.Text = highscore));
}
this.Invoke(new Action(() => goButton.Enabled = false));
}
}

You can use:
continue;
to skip to next repetition of a loop (where you write goto restart;).

Related

How i save and load back and continue the timespan milliseconds value each time running the application again?

the problem is that you can't assign to timespan milliseconds it's read only.
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{
ticksDisplayed += diff;
}
else
{
if (countingDown)
{
ticksDisplayed += diff;
}
else
{
ticksDisplayed -= diff;
}
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
timer1.Enabled = false;
}
ctimeSpan = new TimeSpan(ticksDisplayed);
timeTarget(ctimeSpan);
if (trackBarHours.Value != ctimeSpan.Hours) { trackBarHours.Value = ctimeSpan.Hours; }
if (trackBarMinutes.Value != ctimeSpan.Minutes) { trackBarMinutes.Value = ctimeSpan.Minutes; }
if (trackBarSeconds.Value != ctimeSpan.Seconds) { trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
calling the UpdateTime here
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
saving the timespan milliseconds is not a problem , the problem is how to read it back because you can't assign to ctimeSpan.Milliseconds.
i could save the string.Format variable result again in more places but sometimes result is null if i try to save it in the form1 closed event. so i prefer to save and load back only the ctimeSpan.Milliseconds value in that specific situation.
Editing with the full code of form1 and a screenshot.
Now i'm using the 3 trackBars to save and load the timespan hours,minutes,seconds but because i don't want to add another trackBar for the milliseconds that is the reason i want to save/load the milliseconds separated.
in my application i'm using my own OptionsFile class but it does not matter i want to find the logic and how to save/load the milliseconds separated from the way i'm saving/loading the hours,minutes,seconds.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using DannyGeneral;
namespace StopwatchTimer
{
public partial class Form1 : Form
{
private static readonly Stopwatch watch = new Stopwatch();
private long diff = 0, previousTicks = 0, ticksDisplayed = 0;
private OptionsFile optionsfile = new OptionsFile(Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Settings.txt");
private string result;
private bool runOnStart = false;
private bool countingDown = false;
private TimeSpan ctimeSpan;
public Form1()
{
InitializeComponent();
richTextBox1.TabStop = false;
richTextBox1.ReadOnly = true;
richTextBox1.BackColor = Color.White;
richTextBox1.Cursor = Cursors.Arrow;
richTextBox1.Enter += RichTextBox1_Enter;
trackBarHours.Value = Convert.ToInt32(optionsfile.GetKey("trackbarhours"));
trackBarMinutes.Value = Convert.ToInt32(optionsfile.GetKey("trackbarminutes"));
trackBarSeconds.Value = Convert.ToInt32(optionsfile.GetKey("trackbarseconds"));
richTextBox1.Text = optionsfile.GetKey("result");
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
ticksDisplayed = ctimeSpan.Ticks;
radioButton1.Checked = GetBool("radiobutton1");
timeTargetchkbox.Checked = GetBool("timetargetcheckbox");
timeTargetchkboxState();
if (ticksDisplayed > 0 && radioButton1.Checked == false)
radioButton2.Checked = true;
if (ticksDisplayed == 0)
radioButton1.Checked = true;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnPause.Enabled = false;
btnReset.Enabled = false;
}
else
{
btnPause.Enabled = false;
btnReset.Enabled = true;
}
runOnStart = GetBool("runonstart");
if (runOnStart == true)
{
autoRunOnStart.Checked = true;
StartOnRun();
}
else
{
autoRunOnStart.Checked = false;
}
}
private void timeTargetchkboxState()
{
if (timeTargetchkbox.Checked == false)
{
dateTimePicker1.Enabled = false;
}
else
{
dateTimePicker1.Enabled = true;
}
}
private void RichTextBox1_Enter(object sender, EventArgs e)
{
btnStart.Focus();
}
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{
ticksDisplayed += diff;
}
else
{
if (countingDown)
{
ticksDisplayed += diff;
}
else
{
ticksDisplayed -= diff;
}
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
timer1.Enabled = false;
}
ctimeSpan = new TimeSpan(ticksDisplayed);
timeTarget(ctimeSpan);
if (trackBarHours.Value != ctimeSpan.Hours) { trackBarHours.Value = ctimeSpan.Hours; }
if (trackBarMinutes.Value != ctimeSpan.Minutes) { trackBarMinutes.Value = ctimeSpan.Minutes; }
if (trackBarSeconds.Value != ctimeSpan.Seconds) { trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
private void timeTarget(TimeSpan ctimeSpan)
{
if (dateTimePicker1.Value.Hour == ctimeSpan.Hours
&& dateTimePicker1.Value.Minute == ctimeSpan.Minutes
&& dateTimePicker1.Value.Second == ctimeSpan.Seconds
&& timeTargetchkbox.Checked == true)
{
//ticksDisplayed = 0;
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
}
else
{
if (btnStart.Text == "STOP")
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
timeTargetchkboxState();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "START")
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
else
{
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
btnReset.Enabled = false;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Reset();
timer1.Enabled = false;
UpdateTime();
}
}
private void btnReset_Click(object sender, EventArgs e)
{
watch.Reset();
diff = 0;
previousTicks = 0;
ticksDisplayed = 0;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnReset.Enabled = false;
}
else
{
btnReset.Enabled = true;
}
if (radioButton2.Checked && ticksDisplayed == 0)
{
countingDown = true;
radioButton2.Checked = false;
radioButton1.Checked = true;
}
UpdateTime();
}
private void trackBarHours_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan htimeSpan = new TimeSpan(ctimeSpan.Days, trackBarHours.Value, ctimeSpan.Minutes, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = htimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
UpdateTime();
}
private void trackBarMinutes_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan mtimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, trackBarMinutes.Value, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = mtimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
UpdateTime();
}
private void trackBarSeconds_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan stimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, ctimeSpan.Minutes, trackBarSeconds.Value, ctimeSpan.Milliseconds);
ticksDisplayed = stimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
UpdateTime();
}
private void TrackbarsScrollStates()
{
if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
btnReset.Enabled = false;
if (trackBarSeconds.Value > 0 || trackBarHours.Value > 0 || trackBarMinutes.Value > 0)
btnReset.Enabled = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
optionsfile.SetKey("radiobutton1", radioButton1.Checked.ToString());
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
}
private void btnPause_Click(object sender, EventArgs e)
{
Pause();
}
private void Pause()
{
if (btnStart.Text == "STOP")
{
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
else
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
private void autoRunOnStart_CheckedChanged(object sender, EventArgs e)
{
if (autoRunOnStart.Checked)
{
runOnStart = true;
}
else
{
runOnStart = false;
}
optionsfile.SetKey("runonstart", runOnStart.ToString());
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
countingDown = false;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
btnStart.Focus();
timeTarget(ctimeSpan);
}
private void timeTargetchkbox_CheckedChanged(object sender, EventArgs e)
{
if (timeTargetchkbox.Checked == false)
{
dateTimePicker1.Enabled = false;
}
else
{
dateTimePicker1.Enabled = true;
}
optionsfile.SetKey("timetargetcheckbox", timeTargetchkbox.Checked.ToString());
}
private void StartOnRun()
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
private bool GetBool(string keyname)
{
string radiobutton1 = optionsfile.GetKey(keyname);
bool b = false;
if (radiobutton1 != null)
{
bool.TryParse(radiobutton1.Trim(), out b);
}
return b;
}
}
}
and a screenshot showing the application :
I'm going to attempt to generalize as the question doesn't show a clear intent on what is trying to be accomplished and so it's difficult to give a clear answer.
There are many ways to instantiate a new TimeSpan as documented here:
https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=net-7.0#instantiating-a-timespan-value
If I were trying to persist and load a TimeSpan then I would personally look towards using the ticks value.
e.g.
// Create a TimeSpan to test with.
var randomTimer = Stopwatch.StartNew();
Thread.Sleep((new Random()).Next(1000,5000)); // Wait 1 to 5 second to get a meaningful value in the example TimeSpan.
var myTimeSpanToSave = randomTimer.Elapsed;
// Save the total ticks here.
var totalEllapsedTicks = myTimeSpanToSave.Ticks;
// Load total ticks and instantiate a new TimeSpan
var newTimeSpanFromTicks = new TimeSpan(totalEllapsedTicks);
I'm not sure why you would want to modify just the Millisecond portion of a TimeSpan but assuming there is a valid reason then here are a couple of ideas.
Idea 1 - Create a new TimeSpan using the values from the original object and substituting the Millisecond property only.
var customMilliseconds = 123;
var newTimeSpanWithCustomMilliseconds = new TimeSpan(myOriginalTimeSpan.Days, myOriginalTimeSpan.Hours, myOriginalTimeSpan.Minutes, myOriginalTimeSpan.Seconds, customMilliseconds);
Idea 2 - Use Add to clear the current Millisecond value and insert the loaded value.
var customMilliseconds = new TimeSpan(0, 0, 0, 0, 123);
var oldMillisecondValueToRemove = new TimeSpan(0, 0, 0, 0, myOriginalTimeSpan.Milliseconds);
myOriginalTimeSpan.Add(-oldMillisecondValueToRemove);
myOriginalTimeSpan.Add(customMilliseconds);

Intersect a circle with a picturebox

I am making a DxBaLL Game. First i tried make the ball with picturebox but when it comes to intersection, if ball interects with 2 bricks, bricks just break but i want them break in 3 shots. So then, i tried make ball with Graphics.DrawEllips but how can i detect if ball intersect with picturebox(brick) or not?
This is the ball with picturebox version. when the ball comes between 2 bricks(picturebox), bricks are disappearing.
namespace DxBall
{
public partial class Form1 : Form
{
bool goLeft, goRight, isGameOver;
bool gameStart = false;
int sideCount = 0;
int force = 3;
int x_force = 3;
int gameScore = 0;
int[] direction = { 0, 0 }; //x,y
int stickSpeed = 15;
public Form1()
{
InitializeComponent();
}
private async void MainGameTimer(object sender, EventArgs e)
{
if (gameStart == false)
{
gameStart = true;
}
txt_score.Text = "Score: " + gameScore;
if (goLeft == true && stick.Left > 0)
{
stick.Left -= stickSpeed;
}
if (goRight == true && stick.Left < 458)
{
stick.Left += stickSpeed;
}
if (direction[0] == 0)
{
if (ball.Left > 580)
{
direction[0] = 1;
}
else
{
ball.Left += x_force;
}
}
else if (direction[0] == 1)
{
if (ball.Left < 0)
{
direction[0] = 0;
}
else
{
ball.Left -= x_force;
}
}
if (direction[1] == 0)
{
if (ball.Top > 720)
{
direction[1] = 1;
}
else
{
ball.Top += force;
}
}
else if (direction[1] == 1)
{
if (ball.Top < 0)
{
direction[1] = 0;
}
else
{
ball.Top -= force;
}
}
foreach (Control x in this.Controls)
{
if (x is PictureBox)
{
if ((string)x.Tag == "stick")
{
if (ball.Bounds.IntersectsWith(x.Bounds))
{
direction[1] = 1;
}
x.BringToFront();
}
if ((string)x.Tag == "brick")
{
if (ball.Bounds.IntersectsWith(x.Bounds))
{
sideCount++;
if (x.BackColor == Color.Red && x.Visible == true&&sideCount<1)
{
if (direction[1] == 0) direction[1] = 1;
else if (direction[1] == 1) direction[1] = 0;
x.BackColor = Color.Yellow;
}
else if (x.BackColor == Color.Yellow && x.Visible == true && sideCount < 1)
{
if (direction[1] == 0) direction[1] = 1;
else if (direction[1] == 1) direction[1] = 0;
x.BackColor = Color.Blue;
}
else if (x.BackColor == Color.Blue && x.Visible == true && sideCount < 1)
{
if (direction[1] == 0) direction[1] = 1;
else if (direction[1] == 1) direction[1] = 0;
x.Visible = false;
gameScore++;
}
}
x.BringToFront();
}
if ((string)x.Tag == "gameOver")
{
if (ball.Bounds.IntersectsWith(x.Bounds))
{
GameTimer.Stop();
txtGameOver.Text = "Game Over! Your Score is: " + gameScore;
}
}
}
}
sideCount--;
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goLeft = true;
}
if (e.KeyCode == Keys.Right)
{
goRight = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
ball.Left = rnd.Next(0, 580);
direction[0] = rnd.Next(0, 2);
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goLeft = false;
}
if (e.KeyCode == Keys.Right)
{
goRight = false;
}
}
private void RestartGame()
{
goLeft = false;
goRight = false;
isGameOver = false;
gameScore = 0;
txt_score.Text = "Score: " + gameScore;
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Visible == false)
{
x.Visible = true;
}
}
ball.Left = 390;
ball.Top = 527;
stick.Left = 310;
stick.Top = 700;
GameTimer.Start();
}
}
}

I'm getting error Ambiguity between '¨Form1.score' and ¨Form1.score'

i have int score = 0; under public partial class Form1 : Form and Im getting error in txtscore.Text = "Score: " + score; and score = 0; in private void RestartHry() does someone know why is that? Or know how to fix that bsc i have no idea. ......................................................................................................................................................................................
namespace Projekt_Havlík
{
public partial class Form1 : Form
{
bool vpravo, vlevo;
int rychlost = 8;
int score = 0;
int minul = 0;
Random rndX = new Random();
Random rndY = new Random();
PictureBox minulcoin = new PictureBox();
public Form1()
{
InitializeComponent();
RestartHry();
}
private void MainGameTimerEvent(object sender, EventArgs e)
{
//naprogramovaní textboxů
txtscore.Text = "Score: " + score;
txtminul.Text = "Minul: " + minul;
//změnění postavy při jízdě do leva/prava
if (vlevo == true && player.Left > 0)
{
player.Left -= 12;
player.Image = Properties.Resources.main_left;
}
if (vpravo == true && player.Left + player.Width <this.ClientSize.Width)
{
player.Left += 12;
player.Image = Properties.Resources.main_right;
}
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = false;
}
if (e.KeyCode == Keys.Right)
{
vpravo = false;
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = true;
}
if (e.KeyCode == Keys.Right)
{
vpravo = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void RestartHry()
{
foreach(Control x in this.Controls)
{
if (x is PictureBox &&(string)x.Tag == "coins")
{
x.Top = rndY.Next(80, 300) * -1;
x.Left = rndX.Next(5, this.ClientSize.Width - x.Width);
}
}
player.Left = this.ClientSize.Width / 2;
player.Image = Properties.Resources.main_right;
score = 0;
minul = 0;
rychlost = 8;
vpravo = false;
vlevo = false;
CasovacHry.Start();
}
}
}
Try changing the name of your "score" variable, try calling it like, "myScore", typically if something is ambiguous it is because there are two fields or properties with the same name in assembly references that are not directly specified in the code.

Reset button in a c# game [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So, I'm making a game which is kind of similar to pac-man and I want to add a reset-button (resetting the game, NOT restarting the application). I've tried a lot of things but I still can't get it working. Any solutions?
Thanks in advance,
Henk
public partial class Game : Form
{
public int GameHeigth = 45;
public int GameWidth = 45;
private Hokje[,] matrix = new Hokje[15, 15]; //creates the "game board"
private List<VObject> XObjects = new List<VObject>(); //list of the objects that
the game has(unmoveable boxes and moveable by the player boxes)
private Hero Maxim; // the hero of the game
private Random rnd = new Random();
public Reaper Linde { get; private set; } // the enemy
public Game()
{
InitializeComponent();
GenerateField();
NeighbourBase();
StartGame();
}
private void GenerateField()
{
int newpointY = 0;
int newpointX = 0;
for (int y = 0; y < 15; y++)
{
for (int x = 0; x < 15; x++)
{
int choise = rnd.Next(0, 99);
Hokje green = new Hokje();
matrix[y, x] = green;
green.Location = new Point(newpointX, newpointY);
Controls.Add(green);
if (choise < 20)
{
Doos box = new Doos(green);
}
if (choise >= 20 && choise <= 25)
{
Muur wall = new Muur(green);
}
newpointX = newpointX + GameWidth;
}
newpointX = 0;
newpointY = newpointY + GameHeigth;
}
}
private void NeighbourBase()
{
for (int y = 0; y < 15; y++)
{
for (int x = 0; x < 15; x++)
{
try
{
matrix[y, x].Buren[Direction.Up] = matrix[y - 1, x];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Up] = null;
}
try
{
matrix[y, x].Buren[Direction.Down] = matrix[y + 1, x];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Down] = null;
}
try
{
matrix[y, x].Buren[Direction.Left] = matrix[y, x - 1];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Left] = null;
}
try
{
matrix[y, x].Buren[Direction.Right] = matrix[y, x + 1];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Right] = null;
}
}
}
}
private void StartGame()
{
Maxim = new Hero(matrix[0, 0]);
Linde = new Reaper(matrix[14, 14]);
private void Game_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
Maxim.direction = Direction.Up;
}
if (e.KeyCode == Keys.Down)
{
Maxim.direction = Direction.Down;
}
if (e.KeyCode == Keys.Left)
{
Maxim.direction = Direction.Left;
}
if (e.KeyCode == Keys.Right)
{
Maxim.direction = Direction.Right;
}
Maxim.Move();
}
private void Game_Load(object sender, EventArgs e)
{
foreach (Control control in Controls)
{
control.PreviewKeyDown += new PreviewKeyDownEventHandler(control_PreviewKeyDown);
}
}
private void control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) //overrides browsing buttons focus while pressing on arrows keys
{
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
{
e.IsInputKey = true;
}
}
.......//code missing here
private void ResetButton_Click(object sender, EventArgs e)
{
//what do I set here?
}
Just create a new instance of Game. This will give you a whole new set of variables and therefore a new game state.
You need to keep a reference to the game to keep it from being GC'd, so you also need a static variable.
static private Game _currentGame;
private void ResetButton_Click(object sender, EventArgs e)
{
this.Hide();
_currentGame = new Game();
_currentGame.Show();
this.Close();
}

C# - "Pong Game" - Collision with edges of paddle

I dont know how to make ball bounce when hits Paddle´s Top or Bottom, my problem is that the ball goes through the Paddle and then keep going...
So this is the code, some things are in my language so here is translator:
Mustek = Paddle
Mic = Ball
body = Points
HraciPole = Name for graphics array, something like "GameArray"
casovac = name for timer
Kolize = Collision
PohybDolu = MoveUp (bool)
PohybNahoru = MoveDown (bool)
public partial class Form_Pong : Form
{
public static Mustek p1 = new Mustek();
public static Mustek p2 = new Mustek();
public static Mic ball = new Mic();
public int body1 = 0;
public int body2 = 0;
Graphics draw;
public Form_Pong()
{
InitializeComponent();
draw = picBoxHraciPole.CreateGraphics();
}
public static void Draw(Graphics draw)
{
draw.Clear(Color.Black);
draw.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(p1.location, p1.size));
draw.FillRectangle(new SolidBrush(Color.Red), new Rectangle(p2.location, p2.size));
draw.FillRectangle(new SolidBrush(Color.White), new Rectangle(ball.location, ball.size));
}
private void casovac_Tick(object sender, EventArgs e)
{
if (casovac.Interval == 10)
{
p1.location.X = 30;
p1.location.Y = (picBoxHraciPole.Height - p1.size.Height) / 2;
p2.location.X = (picBoxHraciPole.Width - p2.size.Width) - 30;
p2.location.Y = p1.location.Y;
ball.location = new Point(picBoxHraciPole.Width / 2, picBoxHraciPole.Height / 2);
casovac.Interval = 5;
}
Kolize();
Pohyb();
Draw(draw);
}
public void Kolize()
{
if (p1.location.Y < 0)
{
p1.location.Y = 0;
}
if (p1.location.Y + p1.size.Height > picBoxHraciPole.Height)
{
p1.location.Y = picBoxHraciPole.Height - p1.size.Height;
}
if (p2.location.Y < 0)
{
p2.location.Y = 0;
}
if (p2.location.Y + p2.size.Height > picBoxHraciPole.Height)
{
p2.location.Y = picBoxHraciPole.Height - p2.size.Height;
}
if (ball.location.Y < 0)
{
ball.speed.Y = -ball.speed.Y;
}
if (ball.location.Y + ball.size.Height > picBoxHraciPole.Height)
{
ball.speed.Y = -ball.speed.Y;
}
if (ball.location.X < 0)
{
body2 += 1;
labelBody2.Text = body2.ToString();
Reset();
}
if (ball.location.X + ball.size.Width > picBoxHraciPole.Width)
{
body1 +=1;
labelBody1.Text = body1.ToString();
Reset();
}
if (new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p1.location, p1.size)) ||
new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p2.location, p2.size)))
{
ball.speed.X = -ball.speed.X;
}
if (new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p1.location, p1.size)) ||
new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p2.location, p2.size)))
{
}
}
public void Reset()
{
ball.location = new Point(picBoxHraciPole.Width / 2, picBoxHraciPole.Height / 2);
ball.speed.X = -ball.speed.X;
ball.speed.Y = -ball.speed.Y;
}
public static void Pohyb()
{
if (p1.PohybNahoru == true)
{
p1.location.Y -= 8;
}
if (p1.PohybDolu == true)
{
p1.location.Y += 6;
}
if (p2.PohybNahoru == true)
{
p2.location.Y -= 6;
}
if (p2.PohybDolu == true)
{
p2.location.Y += 6;
}
ball.location.X += ball.speed.X;
ball.location.Y += ball.speed.Y;
}
private void Form_Pong_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
p1.PohybNahoru = true;
}
if (e.KeyCode == Keys.S)
{
p1.PohybDolu = true;
}
if (e.KeyCode == Keys.Escape)
{
Application.Exit();
}
if (e.KeyCode == Keys.Up)
{
p2.PohybNahoru = true;
}
if (e.KeyCode == Keys.Down)
{
p2.PohybDolu = true;
}
if (e.KeyCode == Keys.F1)
{
casovac.Enabled = false;
}
if (e.KeyCode == Keys.F2)
{
casovac.Enabled = true;
}
}
private void EnableDoubleBuffering()
{
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
}
private void Form_Pong_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
p1.PohybNahoru = false;
}
if (e.KeyCode == Keys.S)
{
p1.PohybDolu = false;
}
if (e.KeyCode == Keys.Up)
{
p2.PohybNahoru = false;
}
if (e.KeyCode == Keys.Down)
{
p2.PohybDolu = false;
}
}
}
public class Mustek
{
public Point location;
public Size size;
public bool PohybNahoru, PohybDolu;
public int Score;
public Mustek()
{
Score = 0;
size.Width = 25;
size.Height = 125;
}
}
public class Mic
{
public Point location;
public Size size;
public Point speed;
public Mic()
{
speed.X = -5;
speed.Y = 5;
this.size.Width = 25;
this.size.Height = 25;
}
}
The basic logic that you are looking for is
If edge of ball =edge of paddle then change direction so as if x was decreasing bow x is to ve increasing
Once you have that you can work out angles for different conditions such as if it gits the edge of the paddle ect.

Categories

Resources