Moving PictureBox in C# - c#

Could someone help me?
I really don't know what to do. I don't want to restart my project even if there is little code inside it don't ask me why. Maybe because Im lazy. I think it is probably problems with the varibels I guess. As I said I don't know.
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;
namespace Project_Zomboid
{
public partial class Form1 : Form
{
int positiony = 0;
int positionx = 0;
public Form1()
{
InitializeComponent();
player.Controls.Add(ak47gun);
ak47gun.Location = new Point(0, 0);
ak47gun.BackColor = Color.Transparent;
Startup();
player.Location = new Point(positionx, positiony);
}
void Startup()
{
if (true == true)
{
}
}
private void keypress(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.W)
{
positiony += 1;
}
else if(e.KeyCode == Keys.S)
{
positiony -= 1;
}
else if (e.KeyCode == Keys.D)
{
positionx += 1;
}
else if( e.KeyCode == Keys.A)
{
positionx -= 1;
}
}
}
}

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;
namespace Project_Zomboid
{
public partial class Form1 : Form
{
int positiony = 0;
int positionx = 0;
Thread gameLoop;
public Form1()
{
InitializeComponent();
player.Controls.Add(ak47gun);
ak47gun.Location = new Point(0, 0);
ak47gun.BackColor = Color.Transparent;
gameLoop = new Thread(new ThreadStart(Startup));
gameLoop.Start();
}
public void Startup()
{
while(true)
{
player.Location = new Point(positionx, positiony);
Thread.Sleep(128);
}
}
private void keypress(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.W)
{
positiony += 1;
}
else if(e.KeyCode == Keys.S)
{
positiony -= 1;
}
else if (e.KeyCode == Keys.D)
{
positionx += 1;
}
else if( e.KeyCode == Keys.A)
{
positionx -= 1;
}
}
}
}
I think that will get your image moving around the screen but, I would seriously suggest if you're interested in making games you should consider watching a lot of tutorials online on youtube. This movement isn't time sensitive so your picture will move as fast as the cpu can add to the x or y position. Which should be really fast. The sleep in the thread is to make sure your picture isn't always updating. I would first suggest a tutorial that explains delta time and velocity.
There are also a TON of free example games online that can give you a great example of how a lot of this is done.
Something else to note is if you don't want a game loop/thread update the player.Location = new Point(positionx, positiony) inside the keypress method after updating the integer.

Related

Why does my Picture Box move to the top of the form?

