Console.ForegroundColor = ConsoleColor.Yellow; //设置文字颜色为绿色 Console.BackgroundColor = ConsoleColor.Red; //设置背景颜色为黑色 Console.SetWindowSize(50, 25); Console.SetBufferSize(50, 25); Console.CursorVisible = false; try { char dis; int x=0, y=0; while (true) { Console.Clear(); Console.SetCursorPosition(x, y); Console.Write("■"); dis = Console.ReadKey(true).KeyChar; switch (dis) { case 'w': case 'W': y--; if (y < 0) { y = 0; //防止光标位置小于0 } break; case 'a': case 'A': x -= 2; if (x < 0) { x = 0; //防止光标位置小于0 } break; case 's': case 'S': y++; if (y > Console.BufferHeight - 1) { y = Console.BufferHeight - 1; //防止光标位置超过缓冲区高度 } break; case 'd': case 'D': x += 2; if ( x > Console.BufferWidth - 2) { x = Console.BufferWidth - 2; } break; } } }catch (Exception ex) { Console.WriteLine($"发生异常: {ex.Message}"); } finally { Console.ResetColor(); //重置颜色为默认颜色 Console.Clear(); //清空控制台内容 Console.WriteLine("程序结束"); Environment.Exit(0); }