Holding down a key pauses the timer - c#

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

Related

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.

C# How to make PictureBoxs move automatically?

I created 5 PictureBox "Shapes" and I want them to move to the left automatically when the program is launched. So in the timer1_Tick method, I use "Shapes[i].Left -= 2", it's said that "Shapes" isn't in the actual context, so How can I make the Shapes[i] global from the "CreatePipes" method?
public partial class Form1 : Form
{
int i = 0;
int N = 5;
int yspeed;
int gravity = 2;
public Form1()
{
InitializeComponent();
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
yspeed = -15;
}
}
private void Form1_Load(object sender, EventArgs e)
{
CreatePipes(1);
}
public void CreatePipes(object Number)
{
PictureBox[] Shapes = new PictureBox[N];
for (i = 0; i < N; i++)
{
Shapes[i] = new PictureBox();
Shapes[i].Name = "ItemNum_" + i.ToString();
Shapes[i].Location = new Point(300 + 120 * i, 250);
Shapes[i].Size = new Size(30, 1000 );
Shapes[i].BackColor = Color.Green;
Shapes[i].Visible = true;
this.Controls.Add(Shapes[i]);
}
}
private void bird_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
for (i = 0; i < N; i++)
{
Shapes[i].Left -= 2; //So the problem is here. Shapes[i] isn't in the actual context. But I don't know to to make it global from CreatePipes
}
yspeed += gravity;
bird.Top += yspeed;
}
}
}
You have to declare PictureBox[] Shapes above CreatePipes function, in Form1 class. Then in CreatePipes func, change PictureBox[] Shapes = new PictureBox[N]; to Shapes = new PictureBox[N];

How to move panels up/down on keysDown event in c#

I've 4 panels, having same Y and different X, that are created at the program start on a picturebox. When I click on a panel, it sets the focus and is ready to get a keysDown event so i.e. if I click on up arrow key the panel moves up.
This is the code:
public partial class FormView : Form
{
List<CircleButton> myPanels = new List<CircleButton>(); // array of panels CircleButton
Point[] arrayPoints_milestones; // array of X,Y
int index;
public FormView()
{
InitializeComponent();
arrayPoints_milestones = new Point[4];
for (int i = 0; i < 4; i++ )
{
arrayPoints_milestones[i] = new Point { X = 20, Y = 20 };
}
test();
}
protected void panel_Click(object sender, EventArgs e)
{
myPanels[index].PreviewKeyDown -= new PreviewKeyDownEventHandler(panel_KeyDown);
CircleButton panel = sender as CircleButton;
index = (int)panel.Tag;
myPanels[index].Focus(); //panel.Focus();
myPanels[index].PreviewKeyDown += new PreviewKeyDownEventHandler(panel_KeyDown);
}
private void panel_KeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
myPanels[index].Centre = new Point(myPanels[index].Centre.X, myPanels[index].Centre.Y - 10);
MessageBox.Show("" + myPanels[index].Centre.Y);
Invalidate();
}
if (e.KeyCode == Keys.Down)
{
myPanels[index].Centre = new Point(myPanels[index].Centre.X, myPanels[index].Centre.Y + 10);
MessageBox.Show("" + myPanels[index].Centre.Y);
Invalidate();
}
}
private void test()
{
//for (int i = 0; i < 4; i++)
int i=0;
foreach(var value in arrayPoints_milestones)
{
CircleButton panel = new CircleButton();
panel.Tag = i;
panel.Centre = new Point(arrayPoints_milestones[i].X + i * 10, arrayPoints_milestones[i].Y);
panel.Radius = 10;
panel.BackColor = Color.Red;
panel.Message = "Index: " + panel.Tag.ToString();
myPanels.Add(panel); // qui aggiungo il pannello alla lista di pannelli myPanels
pictureBox1.Controls.Add(myPanels[i]);
myPanels[i].Click += new EventHandler(panel_Click);
i++;
}
}
}
and this is the custom panel class:
public class CircleButton : Panel
{
//Properties to draw circle
float radius;
public float Radius
{
get { return radius; }
set
{
radius = value;
this.Size = new Size((int)Radius, (int)Radius);
}
}
public string Name
{
get;
set;
}
Point centre;
public Point Centre
{
get { return centre; }
set
{
centre = value;
this.Location = Centre;
}
}
public string Message { get; set; }
public CircleButton()
{
//Default Values
Name = "panel_base";
this.BackColor = Color.Black;
Radius = 1;
Centre = new Point(0, 0);
this.DoubleBuffered = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
//Defines a graphic path and set it as the panel's region
//For custom region use different path's
if (centre != null)
{
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, radius, radius);
this.Region = new Region(path);
path.Dispose();
}
}
}
Each time you click a panel, a PreviewKeyDownEventHandler is added - so 3 clicks will trigger 3 (different) eventhandlers with the same invocation target, and each will move your panel for 10 pixels up/down:
protected void panel_Click(object sender, EventArgs e) {
CircleButton panel = sender as CircleButton;
index = (int)panel.Tag;
myPanels[index].Focus(); //panel.Focus();
myPanels[index].PreviewKeyDown += new PreviewKeyDownEventHandler(panel_KeyDown);
}
Updated code for FormView:
public partial class FormView : Form {
List<CircleButton> myPanels = new List<CircleButton>(); // local use only in my example
Point[] arrayPoints_milestones; //not needed anymore
int index; //not needed anymore
public FormView() {
InitializeComponent();
this.Load += FormView_Load;
}
void FormView_Load(object sender, EventArgs args) {
Point panelOffset = new Point(20, 20);
for (int i = 0; i < 4; i++) {
var panel = new CircleButton() {
Name = "panel" + i, //Attention! You have hidden the property "Name" in "Control" with a re-declaration in "CircleButton"
Tag = i, //not needed anymore, right?
Centre = new Point(panelOffset.X + i * 10, panelOffset.Y),
Radius = 10,
BackColor = Color.Red,
Message = "Index: " + i.ToString(),
};
panel.Click += (s, e) => {
panel.Focus();
};
panel.PreviewKeyDown += (s, e) => {
if(e.KeyCode == Keys.Up) {
Point centre = panel.Centre; //copy value
centre.Y -= 10;
panel.Centre = centre; //assign modified copy
Invalidate();
}
if(e.KeyCode == Keys.Down) {
Point centre = panel.Centre; //copy value
centre.Y += 10;
panel.Centre = centre; //assign modified copy
Invalidate();
}
};
myPanels.Add(panel);
pictureBox1.Controls.Add(panel);
}
}
}

