【发布时间】:2018-12-09 16:08:22
【问题描述】:
我正在尝试制作一个按钮,当我单击它时,它会将游戏状态更改为正在玩,然后调用将玩游戏的所有内容,但是我无法获得返回游戏统计信息的方法。
private GameState Playbutton_Click(object sender, EventArgs e)
{
GameState CurrentState = GameState.playing;
return CurrentState;
}
我得到的错误是 'Game1.GameState Game1.Playbutton_Click(object, EventArgs)' 返回类型错误
编辑:
在第 1 场比赛中:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
enum GameState
{
playing,
menu,
over
}
GameState CurrentState = GameState.playing;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
GameState CurrentState = GameState.playing;
Playbutton = new Button(Content.Load<Texture2D>("button"), Content.Load<SpriteFont>("Font"))
{
position = new Vector2(690, 500),
Text = ("Play")
};
Quitbutton = new Button(Content.Load<Texture2D>("button"), Content.Load<SpriteFont>("Font"))
{
position = new Vector2(690, 800),
Text = ("Quit")
};
Playbutton.Click += Playbutton_Click;
Quitbutton.Click += Quitbutton_Click;
components = new List<Component>()
{
Playbutton,
Quitbutton
};
private void Quitbutton_Click(object sender, EventArgs e)
{
Exit();
}
private void Playbutton_Click(object sender, EventArgs e)
{
GameState CurrentState = GameState.playing;
}
按钮类:
private MouseState _currentMouse;
private SpriteFont _font;
private bool _isHovering;
private MouseState _previousMouse;
private Texture2D _texture;
public event EventHandler Click;
public bool Clicked { get; private set; }
public Color PenColour { get; set; }
public Vector2 position { get; set; }
public Rectangle Rectangle
{
get
{
return new Rectangle((int)position.X, (int)position.Y, _texture.Width, _texture.Height);
}
}
public string Text { get; set; }
public Button(Texture2D texture, SpriteFont font)
{
_texture = texture;
_font = font;
PenColour = Color.Black;
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
var colour = Color.White;
if (_isHovering)
colour = Color.Gray;
spriteBatch.Draw(_texture, Rectangle, colour);
if (!string.IsNullOrEmpty(Text))
{
var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour);
}
}
public override void Update(GameTime gameTime)
{
_previousMouse = _currentMouse;
_currentMouse = Mouse.GetState();
var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1);
_isHovering = false;
if (mouseRectangle.Intersects(Rectangle))
{
_isHovering = true;
if (_currentMouse.LeftButton == ButtonState.Released && _previousMouse.LeftButton == ButtonState.Pressed)
{
Click?.Invoke(this, new EventArgs());
}
}
}
}
【问题讨论】:
-
C# 中的所有标准事件处理程序都声明为
void,它们“处理”事件,而不是返回数据。如果您想使用事件处理程序更改应用程序的状态,则必须通过调用方法、更改字段或执行其他修改应用程序状态的操作直接从事件处理程序修改它。 -
在您的事件处理程序中,您正在设置一个私有变量