In this tutorial, we are going to make a simple car racing game in the Visual Studio platform with C# language. For this purpose, we will use Visual Studio Winform and c#.
Step 1:
Create New WinForm project via Visual Studio.
Step 2:
namespace CarGame
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
roadsimulate(carspeed);
enemy(carspeed);
gameover();
}
Random r=new Random();
int x;
void enemy(int speed)
{
if (Enemy1.Top>=500)
{
x=r.Next(40,360);
Enemy1.Location = new Point(x, 0);
}
else
{
Enemy1.Top += speed;
}
if (Enemy2.Top >= 500)
{
x = r.Next(40, 360);
Enemy2.Location = new Point(x, 0);
}
else
{
Enemy2.Top += speed;
}
if (Enemy3.Top >= 500)
{
x = r.Next(60, 320);
Enemy3.Location = new Point(x, 0);
}
else
{
Enemy3.Top += speed;
}
if (Enemy4.Top >= 500)
{
x = r.Next(80, 300);
Enemy4.Location = new Point(x, 0);
}
else
{
Enemy4.Top += speed;
}
}
void gameover()
{
if (car.Bounds.IntersectsWith(Enemy1.Bounds))
{
timer1.Enabled = false;
Label_gameover.Visible = true;
}
if (car.Bounds.IntersectsWith(Enemy2.Bounds))
{
timer1.Enabled = false;
Label_gameover.Visible = true;
}
if (car.Bounds.IntersectsWith(Enemy3.Bounds))
{
timer1.Enabled = false;
Label_gameover.Visible = true;
}
if (car.Bounds.IntersectsWith(Enemy4.Bounds))
{
timer1.Enabled = false;
Label_gameover.Visible = true;
}
}
void roadsimulate(int speed)
{
if (pictureBox1.Top >= this.Size.Height)
{
pictureBox1.Top = 0;
}
else
{ pictureBox1.Top += speed; }
if (pictureBox2.Top >= this.Size.Height)
{
pictureBox2.Top = 0;
}
else
{ pictureBox2.Top += speed; }
if (pictureBox3.Top >= this.Size.Height)
{
pictureBox3.Top = 0;
}
else
{ pictureBox3.Top += speed; }
if (pictureBox4.Top >= this.Size.Height)
{
pictureBox4.Top = 0;
}
else
{ pictureBox4.Top += speed; }
if (pictureBox5.Top >= this.Size.Height)
{
pictureBox5.Top = 0;
}
else
{ pictureBox5.Top += speed; }
}
int carspeed = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
if (car.Left > 20)
car.Left += -10;
}
if (e.KeyCode == Keys.Right)
{
if (car.Right < 360)
car.Left += 10;
}
if (e.KeyCode == Keys.Up)
{
if (carspeed < 18) { carspeed++; }
}
if (e.KeyCode == Keys.Down)
{
if (carspeed > 0) { carspeed--; }
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Step 3:
Comments
Add comment