int vx = 5;
int vy = 5;
int bleft, bright, btop, bbottom;
private void timer1_Tick(object sender, EventArgs e)
{
bleft = b.Left;
bright = b.Right;
btop = b.Top;
bbottom = b.Bottom;
b.Left += vx;
b.Top += vy;
if (b.Left<0)
{
vx = Math.Abs(vx);
}
if (b.Right>this.ClientSize.Width)
{
vx = -Math.Abs(vx);
}
if (b.Top<menuStrip1.Height)
{
vy = Math.Abs(vy);
}
if (b.Bottom>p.Top)//如果用label無法直接使用比較符號
{
int c = (b.Left + b.Right) / 2;
if (c>=p.Left&&c<=p.Right)
{
double f = ((double)c - (double)p.Left) / (double)p.Width;
if (vx<0)
{
f = (1.0 - f);
}
vx = (int)Math.Round(vx * f);
vy = -Math.Abs(vy);
}
else
{
if (b.Top>this.ClientSize.Height)
{
timer1.Stop();
MessageBox.Show("game over,,,,");
}
}
}
foreach (var c in this.Controls)
{
if (c is Label)
{
Label Q = (Label)c;
if (Q.Visible)
{
if (chkHit(Q)) { break; }
}
}
}
}
int mdx;
private void 開始ToolStripMenuItem_Click(object sender, EventArgs e)
{
b.Top = 40 * 10 + 30;
p.Top = this.ClientSize.Height - 30;
b.Left = this.ClientSize.Width / 2;
b.Top = this.ClientSize.Height / 3;
timer1.Start();
}
private void 暫停繼續ToolStripMenuItem_Click(object sender, EventArgs e)
{
timer1.Enabled = !(timer1.Enabled);
}
private void 結束ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void p_MouseDown(object sender, MouseEventArgs e)
{
mdx = e.X;
}
private void p_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int x = p.Left + (e.X - mdx);
if (x < 0)
{
x = 0;
}
if (x > this.ClientSize.Width - p.Width)
{
x = this.ClientSize.Width - p.Width;
}
p.Left = x;
}
}
private Label Brick(int x, int y)
{
Label B = new Label();
B.Width = 60;
B.Height = 40;
B.BackColor = Color.DarkRed;
B.BorderStyle = BorderStyle.FixedSingle;
B.Left = x;
B.Top = this.menuStrip1.Height + y;
return B;
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <10; i++)
{
for (int j = 0; j < 5; j++)
{
this.Controls.Add(Brick(i*60, j*40));
}
}
this.Width = 600 + this.Width - this.ClientSize.Width;
//clientSize無法直接調整,所以只能用整體減去可編輯來調整
this.Height = 400 + this.Height - this.ClientSize.Height;
b.Top = 40 * 10 + 30;
p.Top = this.ClientSize.Height - 30;
b.Left = (this.ClientSize.Width - b.Width) / 2;
p.Left = (this.ClientSize.Width - p.Width) / 2;
}
private Boolean chkHit(Label Q)
{
if (b.Top > Q.Bottom) { return false; }//求在磚塊下方
if (b.Right > Q.Left) { return false; }//求在磚塊左方
if (b.Left > Q.Right) { return false; }//球在磚塊右方
if (b.Bottom <Q.Top) { return false; }//球在磚塊上方
//以上4種判斷都通過代表球有撞到磚塊
Q.Visible = false;
if (b.Right>=Q.Left&&btop>Q.Left)//撞到磚塊底部
{
vy = Math.Abs(vy);
return true;
}
if (b.Left<=Q.Right&&bright>Q.Right)//撞到磚塊右邊
{
vx = Math.Abs(vx);
return true;
}
if (b.Left>= Q.Right && bright < Q.Right)//撞到磚塊左邊
{
vx =- Math.Abs(vx);
return true;
}
if (b.Bottom>=Q.Top&&bbottom<Q.Top)//撞到磚塊底部
{
vy = -Math.Abs(vy);
return true;
}
return false;
}
打磚塊小遊戲,球是自己把圖片放上去