//盤面の状態と選択されているブロックによってブロックを動かす private void slide() { Point direction = new Point(0, 0); Point zero = searchZoro(); if(zero.X == selectCell.X) { //縦 if(zero.Y > selectCell.Y) { direction = new Point(0, -1); } else if(zero.Y < selectCell.Y) { direction = new Point(0, 1); } } else if(zero.Y == selectCell.Y) {//横 if(zero.X > selectCell.X) { direction = new Point(-1, 0); } else if(zero.X < selectCell.X) { direction = new Point(1, 0); } } slide(direction); } private void slide(Point direction) { if(direction == new Point(0, 0)) return; Point zero = searchZoro(); while(true) { table[zero.X, zero.Y] = table[zero.X + direction.X, zero.Y + direction.Y]; zero.Offset(direction); if(zero == selectCell) { table[selectCell.X, selectCell.Y] = 0; return; } } } //ブロックが無い場所を探す private Point searchZoro() { for(int y = 0; y < 4; y++) { for(int x = 0; x < 4; x++) { if(table[x, y] == 0) { return new Point(x, y); } } } return new Point(); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { e.Graphics.FillRectangle(Brushes.Black, 0, 0, this.ClientSize.Width, this.ClientSize.Height);//背景 for(int y = 0; y < 4; y++) { for(int x = 0; x < 4; x++) { if(table[x, y] == 0) continue; Rectangle rect = new Rectangle(x * cellSize, y * cellSize, cellSize, cellSize);//ブロックの矩形 e.Graphics.FillRectangle(Brushes.AliceBlue, rect);//ブロック e.Graphics.DrawRectangle(Pens.Black, rect);//枠 e.Graphics.DrawString(table[x, y].ToString(), new Font(FontFamily.GenericSerif, 38), Brushes.Black, rect);//ブロックの数字 } } e.Graphics.DrawRectangle(new Pen(Color.White, 2), selectCell.X * cellSize, selectCell.Y * cellSize, cellSize, cellSize);//カーソル } //マウスが指し示す位置を選択 private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { for(int y = 0; y < 4; y++) { for(int x = 0; x < 4; x++) { Rectangle rect = new Rectangle(x * cellSize, y * cellSize, cellSize, cellSize); if(rect.Contains(e.Location)) { selectCell = new Point(x, y); pictureBox1.Refresh(); return; } } } } //クリックはEnter or Spaceキーと等価 private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { Form1_KeyDown(this, new KeyEventArgs(Keys.Enter)); } } }