private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space && !isJumping && !gameOver)
{
jumpSpeed = -10;
}
}
显示图片与得分情况:
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.SkyBlue, 0, 0, ClientSize.Width, ClientSize.Height);
e.Graphics.DrawImage(Properties.Resources._1, 50, marioY, MarioSize, MarioSize);//图片
e.Graphics.FillRectangle(Brushes.Red, objectX, objectY, ObjectSize, ObjectSize);
e.Graphics.DrawString($"得分:{score}", Font, Brushes.Black, 10, 10);
}
窗体初始化:
private const int MarioSize = 50;
private const int ObjectSize = 50;
private const int ObjectSpeed = 10;
private int marioY;
private int objectX;
private int objectY;
private bool isJumping;
private int jumpSpeed;
private bool gameOver;
private int score;
public Form1()
{
InitializeComponent();
marioY = ClientSize.Height - MarioSize;
objectX = ClientSize.Width;
objectY = ClientSize.Height - ObjectSize;
isJumping = false;
jumpSpeed = 10;
gameOver = false;
score = 0;
timer1.Interval = 1000 / 60; // 每秒60帧
timer1.Enabled = true;
}
添加时间控件:
private void timer1_Tick(object sender, EventArgs e)
{
if (!gameOver)
{
objectX -= ObjectSpeed;
if (objectX < -ObjectSize)
{
objectX = ClientSize.Width ObjectSize;
objectY = ClientSize.Height - ObjectSize - new Random().Next(50, 150);
score ;
}
if (isJumping)
{
marioY -= jumpSpeed;
jumpSpeed--;
if (marioY >= ClientSize.Height - MarioSize)
{
isJumping = false;
marioY = ClientSize.Height - MarioSize;
jumpSpeed = 10;
}
}
else
{
marioY = jumpSpeed;
jumpSpeed = Math.Min(jumpSpeed 1, 20);
if (marioY MarioSize > ClientSize.Height)//停在底部
{
marioY = ClientSize.Height - MarioSize;
}
}
if (objectX < 100 && objectX > 0 && marioY MarioSize > objectY)
{
gameOver = true;
timer1.Enabled = false;
MessageBox.Show($"游戏结束!得分:{score}");
}
Invalidate();
}
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved