想实现一个小游戏,先做地图移动。步骤记录如下:
1、百度到一张大的迷宫地图,放在项目的debug目录下,备用。
2、创建一个winform项目,不添加任何界面元素。
3、添加数据成员如下:
PictureBox pictureBox1; Bitmap myBitmap; Bitmap currBitmap; Point mypoint;
分别用于显示图片、存储地图,存储界面上的地图,界面上的地图显示的左上角坐标。
4、设置窗体启动后最大化
public Form1() { InitializeComponent(); this.WindowState = FormWindowState.Maximized; }
5、窗口启动后添加图片和做其他各种预备工作。
private void Form1_Shown(object sender, EventArgs e) { this.MaximumSize = this.Size; this.MinimumSize = this.Size; pictureBox1 = new PictureBox(); pictureBox1.Location = new System.Drawing.Point(0, 0); pictureBox1.Size = this.Size; this.Controls.Add(pictureBox1); myBitmap = new Bitmap("map.jpeg"); currBitmap = new Bitmap(this.Size.Width, this.Size.Height); pictureBox1.Image = currBitmap; mypoint = new Point(0, 0); var g = Graphics.FromImage(pictureBox1.Image); g.DrawImage(myBitmap, mypoint); }
6、处理asdw按键按下消息,让地图可以移动。
private void Form1_KeyDown(object sender, KeyEventArgs e) { var key = e.KeyValue; var g = Graphics.FromImage(pictureBox1.Image); if (key >= 'a' && key <= 'z') key -= ('a' - 'A'); switch(key) { case 'A': mypoint.X -= 10; if (mypoint.X + myBitmap.Size.Width <currBitmap.Size.Width) mypoint.X = currBitmap.Size.Width-myBitmap.Size.Width; break; case 'D': mypoint.X += 10; if (mypoint.X>0) mypoint.X = 0; break; case 'W': mypoint.Y -= 10; if (mypoint.Y + myBitmap.Size.Height < currBitmap.Size.Height) mypoint.Y = currBitmap.Size.Height - myBitmap.Size.Height; break; case 'S': mypoint.Y += 10; if (mypoint.Y>0) mypoint.Y = 0; break; default: break; } g.DrawImage(myBitmap, mypoint); pictureBox1.Refresh(); }
完毕。
显示效果如下:
下一步找一些小人加上去。
标签:游戏,c#,地图,Height,mypoint,pictureBox1,myBitmap,new,Size From: https://www.cnblogs.com/tyxajh/p/17024570.html