c# - My snake program won't show the objects I drew. How can I fix it?
问题描述
I'm following a snake tutorial right now and I wrote the exact thing as said, but it won't even show the rectangles of the snake and food.enter code here
I'm using Windows Form Application.
I made separate classes - Food; Snake; And the one for the form.
//Snake class
public Rectangle[] Body;
private int x = 0, y = 0, width = 20, height = 20;
public Snake()
{
Body = new Rectangle[1];
Body[0] = new Rectangle(x, y, width, height);
}
public void Draw()
{
for (int i = Body.Length - 1; i < 0; i--)
Body[i] = Body[i - 1];
}
public void Draw (Graphics graphics)
{
graphics.FillRectangles(Brushes.AliceBlue, Body);
}
public void Move (int direction)
{
Draw();
//Food Class
public class Food
{
public Rectangle Piece;
private int x, y, width = 20, height = 20;
public Food(Random rand)
{
Generate(rand);
Piece = new Rectangle(x, y, width, height);
}
public void Draw(Graphics graphics)
{
Piece.X = x;
Piece.Y = y;
graphics.FillRectangle(Brushes.Red, Piece);
解决方案
您没有从任何形式的可绘制上下文对象继承您的身体和食物类。因此,每当发生更改时,都需要显式调用“绘制”例程。您似乎试图模仿 WinForms UI 组件的结构,其中它有自己的内置 Draw() 方法,该方法在 UI 需要更新时被隐式调用。
此外,由于您在没有任何参数的情况下调用“Draw”,除非您在不需要参数的地方有重载,否则应该会引发错误。在这种情况下,将没有要绘制的图形上下文。
我不是游戏图形方面的专家,但我知道不断调用 UI 组件的重绘方法是非常低效的。Invalidate() 方法有一些覆盖,您可以在其中提供矩形以仅使整个组件的一小部分无效。这有助于提高重绘率。
我建议在屏幕上使用一个可渲染的 UI 组件链接到您的数据对象。并覆盖该组件的 draw() 方法,以便它根据存储在游戏对象中的数据绘制整个游戏板(或基于无效区域的部分游戏板)。
推荐阅读
- sparql - sideEffects、map 和 path 都没有 Y 键:WherePredicateStep(neq(Y))
- python - 尝试将 fit 与 SelectKBest 变量一起使用并不断收到 TypeError
- google-cloud-platform - 来自 Colab 笔记本的 Google 服务帐户的 12 因素身份验证
- c++ - 对标准安全:移动成员?
- java - 上传两个文件和一个对象失败并出现错误 415
- excel - 计数当前行和下一行是否满足条件
- corda - 我如何在 Corda 事务中使用响应者 inputsStatesAndRef?
- python - 从 pyinstaller bundle #2 访问 python 解释器
- python - 使用 matplotlib 和 numpy 查找一组局部最大值的最大值
- python - 从另一个文件调用函数 - Discord bot