// Обработка событий мыши на клетки игрового поля private void GameStart_MouseClick(object sender, MouseEventArgs e) { if ((e.X < 498) && (e.Y < 498)) { if (!button1.Visible) { return; } setShip(e); return; } Cell cell = null; if ((e.X <= 1100) && (e.X > 600) && (e.Y < 498)) { if (!is_your_turn) { return; } if (e.Button.ToString() == "Left") { cell = opponentfield.getCellByCoordinate(e.X - 600, e.Y); string msg = "shot:" + cell.getX().ToString() + '_' + cell.getY().ToString(); sendData(msg); string result = ""; try { result = receiveData(); } catch { MessageBox.Show("Проблемы с сервером"); this.Close(); } Graphics g = CreateGraphics(); if (result == "true") { cell.setState(5); cell.draw(g); if (opponentfield.checkFinishOpponent()) { MessageBox.Show("Победа " + this.Text.ToString() + '!'); this.Close(); } } else { cell.setState(1); cell.draw(g); is_your_turn = false; WhoTurnLabel.Text = "Сейчас ход противника"; WhoTurnLabel.Refresh(); // На поражение чекаем в waitForShot Thread clientThread = new Thread(new ThreadStart(waitForShot)); clientThread.Start(); } } } }
// Ожидание хода противника. Прослушивание данных от сервера private void waitForShot() { string shot = ""; try { shot = receiveData(); } catch { MessageBox.Show("Проблемы с сервером"); this.Close(); } string[] parameters = shot.Split(':'); string[] indexes = parameters[1].Split('_'); int i = Convert.ToInt32(indexes[0]); int j = Convert.ToInt32(indexes[1]); Cell cell = startfield.getCellByCoordinate(i - 600, j); int state = cell.getState(); Graphics g = CreateGraphics(); if (state == 2) { cell.setState(3); cell.draw(g); sendData("true"); if (startfield.checkFinishSelf()) { MessageBox.Show("Поражение " + this.Text.ToString()); this.Close(); } waitForShot(); } else { cell.setState(1); cell.draw(g); //this.Refresh(); sendData("false"); is_your_turn = true; WhoTurnLabel.Text = "Сейчас ваш ход"; this.Refresh(); } }
private void setShip(MouseEventArgs e) { Cell cell = null; if (e.Button.ToString() == "Left") { cell = startfield.getCellByCoordinate(e.X, e.Y); cell.setState(2); Graphics g = CreateGraphics(); Checkships(cell); cell.draw(g); } if (e.Button.ToString() == "Right") { cell = startfield.getCellByCoordinate(e.X, e.Y); cell.setState(0); Graphics g = CreateGraphics(); cell.draw(g); } ShipRemaining(); }
// Проверка соседствующих клеток на наличие кораблей private void Checkships(Cell cell) { Cell cell1; Graphics g = CreateGraphics(); int mainX = cell.getX(); int mainY = cell.getY(); for (int i = mainX - 50; i <= mainX + 50; i += 100) { if (i <= 0) { continue; } if (i >= 498) { continue; } for (int j = mainY - 50; j <= mainY + 50; j += 100) { if (j <= 0) { continue; } if ((i == mainX) && (j == mainY)) { continue; } if (j >= 498) { continue; } cell1 = startfield.getCellByCoordinate(i, j); if (cell1.getState() == 2) { MessageBox.Show("Боевые корабли соседствуют друг с другом!"); cell.setState(0); } } } }