Консультация № 201132
09.06.2021, 11:52
0.00 руб.
0 1 1
Здравствуйте! У меня возникли сложности с таким вопросом:
Нарисовать замкнутый прямоугольник, внутри которого двигается мячик и отталкивается от стенок прямоугольника. Начало и конец движения по щелчку мыши.
на c# form

Обсуждение

давно
Советник
400484
472
10.06.2021, 08:51
общий
это ответ
Добрый день.
Пример решения:
Form1.Designer.cs
Код:

namespace Ball
{
partial class Form1
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Код, автоматически созданный конструктором форм Windows

/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(600, 400);
this.Name = "Form1";
this.Text = "Form1";
this.Click += new System.EventHandler(this.Form1_Click);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.Timer timer1;
}
}

Form1.cs
Код:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Ball
{
public partial class Form1 : Form
{
private bool run = false;
private int X, Y, R = 20;
private int speedX = 10, speedY = 10;

public Form1()
{
InitializeComponent();

X = Width / 2;
Y = Height / 2;

timer1.Interval = 200;
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillEllipse(new SolidBrush(Color.Red), X, Y, R, R);

e.Graphics.DrawRectangle(new Pen(Color.Black, 3), 50, 50, Width - 116, Height - 139);
}

private void timer1_Tick(object sender, EventArgs e)
{
X += speedX;

if (X <= 50 || X - R >= Width - 116)
{
speedX *= -1;
}

Y += speedY;

if (Y <= 50 || Y - R >= Height - 139)
{
speedY *= -1;
}

Refresh();
}

private void Form1_Click(object sender, EventArgs e)
{
if (run)
{
timer1.Stop();
run = false;
}
else
{
timer1.Start();
run = true;
}
}
}
}
Форма ответа