用winform写一个横版过关游戏
时间: 2023-12-20 07:06:06 浏览: 42
好的,下面是一个简单的横版过关游戏的WinForms代码示例。这个游戏包括一个玩家角色和一些敌人,玩家需要躲避敌人并到达终点。你可以根据需要进行修改和扩展。
首先,需要一个 `Player` 类,继承自 `PictureBox`,表示玩家角色:
```csharp
public class Player : PictureBox
{
public int Speed { get; set; } = 5;
public Player()
{
Image = Properties.Resources.player;
SizeMode = PictureBoxSizeMode.StretchImage;
Size = new Size(50, 50);
Location = new Point(20, 200);
}
public void MoveLeft()
{
if (Left > 0)
{
Left -= Speed;
}
}
public void MoveRight()
{
if (Right < Parent.ClientSize.Width)
{
Left += Speed;
}
}
public void Jump()
{
// Jump logic
}
}
```
接下来是敌人的类 `Enemy`,同样继承自 `PictureBox`:
```csharp
public class Enemy : PictureBox
{
public int Speed { get; set; } = 3;
public Enemy()
{
Image = Properties.Resources.enemy;
SizeMode = PictureBoxSizeMode.StretchImage;
Size = new Size(50, 50);
Location = new Point(700, 200);
}
public void Move()
{
if (Right > 0)
{
Left -= Speed;
}
else
{
Left = Parent.ClientSize.Width;
}
}
}
```
现在可以创建主窗体 `Form1`,在 `Form_Load` 事件中添加玩家和敌人:
```csharp
public partial class Form1 : Form
{
private Player _player;
private List<Enemy> _enemies;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_player = new Player();
_enemies = new List<Enemy>();
Controls.Add(_player);
for (int i = 0; i < 5; i++)
{
var enemy = new Enemy();
_enemies.Add(enemy);
Controls.Add(enemy);
}
}
}
```
接下来需要让敌人动起来,可以在 `Timer` 的 `Tick` 事件中调用 `Move` 方法:
```csharp
private void timer1_Tick(object sender, EventArgs e)
{
foreach (var enemy in _enemies)
{
enemy.Move();
}
}
```
最后,通过键盘事件来控制玩家的移动:
```csharp
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
_player.MoveLeft();
break;
case Keys.Right:
_player.MoveRight();
break;
case Keys.Space:
_player.Jump();
break;
}
}
```
这只是一个简单的示例,你可以根据需要进行修改和扩展。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)