Tutorial para programar el clásico juego ping pong en C# .net
En esta ocasión les traigo un pequeño tutorial que me solicitó una persona hace unos días. los pasos son:
1. Crear una nueva solución y agregar un proyecto Windows Form Application en el lenguaje C#
2. Agregar una forma, o usar la que viene por defecto al crear el proyecto. y arrastrar los siguientes controles:
1. Crear una nueva solución y agregar un proyecto Windows Form Application en el lenguaje C#
2. Agregar una forma, o usar la que viene por defecto al crear el proyecto. y arrastrar los siguientes controles:
- 2 Buttons
- 2 Labels
- 1 RadioButton
- 1 Timer
El diseño es el siguiente:
Explicación del diseño;
- Los 2 botones serán el player 1 y player 2 respectivamente, darle color con la propiedad backcolor(opcional) y nombres reconocibles "Player1, Player2".
- Los 2 Labels serán las puntuaciones del player 1 y player 2 respectivamente, darle nombres "PuntajePlayer1 y PuntajePlayer2".
- El RadioButton será nuestra pelota, dejar en blanco la propiedad text, centrarla y darle nombre "ball".
- El Timer, establecer la propiedad Interval en 10 (velocidad en que la pantalla se va a refrescar)
3. Crear eventos:
//variables que obtiene y establece la dirección de movimiento de la bola
Boolean moverBolaALaIzquierda;
Boolean moverArriba;
//variable que obtiene y establece la posición de la bola
Point posicionBola;
//variable que establece la rapidez del movimiento de la bola
//en los ejes X y Y
int speedX = 5;
int speedY = 5;
//variable que indica la puntuación máxima a obtener para terminar el juego
int meta = 3;
private void FormPingPong_Load(object sender, EventArgs e)
{
this.KeyPreview = true; //Permite disparar el evento keypress del form sin tener el foco
IniciaJuego();
}
private void FormPingPong_KeyPress(object sender, KeyPressEventArgs e)
{
switch ((e.KeyChar).ToString().ToUpper())
{
case "S":
Player1.Top += 20;
break;
case "W":
Player1.Top -= 20;
break;
}
}
private void FormPingPong_MouseMove(object sender, MouseEventArgs e)
{
Player2.Top = e.Y;
}
private void IniciaJuego()
{
PuntajePlayer2.Text = "0";
PuntajePlayer1.Text = "0";
//centra la bola
posicionBola = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2);
timer1.Enabled = true;
}
private void TerminaJuego()
{
timer1.Enabled = false;
if (MessageBox.Show(this.PuntajePlayer1.Text + " - " + PuntajePlayer2.Text + " Quieres jugar de nuevo?", "Fin del juego",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
IniciaJuego();
}
else
{
this.Close();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
//Player 1 anota, cada vez que anota se incrementa en 1 su puntaje
if (ball.Location.X >= this.Size.Width - ball.Size.Width - 15)
{
PuntajePlayer1.Text = Convert.ToString(Convert.ToInt32(PuntajePlayer1.Text) + 1);
if (Convert.ToInt32(PuntajePlayer1.Text) >= meta)
{
TerminaJuego();
}
else
{
moverBolaALaIzquierda = true;
}
}
//Player 2 anota
if (ball.Location.X <= 0)
{
PuntajePlayer2.Text = Convert.ToString(Convert.ToInt32(PuntajePlayer2.Text) + 1);
if (Convert.ToInt32(PuntajePlayer2.Text) >= meta)
{
TerminaJuego();
}
else
{
moverBolaALaIzquierda = false;
}
}
//bola rebota en Player 1
//If (ball.Location.Y >= Player1.Location.Y And ball.Location.Y <= (Player1.Location.Y + Player1.Size.Height)) And ball.Location.X <= (Player1.Location.X + Player1.Size.Width) Then
if ((ball.Location.Y >= Player1.Location.Y && ball.Location.Y <= (Player1.Location.Y + Player1.Size.Height)) && ball.Location.X <= (Player1.Location.X + Player1.Size.Width))
{
moverBolaALaIzquierda = false;
}
//bola rebota en Player 2
if ((ball.Location.Y >= Player2.Location.Y && ball.Location.Y <= (Player2.Location.Y + Player2.Size.Height)) && ball.Location.X >= (Player2.Location.X - Player2.Size.Width + 10))
{
moverBolaALaIzquierda = true;
}
//mueve la bola en el eje de las X
if (moverBolaALaIzquierda == true)
{
posicionBola.X = posicionBola.X - speedX; //se mueve a la izquierda
}
else
{
posicionBola.X = posicionBola.X + speedX; //se mueve a la derecha
}
//Pregunta si la bola va a rebotar hacia arriba
if (ball.Top >= this.Size.Height - ball.Size.Height - 30)
{
moverArriba = true;
}
//Pregunta si la bola va a rebotar hacia abajo
if (ball.Top <= 0)
{
moverArriba = false;
}
if (moverArriba == true)
{
posicionBola.Y = posicionBola.Y - speedY;
}
else
{
posicionBola.Y = posicionBola.Y + speedY;
}
ball.Location = posicionBola;
}
Algo importante a recalcar es la propiedad KeyPreview de la forma, debe establecerse en true para que el juego funcione correctamente (ver el evento load del form).
6. Correr la aplicación y jugar. Debe quedar algo como esto:


Para usar hilos en los 2 jugadores, cómo sería la estructura del código
ResponderEliminarTutorial Ping Pong En .Net >>>>> Download Now
ResponderEliminar>>>>> Download Full
Tutorial Ping Pong En .Net >>>>> Download LINK
>>>>> Download Now
Tutorial Ping Pong En .Net >>>>> Download Full
>>>>> Download LINK DA