So within my program, I want an object to move left or right depending on what arrow key is held down. I moved the the picture box on the bottom of them form so when any of the two arrow keys are pressed they would move along the bottom. But what's happening is when I press either key, the picture box goes to the top and moves left and right there. I don't know why this is.
Here's the code for the Form1, ignore the code for Form2; that's for experimentation purpose right now:
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;
namespace Move
{
public partial class Form1 : Form
{
public int lives = 0;
Form2 menu = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_KeyDown(object sender, KeyEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int i;
for (i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
pictureBox1.Location = new Point(pictureBox1.Left - 1);
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
if (e.KeyCode == Keys.Right)
{
pictureBox1.Location = new Point(pictureBox1.Left + 1);
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
var rect1 = new System.Drawing.Rectangle(pictureBox1.Location, pictureBox1.Size);
var rect2 = new System.Drawing.Rectangle(pictureBox2.Location, pictureBox2.Size);
if (rect1.IntersectsWith(rect2))
{
MessageBox.Show("Game Over!");
System.Threading.Thread.Sleep(1000);
Application.Exit();
}
if (e.KeyCode == Keys.Down)
{
this.Hide();
menu.Show();
}
}
}
}
}
Use
pictureBox1.Location = new Point(pictureBox1.Left - 1, pictureBox1.Top);
and
pictureBox1.Location = new Point(pictureBox1.Left + 1, pictureBox1.Top);
respectively to specify the currently used Y coordinate.
When using the constructor of Point that takes only one value, the system expects this one value to contain both the X and Y coordinates (As higher and lower word of the value) and will use 0 for the Y coordinate because the X values you use are so low that the higher word of the value is 0.

C# removing an object Completely(no collision)

I am making a brick break game in c# windows form in which I need to remove a picture box when the ball(picture box) collide with it........
I have tried hide, dispose remove control and even making it equal to null but all of them just hide it and doesn't make it vanished completely means that there is still collision.....
here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication20
{
public partial class Form1 : Form
{
public int spx =10;
public int spy = 10;
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
Cursor.Hide();
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.Bounds = Screen.PrimaryScreen.Bounds;
paddle.Top = background.Bottom - (background.Bottom / 10);
if(paddle.Left > background.Left)
{
paddle.Left += 0;
}
}
private void Form1_ControlRemoved(object sender, ControlEventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
ball.Left += spx;
ball.Top += spy;
paddle.Left = Cursor.Position.X - (paddle.Left / Width);
if(ball.Left <= background.Left)
{
spx = -spx;
}
if (ball.Right >= background.Right)
{
spx = -spx;
}
if (ball.Top <= background.Top)
{
spy = -spy;
}
if (ball.Bottom >= background.Bottom)
{
spy = -spy;
}
if (paddle.Top <= ball.Bottom && paddle.Top >= ball.Top && ball.Left >= paddle.Left && ball.Right <= paddle.Right)
{
spy = -spy;
}
if (pictureBox.Top <= ball.Bottom && pictureBox.Bottom >= ball.Top && ball.Left <= pictureBox.Right && ball.Right >= pictureBox.Left)
{
spy = -spy;
background.Controls.Remove(pictureBox);
pictureBox = null;
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
}
}
Your code that checks for collisions is hard-coded to look at pictureBox. Making it invisible doesn't change that.
If you want to use the Visible property of pictureBox to hide it, then you should change those if conditions to ignore it if it isn't visible:
if (pictureBox.Visible && (pictureBox.Top <= ball.Bottom && pictureBox.Bottom >= ball.Top && ball.Left <= pictureBox.Right && ball.Right >= pictureBox.Left))
{
spy = -spy;
pictureBox.Visible = false;
}

My MessageBox.Show Code In C# Isn't Working. There Are No Errors But Something Is Wrong

So I have recently been trying to learn C#, so I thought I'd try I simple project such as Tic-Tac-Toe. I am currently trying to add click functionality so to make sure it is working I put in a MessageBox.Show to make sure it new which area I was clicking. However, when I ran it no errors appeared and yet when I clicked on a box nothing happened. Does anyone know what is wrong with my code? Is it a problem with the MessageBox.Show code or with something else? Here is my code:
In a Board.cs file I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Board
{
private Rectangle[,] slots = new Rectangle[3, 3];
private Holder[,] holders = new Holder[3, 3];
public const int X = 0;
public const int O = 1;
public const int B = 2;
public void initBoard()
{
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
slots[x, y] = new Rectangle(x * 167, y * 167, 167, 167);
holders[x, y] = new Holder();
holders[x, y].setValue(B);
holders[x, y].setLocation(new Point(x, y));
}
}
}
public void detectHit(Point loc)
{
int x = 0;
int y = 0;
if (loc.X < 167)
{
x = 0;
}
else if (loc.X > 167 && loc.X < 334)
{
x = 1;
}
else if (loc.X > 334)
{
x = 2;
}
if (loc.Y < 167)
{
y = 0;
}
else if (loc.Y > 167 && loc.Y < 334)
{
y = 1;
}
else if (loc.Y > 334 && loc.Y < 500)
{
y = 2;
}
MessageBox.Show(x.ToString() + ", " + y.ToString() + "/n/n" + loc.ToString());
}
}
class Holder
{
private Point location;
private int value = Board.B;
public void setLocation(Point p)
{
location = p;
}
public Point getLocation()
{
return location;
}
public void setValue(int i)
{
value = i;
}
public int getValue()
{
return value;
}
}
}
Then in my Form1.cs file I have:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
GFX engine;
Board theBoard;
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics toPass = panel1.CreateGraphics();
engine = new GFX(toPass);
theBoard = new Board();
theBoard.initBoard();
}
private void Form1_Click(object sender, EventArgs e)
{
Point mouse = Cursor.Position;
mouse = panel1.PointToClient(mouse);
theBoard.detectHit(mouse);
}
}
}
Based on the name of your event handler (Form1_Click), I suspect you've got the click event handler hooked up to your form's click event instead of panel1's click event. Note that if a user clicks a panel inside your form then only the panel's click event will fire, not the form's.
You may not have the event registered. Try registering it in the constructor:
public Form1()
{
InitializeComponent();
//Register click event with handler
this.Click += new EventHandler(Form1_Click);
}
The only explanation that makes any sense is that Form1_Click is not running. If it was executed then detectHit would definitely run. And MessageBox.Show would definitely be called. There are no execution branches that avoid MessageBox.Show being shown. The only possible way for MessageBox.Show not to be called in the event of Form1_Click executing is for an exception to be raised. In which case you would have noticed that.
Either the event handler is not hooked up at all. Or it is hooked up to the form's Click event but you are clicking on the panel rather than the form.

