2010-05-06

讓背景捲動



看書學的,用方向鍵控制方向,空白鍵換場景



-------------------------------------------------------------
namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        Image[]BG = new Image[3];
        int dx = 0, dy = 0;
        int k = 0;
        int dir = 2;
   
        public Form1()
        {
            InitializeComponent();
            BG[0] = new Bitmap (Properties.Resources.A01);
            BG[1] = new Bitmap (Properties.Resources.A02);
            BG[2] = new Bitmap (Properties.Resources.A03);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            for (int i= -1; i <= this.ClientSize.Width / BG[k].Width +1; i++)
                 for (int j = -1; j <= this.ClientSize.Height/BG[k].Height +1; j++)
                     e.Graphics.DrawImage(BG[k], i * BG[k].Width + (dx % BG[k].Width), j * BG[k].Height + (dy % BG[k].Height));
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Down)
                dir = 0;
            else if (e.KeyData == Keys.Up)
                dir = 1;
            else if (e.KeyData == Keys.Right)
                dir = 2;
            else if (e.KeyData == Keys.Left)
                dir = 3;
            else if (e.KeyData == Keys.Space)
                k = ++k % 3;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (dir == 0) dy = dy - 5;
            else if (dir == 1) dy = dy + 5;
            else if (dir == 2) dx = dx - 5;
            else if (dir == 3) dx = dx + 5;
            this.Invalidate();
        }
    }
}




沒有留言:

張貼留言