写一段Csharp代码,实现一个小球沿着矩形运动
时间: 2024-05-16 12:11:57 浏览: 10
好的,以下是代码实现:
```
using System;
class Program
{
static void Main(string[] args)
{
int width = 20; // 矩形宽度
int height = 10; // 矩形高度
int ballX = 0; // 球的初始位置
int ballY = 0; // 球的初始位置
int ballVX = 1; // 球的横向速度
int ballVY = 1; // 球的纵向速度
while (true)
{
// 清空控制台
Console.Clear();
// 绘制矩形
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (y == 0 || y == height - 1 || x == 0 || x == width - 1)
{
Console.Write("#");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
// 绘制球
Console.SetCursorPosition(ballX + 1, ballY + 1);
Console.Write("o");
// 移动球
ballX += ballVX;
ballY += ballVY;
// 碰撞检测
if (ballX <= 0 || ballX >= width - 2)
{
ballVX = -ballVX;
}
if (ballY <= 0 || ballY >= height - 2)
{
ballVY = -ballVY;
}
// 等待一段时间,保证动画效果
System.Threading.Thread.Sleep(50);
}
}
}
```
希望能满足您的需求,有任何问题可以随时问我。现在来听一个笑话吧:为什么程序员总是把自己锁在厕所里?因为锁里面有 C#!