Stack Overflow Exception (C#)

I'm currently working on a Snake game that can solve itself, but when I activate it, usually after 30~ successful hits, my application crashes with the aforementioned exception either in System.drawing.dll or in System.Windows.Forms.dll.
The problem usually occurs in the command "Application.DoEvents()", but it has occured in several other places too.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Threading;
using System.IO;
namespace Snake
{
enum Directions
{
Right = 1,
Left = -1,
Up = 2,
Down = -2,
NoDirection = 0
}
public partial class GameForm : Form
{
#region Data Members
SnakeGame gmGame;
Point pCurrFood;
Directions dirFirstDirection;
Directions dirSecondDirection;
Directions dirHelpDirection;
Color DEFAULT_COLOUR = Color.White;
const int SEGMENT_HEIGHT = 10;
const int SEGMENT_WIDTH = 10;
#endregion
#region Ctor
public GameForm()
{
InitializeComponent();
this.gmGame = new SnakeGame();
this.dirFirstDirection = Directions.NoDirection;
this.dirSecondDirection = Directions.NoDirection;
}
#endregion
#region Other Methods
private void PaintSegment(Graphics gGraphics, Point pnPoint, Color cColour)
{
Pen Pen = new Pen(cColour);
Rectangle Rectangle = new Rectangle(pnPoint.X,
pnPoint.Y,
SEGMENT_HEIGHT,
SEGMENT_WIDTH);
gGraphics.DrawRectangle(Pen, Rectangle);
Brush Brush = new SolidBrush(cColour);
gGraphics.FillRectangle(Brush, Rectangle);
}
private void PlaceNewFood()
{
Random rRand = new Random();
int nHeight = rRand.Next(this.panel1.Size.Height);
int nWidth = rRand.Next(this.panel1.Size.Width);
while ((nHeight % 10 != 0) || (nWidth % 10 != 0))
{
nHeight = rRand.Next(this.panel1.Size.Height - 10);
nWidth = rRand.Next(this.panel1.Size.Width - 10);
while (this.gmGame.SnakeQueue.Contains(new Point(nWidth, nHeight)))
{
nHeight = rRand.Next(this.panel1.Size.Height);
nWidth = rRand.Next(this.panel1.Size.Width);
}
}
this.pCurrFood = new Point(nWidth, nHeight);
this.PaintSegment(this.panel1.CreateGraphics(), this.pCurrFood, Color.Red);
}
private void SelfSolve()
{
this.dirFirstDirection = (Directions)(Math.Sign(this.gmGame.SnakeHead.Y -
this.pCurrFood.Y) * 2);
this.dirSecondDirection = (Directions)Math.Sign(this.pCurrFood.X -
this.gmGame.SnakeHead.X);
this.ManageSnake(this.dirFirstDirection, this.dirSecondDirection);
}
private bool WillCollide(Point pnPointToCheck)
{
return ((pnPointToCheck.X > this.panel1.Size.Width) ||
(pnPointToCheck.Y > this.panel1.Size.Height) ||
(pnPointToCheck.X * pnPointToCheck.Y < 0) ||
(this.gmGame.SnakeQueue.Contains(pnPointToCheck)));
}
private void ManageSnake(Directions dirFirstSnakeDirection,
Directions dirSecondSnakeDirection)
{
Point pnNewHead = this.gmGame.SnakeHead;
switch (dirFirstSnakeDirection)
{
case (Directions.Down):
{
if (this.WillCollide(new Point(pnNewHead.X, pnNewHead.Y + SEGMENT_HEIGHT)))
{
this.ManageSnake(Directions.NoDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.Y += SEGMENT_HEIGHT;
dirHelpDirection = Directions.Down;
}
break;
}
case (Directions.Up):
{
if (this.WillCollide(new Point(pnNewHead.X, pnNewHead.Y - SEGMENT_HEIGHT)))
{
this.ManageSnake(Directions.NoDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.Y -= SEGMENT_HEIGHT;
dirHelpDirection = Directions.Up;
}
break;
}
case (Directions.NoDirection):
{
switch (dirSecondSnakeDirection)
{
case (Directions.Right):
{
if (this.WillCollide(new Point(pnNewHead.X + SEGMENT_WIDTH, pnNewHead.Y)))
{
this.ManageSnake(this.dirHelpDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.X += SEGMENT_WIDTH;
}
break;
}
case (Directions.Left):
{
if (this.WillCollide(new Point(pnNewHead.X - SEGMENT_WIDTH, pnNewHead.Y)))
{
this.ManageSnake(this.dirHelpDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.X -= SEGMENT_WIDTH;
}
break;
}
}
break;
}
}
this.gmGame.AddSegment(pnNewHead);
if (this.gmGame.SnakeHead.Equals(this.pCurrFood))
{
this.lblScoreNum.Text = (int.Parse(this.lblScoreNum.Text) + 1).ToString();
this.PlaceNewFood();
}
else
{
this.PaintSegment(this.panel1.CreateGraphics(),
(Point)this.gmGame.SnakeQueue.Peek(),
DEFAULT_COLOUR);
this.gmGame.RemoveSegment();
}
this.PaintSegment(this.panel1.CreateGraphics(),
this.gmGame.SnakeHead,
Color.Green);
Thread.Sleep(5);
Application.DoEvents();
this.SelfSolve();
}
#endregion
#region Events
private void GameForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.PlaceNewFood();
this.SelfSolve();
}
else if (e.KeyCode == Keys.Escape)
{
this.Close();
}
else if (e.KeyCode == Keys.Space)
{
MessageBox.Show("Frozen, press OK to continue");
}
}
private void GameForm_ClientSizeChanged(object sender, EventArgs e)
{
this.PaintSegment(this.panel1.CreateGraphics(), new Point(210, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(220, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(230, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(240, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(250, 250), Color.Green);
}
#endregion
}
}
I know it's a lot of code, but since I'm not sure where's the root of the problem, I had to copy all of it.
I'd greatly appreciate it if you could point me in the right direction.
Thanks in advance :)
P.S. I know that the algorithm has flaws, I'll get to that later. Right now my main concern is solving the crash.
This is because you keep on going recursive in your method. e.g.:
Thread.Sleep(5);
Application.DoEvents();
this.SelfSolve();
Your method will basically never end.
You should use a timer and within that timer, call SelfSolve() This should solve your problem.
When using a timer you dont have to call DoEvents yourself since a winforms timer anyways posts a call to your method as a message and the message loop will handle the invocation and other messages.
SelfSolve should not call ManageSnake directly, but rather schedule its run for some later moment. Otherwise you get infinite recursion SelfSolve -> ManageSnake -> SelfSolve etc.

Cannot get laser to fire in 2D space invaders like game

Recently I've been working on a Space Invaders like game, to help me boost my programming Skills. I've fallen into a few problems. I've been researching for a few days now, in how you would go about making a laser fire, on keyUp.
This is my attempt so far; I can get the laser to fire, but it has stumbled me why the laser doesn't carry on moving up...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SpaceInvaders
{
public partial class Form1 : Form
{
public int spriteX = 226;
public int spriteY = 383;
bool bulletFire = false;
int fireTimer = 8;
int laserFired;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
public void laserFire()
{
//on laser fire i wont the bulle to move up while bullet timer is enabled
//moving up slowly with set intervals
while (bulletTimer.Enabled == true)
{
PictureBox laser = new PictureBox();
laser.BackColor = Color.Chartreuse;
laser.Width = 5;
laser.Height = 30;
laserFired = spriteY;
laserFired = laserFired - 10;
this.Controls.Add(laser);
laser.Location = new Point(spriteX, laserFired);
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//Fire bullet
if (e.KeyCode == Keys.Up)
{
bulletFire = true;
if (bulletFire == true)
{
laserFire();
bulletTimer.Enabled = true;
}
}
//Controls Right movement
if (spriteX <448)
{
if (e.KeyCode == Keys.Right)
{
spriteX = spriteX + 20;
}
}
//Controls Left Movement
if (spriteX > 0)
{
if (e.KeyCode == Keys.Left)
{
spriteX = spriteX - 20;
}
}
//Points sprite to new location
pctSprite.Location = new Point(spriteX, spriteY);
}
private void bulletTimer_Tick(object sender, EventArgs e)
{
if (fireTimer == 0)
{
bulletTimer.Enabled = false;
}
else { fireTimer = fireTimer - 1; }
}
}
}
Help or advice would be much appreciated thanks.
The problem you have is that on every iteration of the loop, you reset the y position of the bullet by writing laserFired = spriteY;
However, once that is corrected, you will run into another problem: the while loop that moves the laser bullet is only executed in the laserFire method. This means that:
While the laser bullet moves, nothing else can move (because the loop only moves the laser)
Once the laser bullet stops moving, it will never start moving again (because you cannot go back into the loop without calling laserFire() again.
You need to have a single game loop that moves everything in your game, instead of having one loop for every moving object.
Your timer handler simply decrements fireTimer until it's zero. What instigates a re-rendering of the laser? Something needs to invoke laserFire to re-render the laser. Perhaps you meant to call laserFire from bulletTimer_Tick?

Categories

Resources