Reset button in a c# game [closed] - c#

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();
}

Related

Holding down a key pauses the timer

I have an astro game with 2 picture boxes. One with a fireball(asteroid), and another with a UFO. I am moving the UFO with left and right key, handeled in keydown event. The asteroid falls from top to bottom. I am changing Y coordinate in a timer tick event. My problem is that if I hold down a key, the asteroid stops from falling and starts again as soon as I release the key.
UFOpictureBox is 100,100 picture box
Form Class
public partial class Form1 : Form
{
int hearts = 3, score = 0;
Point pozitieUFO, pozitieAsteroid;
Asteroid asteroid = new Asteroid();
Random random = new Random();
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
KeyPreview = true;
pozitieUFO = UFOpictureBox.Location;
}
private void startBtn_Click(object sender, EventArgs e)
{
hearts = 3;
score = 0;
gameOverLabel.Visible = false;
startBtn.Visible = false;
exitBtn.Visible = false;
Controls.Add(asteroid);
pozitieAsteroid = asteroid.Location;
asteroidTimer.Start();
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Left) pozitieUFO.X -= 10;
if (pozitieUFO.X <= 12) pozitieUFO.X = 12;
if (e.KeyData == Keys.Right) pozitieUFO.X += 10;
if (pozitieUFO.X >= 792) pozitieUFO.X = 792;
UFOpictureBox.Invalidate();
UFOpictureBox.Location = pozitieUFO;
}
private void asteroidTimer_Tick(object sender, EventArgs e)
{
pozitieAsteroid.Y += score/5 + 5;
if (pozitieAsteroid.Y > 420)
{
hearts--;
heartsLabel.Text = "Hearts: " + hearts;
if (hearts <= 0)
{
gameOver();
return;
}
pozitieAsteroid.Y = 1;
pozitieAsteroid.X = random.Next(12, 792);
}
if (asteroid.Bounds.IntersectsWith(UFOpictureBox.Bounds))
{
pozitieAsteroid.Y = 1;
pozitieAsteroid.X = random.Next(12, 792);
score++;
scoreLabel.Text = "Score: " + score;
}
asteroid.Invalidate();
asteroid.Location = pozitieAsteroid;
}
private void gameOver()
{
startBtn.Visible = true;
exitBtn.Visible = true;
gameOverLabel.Visible = true;
asteroidTimer.Stop();
}
}
Asteroid Class
class Asteroid : PictureBox
{
Random random = new Random();
public Asteroid()
{
Width = Height = 50;
SizeMode = PictureBoxSizeMode.StretchImage;
BackColor = Color.Transparent;
Image = Properties.Resources.fire;
Left = random.Next(12,792);
Top = 0;
}
}

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.

How do I move an object using a timer and the key press event (Like snake)

I want to move a button automatically using a timer and want it to change direction when another key is pressed, kinda like what happens in snake
I have used a string to set what the direction should be, but this doesn't work.
string x = "right";
public Form1()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Start();
}
private void Player_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
string x = "up";
}
else if (e.KeyCode == Keys.S)
{
string x = "down";
}
else if (e.KeyCode == Keys.D)
{
string x = "right";
}
else if (e.KeyCode == Keys.A)
{
string x = "left";
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Timer1_Tick(object sender, EventArgs e)
{
while (x == "up")
{
Player.Top -= 10;
}
while (x == "down")
{
Player.Top += 10;
}
while (x == "right")
{
Player.Left += 10;
}
while (x == "left")
{
Player.Left -= 10;
}
}
}
The button just disappears, but I want it to move by ten until it gets a key press like "D" then it changes direction
1: You are creating variable 'x' every time means locally in player_keyDown event so create it globally.
2: you are using while loop it, not needed as you are already using timer_tick.
3: Instead of Top, Left use Location property of button it gives you X, Y co-ordinate
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Start();
}
string x = "right";
private void Player_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
x = "up";
}
else if (e.KeyCode == Keys.S)
{
x = "down";
}
else if (e.KeyCode == Keys.D)
{
x = "right";
}
else if (e.KeyCode == Keys.A)
{
x = "left";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (x == "up")
{
Player.Location = new System.Drawing.Point(Player.Location.X, Player.Location.Y - 10);
}
if (x == "down")
{
Player.Location = new System.Drawing.Point(Player.Location.X, Player.Location.Y + 10);
}
if (x == "right")
{
Player.Location = new System.Drawing.Point(Player.Location.X + 10, Player.Location.Y);
}
if (x == "left")
{
Player.Location = new System.Drawing.Point(Player.Location.X - 10, Player.Location.Y);
}
}
}

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.

Keys do not work while using Keys.Down (Or up, left, right)

I am a beginner at C# (C Sharp) and I couldn't figure out why my Arrow keys would not work. Can anyone help me? Note: I am a beginner, I have been working at this for a while now and I can't figure it out. I have tried researching it with no luck, I hope I don't bother you. When I try and move it it doesn't work.
Here is my Form1
public partial class Form1 : Form
{
Graphics paper;
Snake snake = new Snake();
bool left = false;
bool right = false;
bool down = false;
bool up = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
paper = e.Graphics;
snake.drawSnake(paper);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Down && up == false)
{
down = true;
up = false;
right = false;
left = false;
}
if (e.KeyData == Keys.Up && down == false)
{
down = false;
up = true;
right = false;
left = false;
}
if (e.KeyData == Keys.Right && left == false)
{
down = false;
up = false;
right = true;
left = false;
}
if (e.KeyData == Keys.Left && right == false)
{
down = false;
up = false;
right = false;
left = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (down) { snake.moveDown(); }
if (up) { snake.moveUp(); }
if (right) { snake.moveRight(); }
if (left) { snake.moveLeft(); }
this.Invalidate();
}
}
}
Here is my Snake class if you need it.
{
public Snake()
{
snakeRec = new Rectangle[3];
brush = new SolidBrush(Color.Blue);
x = 20;
y = 0;
width = 10;
height = 10;
for(int i = 0; i < snakeRec.Length; i++)
{
snakeRec[i] = new Rectangle(x, y, width, height);
x -= 10;
}
}
public void drawSnake(Graphics paper)
{
foreach (Rectangle rec in snakeRec)
{
paper.FillRectangle(brush, rec);
}
}
public void drawSnake()
{
for (int i = snakeRec.Length - 1; i > 0; i--)
{
snakeRec[i] = snakeRec[i - 1];
}
}
public void moveDown()
{
drawSnake();
snakeRec[0].Y += 10;
}
public void moveUp()
{
drawSnake();
snakeRec[0].Y -= 10;
}
public void moveRight()
{
drawSnake();
snakeRec[0].X += 10;
}
public void moveLeft()
{
drawSnake();
snakeRec[0].X -= 10;
}
}
}
I tried your code and it works well, so this is the only thing I can think of:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
Make sure that big guy is enabled.
Don't hold on to the Graphics from the Paint() event like that. Just pass e.Graphics directly to your Draw() method like this:
private void Form1_Paint(object sender, PaintEventArgs e)
{
snake.drawSnake(e.Graphics);
}
Also, make sure the Paint() event of the Form is wired up. Select the Form. Now click the "Lightning" Bolt" icon in the Properties Pane (bottom right by default). Find the Paint entry and change the dropdown to the right to "Form1_Paint".

Categories

Resources