C# Keep picturebox in form1

I have a picturebox in windows form application that has the ability to move with arrowkeys. I want it to have certain limits to where it can go, specifically in the form. How do I do this? My class to move the target is below:
namespace AmazingPaintball
{
class Target
{
private Point p;
public Target(Point myPoi)
{
p = myPoi;
}
public Point Move(Keys key)
{
if (key == Keys.Left)
{
p.Offset(-50, 0);
}
else if (key == Keys.Right)
{
p.Offset(50, 0);
}
else if (key == Keys.Up)
{
p.Offset(0, -50);
}
else if (key == Keys.Down)
{
p.Offset(0, 50);
}
return p;
}
}
}
Below is the form1:
namespace AmazingPaintball
{
public partial class Form1 : Form
{
Random positionX = new Random();
Random positionY = new Random();
Target einstein;
int count = 0;
Paintballs pBalls = new Paintballs();
Stopwatch stopwatch = new Stopwatch();
SoundPlayer wavPlayer = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\Resources\singlegunshot.wav");
SoundPlayer wavPlayer2 = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\bin\Debug\Resources\Applause.wav");
public Form1()
{
InitializeComponent();
Point point = new Point(positionX.Next(0, 638), positionY.Next(0, 404));
einstein = new Target(point);
ptrEinstein.Location = point;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pBalls.paint(e.Graphics);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
ptrEinstein.Location = einstein.Move(e.KeyData);
pictureBox1.Update();
pictureBox1.Refresh();
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
wavPlayer.Play();
pBalls.add(e.Location);
pictureBox1.Refresh();
count++;
}
private void Form1_Load(object sender, EventArgs e)
{
stopwatch.Start();
}
private void ptrEinstein_MouseClick(object sender, MouseEventArgs e)
{
count++;
ptrEinstein.Image = Properties.Resources.AlbertEinsteinTongue;
stopwatch.Stop();
wavPlayer2.Play();
MessageBox.Show("It took " + count + " shots and " + stopwatch.Elapsed + " seconds to hit the target");
wavPlayer2.Stop();
ptrEinstein.Image = Properties.Resources.AlbertEinsteinFace;
count = 0;
stopwatch.Reset();
stopwatch.Start();
}
}
}
The picturebox is ptrEinstein and it is able to move in the form1_keydown event.
When you're moving the picture box, first check to make sure where you're moving it to is inside the form. E.g. check if the new X + the width of the picture box is less than the width of the form, etc.
This will be incomplete because we do not have your code, but you should compare the clientSize properties to the picturebox location (taking into account the size of the picturebox):
PictureBox pb = new PictureBox();
int newX = oldX + xOffset; // xOffset is whatever you're incrementing x by
int newY = oldY + yOffset; // yOffset is whatever you're incrementing y by
if (newX < 0) {
newX = 0;
} else if (newX > this.ClientSize.Width - pb.Width) {
newX = this.ClientSize.Width - pb.Width;
}
if (newY < 0) {
newY = 0;
} else if (newY > this.ClientSize.Height - pb.Height) {
newY = this.ClientSize.Height - pb.Height;
}
// New point to move it to
Point newP = new Point(newX, newY);

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