Search
Write a publication
Pull to refresh

Создание игры Ping-Pong на C# и .NET

Вступление


Привет, Хабр! В среде .NET есть компонент Graphics. Он позволяет рисовать в .NET форме.
Сегодня я расскажу о создании игры Пинг-Понг на C#.

Для начала немного истории о самой игре. Игра был сделана компанией Atari в 1972 году.
Цель игрока отбивать мяч и не промахнуться.

image

Создание проекта и формы


Создаём новый проект и выбираем Windows Application. Создаётся файл program.cs и MainForm.cs.

Нам нужен MainForm.cs. На форму нужно добавить компонент Label и спрятать его путём установления параметра Visible в значение False.

image

Начинаем писать код


Для начала нужно создать следующие поля:

Graphics graphics;
Timer timer = new Timer();
		
int FPS = 60;
int player1y;
		
int ballx;
int bally;
int ballspdx = 3;
int ballspdy = 3;

После зададим значения переменных:

public MainForm()
{
	InitializeComponent();
			
	timer.Enabled = true;
        timer.Interval = 1000 / FPS;
        timer.Tick += new EventHandler(TimerCallback);
        	
        ballx = this.Width / 2 - 10;
        bally = this.Height / 2 - 10;
}

Теперь создадим объект Graphics:

//Creating grahics object
void MainFormPaint(object sender, PaintEventArgs e)
{
	graphics =  CreateGraphics();
	DrawRectangle(0,player1y,20,130,new SolidBrush(Color.Black));
	DrawRectangle(ballx,bally,20,20,new SolidBrush(Color.Black));
}	

Теперь займёмся игроком и отслеживанием клавиатуры.

//Method for drawing rectangles
void DrawRectangle(int x, int y, int w, int h, SolidBrush Color){
	graphics.FillRectangle(Color, new Rectangle(x,y,w,h));
}
	
//Ball border check	
void UpdateBall(){
	ballx += ballspdx;
	bally += ballspdy;
			
	if(ballx + 40 > this.Width){
		ballspdx = -ballspdx;
	}

	if(bally < 0 || bally + 40 > this.Height){
		ballspdy = -ballspdy;
	}
			
	if(IsCollided()){
		ballspdx = -ballspdx;
	}
			
	if(ballx < 0){
		label1.Visible = true;
		timer.Stop();
	}
}
		
//Player and Ball collision
bool IsCollided(){
	if(ballx < 20 && bally > player1y && bally < player1y + 130){
		return true;
	} else {
		return false;
	}
}

//Update graphics
void TimerCallback(object sender, EventArgs e)
{
        //Draw
	DrawRectangle(0,player1y,20,130,new SolidBrush(Color.Black));
	DrawRectangle(ballx,bally,20,20,new SolidBrush(Color.Black));
	UpdateBall();
			
	this.Invalidate();
	return;
}		

//Keydown event
void MainFormKeyDown(object sender, KeyEventArgs e)
{
	int key = e.KeyValue;
        //38 - up arrow
        //40 - down arrow
	if(key == 38){ 
		player1y -= 5; //5 - moving speed
	}

	if(key == 40){
		player1y += 5; //5 - moving speed
	}
}

Весь код и проект тут.

Результат


image

image
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.