I am working on a pong game using c# and gdi+. here is my code so far.
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 winpong
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
int move = 0;
float comp_move = 0.0f, comp_velocity = 1.0f, screen_height = 250.0f, flag = 0.0f;
public void Form1_KeysDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)//key up
{
move-=5;
if (move <= -250)
{
move = -250;
}
}
if (e.KeyCode == Keys.Down)//key down
{
move+=5;
if(move >= 210)
{
move = 210;
}
}
Invalidate();
}
private void timer1_Tick(object sender, EventArgs e)
{
comp_velocity = (comp_move < screen_height && flag == 0.0f) ? (comp_velocity = 5.0f) : (comp_velocity = -5.0f);
comp_move = (comp_velocity == 5.0f) ? (comp_move += 5.0f) : (comp_move -= 5.0f);
if(comp_move >= screen_height-40.0f)
{
flag = 1.0f;
}
if(comp_move <= -screen_height)
{
flag = 0.0f;
}
Invalidate();
}
float x = 0.0f, y = 0.0f, xstep = 5.0f, ystep = 5.0f;
private void timer2_Tick(object sender, EventArgs e)
{
if (x >= 395.0f || x <= -390.0f)
{
xstep = -xstep;
}
if (y >= 270.0f || y <= -290.0f)
{
ystep = -ystep;
}
x += xstep;
y += ystep;
Invalidate();
}
public void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
SolidBrush blueBrush = new SolidBrush(Color.Blue);
SolidBrush redBrush = new SolidBrush(Color.Red);
SolidBrush whiteBrush = new SolidBrush(Color.White);
RectangleF rect1 = new RectangleF(0, 250 + comp_move, 35, 100); //blue paddle
Rectangle rect2 = new Rectangle(750, 250 + move, 35, 100); //red paddle
RectangleF rect3 = new RectangleF(390+x, 290+y, 10, 10); //white ball
g.FillRectangle(blueBrush, rect1);
g.FillRectangle(redBrush, rect2);
g.FillRectangle(whiteBrush, rect3);
g.Dispose();
}
}
}
I am almost done with my pong game all I have to do is implement the scoring algorithm.