using System;
using System.Drawing;
using System.Windows.Forms;
public class BouncingBallsForm : Form
{
private const int ContainerWidth = 600;
private const int ContainerHeight = 400;
private const int BallRadius = 20;
private const int BallDiameter = BallRadius * 2;
private const int BallCount = 5;
private const int BallSpeed = 5;
private const int Force = 1;
private Ball[] balls;
public BouncingBallsForm()
{
balls = new Ball[BallCount];
Random random = new Random();
for (int i = 0; i < BallCount; i++)
{
int x = random.Next(BallRadius, ContainerWidth - BallDiameter);
int y = random.Next(BallRadius, ContainerHeight - BallDiameter);
int speedX = random.Next(-BallSpeed, BallSpeed);
int speedY = random.Next(-BallSpeed, BallSpeed);
balls[i] = new Ball(x, y, speedX, speedY);
}
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
DoubleBuffered = true;
Timer timer = new Timer();
timer.Interval = 16;
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
for (int i = 0; i < BallCount; i++)
{
Ball ball = balls[i];
ball.Move();
ball.CheckCollision();
}
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics graphics = e.Graphics;
graphics.Clear(Color.Transparent);
foreach (Ball ball in balls)
{
graphics.FillEllipse(Brushes.Blue, ball.X, ball.Y, BallDiameter, BallDiameter);
}
}
private class Ball
{
public int X { get; private set; }
public int Y { get; private set; }
public int SpeedX { get; private set; }
public int SpeedY { get; private set; }
public Ball(int x, int y, int speedX, int speedY)
{
X = x;
Y = y;
SpeedX = speedX;
SpeedY = speedY;
}
public void Move()
{
X += SpeedX;
Y += SpeedY;
}
public void CheckCollision()
{
if (X <= 0 || X >= ContainerWidth - BallDiameter)
{
SpeedX = -SpeedX + Force;
}
if (Y < 0 || Y >= ContainerHeight - BallDiameter)
{
SpeedY = -SpeedY + Force;
}
}
}
[STAThread]
public static void Main()
{
Application.Run(new BouncingBallsForm());
}
}