public CellDto[] Parse(string[] stringCells) { if (stringCells == null) { throw new NullReferenceException(nameof(stringCells)); } if (stringCells.Length == 0) { throw new ArgumentException("Array of string cells can't be empty"); } var height = stringCells.Length; var width = stringCells[0].Length; var cells = new CellDto[height * width]; for (var i = 0; i < height; i++) { for (var j = 0; j < width; j++) { var index = i * width + j; cells[index] = CheckCell(stringCells[i][j], index, j, i); } } return(cells); }
// public void GenerateRandomPuzzle() // { // lock (_lock) // { // _sudokuBoard.Clear(); // _sudokuSolver.SolveThePuzzle(true); // // _sudokuBoard.Cells.First().Value = -1; // } // } public bool SetCellValue(CellDto cellDto, Participant participant) { lock (_lock) { if (cellDto == null) { return(false); } var cell = _sudokuBoard.Cells.First(c => c.Position.Column == cellDto.Column && c.Position.Row == cellDto.Row); if (!_sudokuSolver.IsValidValueForTheCell(cellDto.Value, cell)) { return(false); } cell.Value = cellDto.Value; OnCellUpdated(cellDto); if (_sudokuBoard.IsBoardFilled()) { OnGameCompleted(participant); } return(true); } }
/// <summary>Пересоздание массива ячеек поля игры.</summary> /// <param name="rows">Количество строк поля</param> /// <param name="columns">Количество колонок поля</param> /// <remarks>Пересоздание происходит, если одно из новых значений не совпадает с текущим.</remarks> void ChangeCellsCount(int rows, int columns) { if (Cells == null || Cells.GetLength(0) != rows || Cells.GetLength(1) != columns) { Cells = new CellDto[rows, columns]; ChangedStateEvent?.Invoke(this, new ChangedStateHandlerArgs(NamesState.ChangeCellsCount, new int[] { rows, columns })); } }
public bool CanMove(CellDto cell, UserDto user) { if (user == null || CurrentGamer == null || user.UserName != CurrentGamer.UserName || GameStatus != GameStatuses.Game) { return(false); } return(Cells[cell.Row, cell.Column]?.CellType == null); }
public void gameCell() { this.cellCurrent = this.player.Cell; deplacement(); if (!this.exit) { movePlayer(); } }
private void Move() { Console.Clear(); Console.WriteLine("Vers où souhaites-tu t'aventurer ? (Tape Est,Nord,Ouest,Sud)"); string line = ZorkRead.ReadLine().ToLowerInvariant(); while (line != "est" && line != "nord" && line != "sud" && line != "ouest") { Console.WriteLine("Exprime toi plus clairement ! (Tape Est,Nord,Ouest,Sud)"); line = ZorkRead.ReadLine(); } var cell = Globals.Player.Cell; CellDto nextCell = null; bool move = false; while (!move) { switch (line) { case "est": nextCell = Globals.Player.Map.Cells.FirstOrDefault(c => c.PosX == cell.PosX + 1 && c.PosY == cell.PosY); break; case "nord": nextCell = Globals.Player.Map.Cells.FirstOrDefault(c => c.PosX == cell.PosX && c.PosY == cell.PosY + 1); break; case "sud": nextCell = Globals.Player.Map.Cells.FirstOrDefault(c => c.PosX == cell.PosX - 1 && c.PosY == cell.PosY); break; case "ouest": nextCell = Globals.Player.Map.Cells.FirstOrDefault(c => c.PosX == cell.PosX && c.PosY == cell.PosY - 1); break; } if (nextCell == null) { Console.WriteLine("Les montagnes géantes bloque ton avancée. Tu dois choisir une autre direction !"); line = ZorkRead.ReadLine(); } else { move = true; } } Globals.Player.Cell = nextCell; //PlayerService.Save(Globals.Player); MovementRandomMeeting(); }
private void FinishGame(CellDto testCell) { bool isWin = WinCheck(testCell); if (isWin) { SetGameStatus(GameStatuses.Win, CurrentGamerId); return; } if (!Cells.Cast <CellDto>().Any(cl => cl?.CellType == null)) { SetGameStatus(GameStatuses.Draw); } }
/// <summary>Проверка на появление новой завершенной линии относительно свежедобавленного элемента</summary> /// <param name="cell">ячейка, относительно которой осуществляется проверка</param> /// <param name="elementsCount">количество подряд идущих однотипных элементов в ряду, необходимых для зачисления новой линии</param> /// <param name="useShiftX">использование при проверке сдвига по оси X</param> /// <param name="useShiftY">использование при проверке сдвига по оси Y</param> /// <param name="directionForDiagonalTest">должно быть true при проверке диагонали, идущей с верхнего правого конца относительно выбранной ячейки к левому нижнему концу</param> /// <returns>Возвращает true в случае появления хоть одной новой заполненной линии</returns> private bool TestLine(CellDto cell, int elementsCount, bool useShiftX, bool useShiftY, bool directionForDiagonalTest) { int ShiftForCalculateCompleteLine = LineLength - 1; //сдвиг относительно проверяемой ячейки //Utils.Log("start test line************************************", useShiftX, useShiftY, directionForDiagonalTest); int shiftFromX = 0; //точка начала проверки по оси X int shiftFromY = (useShiftY == true) ? cell.Row - ShiftForCalculateCompleteLine : 0; //точка начала проверки по оси Y - вычисляется сразу т.к. параметр directionForDiagonalTest не влияет на расчеты по оси Y int diagonalFactor = 1; //коэффициент для расчета в случае проверки совпадений по 2й диагонали int countCoinCidencesInLine = 0; //количество совпадений в линии int countLinesComplete = 0; if (useShiftX == true) //смещение по оси X { if (directionForDiagonalTest == true) //расчет по диагонали с правой стороны { shiftFromX = cell.Column + ShiftForCalculateCompleteLine; diagonalFactor = -1; } else { shiftFromX = cell.Column - ShiftForCalculateCompleteLine; } } int length = ShiftForCalculateCompleteLine * 2 + 1; //количество определяемых ячеек - длина возможной линии в обе стороны (с учетом текущей ячейки) for (int i = 0; i < length; i++) { int x = (useShiftX) ? shiftFromX + (diagonalFactor * i) : cell.Column; //координаты проверяемой ячейки по оси X int y = (useShiftY) ? shiftFromY + i : cell.Row; //координаты проверяемой ячейки по оси Y CellDto targetCell = GetCellByPosiotion(x, y); //Utils.Log("test cell (x, y):", x, y); if (targetCell != null && targetCell.CellType == cell.CellType) //если ячейка существует и типы совпадают... { countCoinCidencesInLine++; if (countCoinCidencesInLine >= LineLength) { countLinesComplete++; } } else { countCoinCidencesInLine = 0; } } return(countLinesComplete > 0); }
public IEnumerable <CellDto> PopulateCellDtos(IEnumerable <Cell> cells) { IList <CellDto> result = new List <CellDto>(); foreach (Cell cell in cells) { CellDto cellDto = new CellDto() { RowNum = cell.RowNum, ColumnField = cell.ColumnField, CellState = cell.CellState }; result.Add(cellDto); } return(result); }
public void Move(CellDto cell, UserDto user) { if (!CanMove(cell, user)) { throw new Exception("Данный ход не возможен. Игрок: " + user.Id + ", column: " + cell.Column + ", row: " + cell.Row); } SetCellType(cell, CurrentGamer.CellType); FinishGame(Cells[cell.Row, cell.Column]); if (GameStatus == GameStatuses.Game) { SetCurrentGamerIndex(CurrentGamerIndex + 1); } //else // /// Сброс флага начатой игры // SetIsGameSaved(false); }
//private int ShiftForCalculateCompleteLine;//сдвиг относительно проверяемой ячейки //public event NotifyChangedCellHandler ChangedCellEvent; /// <summary>Изменение типа содержания заданной ячейки</summary> /// <param name="cell">Заданная ячейка</param> /// <param name="type">Новый тип содержания</param> void SetCellType(CellDto cell, CellTypeDto type) { // Если текущий тип равен присваиваемому, то ничего не делается. // Можно написать сокращённо: //if (Cells[cell.Row, cell.Column]?.CellType == type) if (Cells[cell.Row, cell.Column] != null && Cells[cell.Row, cell.Column].CellType == type) { return; } // В противном случае создаётся новый экземпляр ячейки с новым значением контента. // Если ячейка заполнена, то Id берётся из неё. Если не заполнена, то из переданного // параметра cell. После присвоения ячейке нового экземпляра, создаётся событие // с передачей нового содержания ячейки. ChangedStateEvent?.Invoke(this, new ChangedStateHandlerArgs(NamesState.CellType, Cells[cell.Row, cell.Column] = new CellDto(Cells[cell.Row, cell.Column]?.Id ?? cell.Id, cell.Row, cell.Column, type))); }
private static void Move(string command) { try { int x = Int32.Parse(command[0].ToString()); int y = Int32.Parse(command[1].ToString()); CellContent content = (_currentUser == UserType.UserFirst) ? CellContent.Cross : CellContent.Zero; CellDto cell = new CellDto(x, y, content); CellView cellView = new CellView(cell); cells[y][x] = cellView; for (int i = 0; i < cells.Length; i++) { string res = ""; string symbol; CellView[] row = cells[i]; for (int j = 0; j < row.Count(); j++) { CellContent cellContent = row[j].CellType; symbol = "-"; if (cellContent == CellContent.Cross) { symbol = "X"; } if (cellContent == CellContent.Zero) { symbol = "0"; } res += symbol; } Console.WriteLine(res); } Console.WriteLine("************************** - ход совершен"); _currentUser = (_currentUser == UserType.UserSecond) ? UserType.UserFirst : UserType.UserSecond; } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// 确定属性信息 /// </summary> /// <param name="sheetData"><see cref="SheetData"/>对象</param> /// <returns><see cref="PropertyDto"/>对象数组</returns> private PropertyDto[] GetPropertyDtos(SheetData sheetData) { int pcount = propertyInfoes.Length; uint i = 0; PropertyDto[] pds = new PropertyDto[pcount]; for (; i < pcount; i++) { PropertyInfo pi = propertyInfoes[i]; DisplayOpenXmlAttribute displayAtt = pi.GetCustomAttributes(typeof(DisplayOpenXmlAttribute), false).FirstOrDefault() as DisplayOpenXmlAttribute; PropertyDto pd = new PropertyDto(pi.PropertyType, displayAtt); pd.ColumnReference = CellReferenceUtil.GetColumnReference(i); pds[i] = pd; } // 使用模板并且使用最后一行的样式 if (UseTemplate && TemplateUseLastRowStyle) { // 最后一行 Row rl = sheetData.LastChild as Row; if (rl != null) { IEnumerable <Cell> cls = rl.Elements <Cell>().Where(x => false == string.IsNullOrEmpty(x.CellReference)); Dictionary <int, CellDto> dic = cls.Select(x => new CellDto(x.CellReference, x.StyleIndex)).ToDictionary(x => x.ColumnIndex); if (dic.Count() > 0) { int j = 0; for (; j < pcount; j++) { PropertyDto pd = pds[j]; CellDto cd = null; bool s = dic.TryGetValue(j, out cd); if (true == s && cd != null) { pd.StyleIndex = (int)cd.StyleIndex; } } } } } return(pds); }
private bool WinCheck(CellDto cell) { if (cell.CellType == null) { throw new Exception("Попытка проверки пустой ячейки"); } bool horizontal = TestLine(cell, LineLength, true, false, false); bool vertical = TestLine(cell, LineLength, false, true, false); bool diagonalRight = TestLine(cell, LineLength, true, true, true); bool diagonalLeft = TestLine(cell, LineLength, true, true, false); return(horizontal || vertical || diagonalLeft || diagonalRight); /*return ( * TestLine(cell, LineLength, true, false, false) || //horizontal * TestLine(cell, LineLength, false, true, false) || //vertical * TestLine(cell, LineLength, true, true, false) || //diagonal-1 * TestLine(cell, LineLength, true, true, true) //diagonal-2 * );*/ }
public GameVM() { for (int row = 0; row < RowsCount; row++) { for (int column = 0; column < ColumnsCount; column++) { Cells.Add(new CellVM() { Row = row, Column = column, CellType = CellTypes[random.Next(CellTypes.Count)] }); } } MoveCommand = new RelayCommand ( p => { CellDto cell = (CellDto)p; Cells[cell.Row * ColumnsCount + cell.Column].CellType = CellTypes[random.Next(CellTypes.Count - 1) + 1]; }, p => p is CellDto cell && (string.IsNullOrWhiteSpace(cell.CellType.Type) || cell.CellType.Type == "Empty") ); }
private void Model_ChangedStateEvent(object sender, ChangedStateHandlerArgs e) { switch (e.StateName) { case NamesState.RowsCount: RowsCount = (int)e.NewValue; break; case NamesState.ColumnsCount: ColumnsCount = (int)e.NewValue; break; case NamesState.LineLength: LineLength = (int)e.NewValue; break; case NamesState.GameStatus: //int userId = (int)e.NewValue[1]; if (e.NewValue is GameStatuses status) { Statuse = status; } else { object[] args = (object[])e.NewValue; int userId = (int)args[1]; status = (GameStatuses)args[0]; if (status == GameStatuses.Win) { if (FirstGamer.Id == userId) { Winner = FirstGamer; Loser = SecondGamer; } else if (SecondGamer.Id == userId) { Winner = SecondGamer; Loser = FirstGamer; } else { throw new ArgumentException("Не существующий UserId, когда один из игроков сдался/выиграл"); } } else { throw new ArgumentException("Не допустимый статус игры"); } Statuse = status; } break; case NamesState.Gamers: var users = ((IEnumerable <UserDto>)e.NewValue).OrderBy(us => us.Turn); var first = users.First(); var second = users.Skip(1).First(); CopyPropertiesToVM(first, FirstGamer); CopyPropertiesToVM(second, SecondGamer); FirstGamer.Image = PiecesCollection.ElementAt(FirstGamer.ImageIndex); SecondGamer.Image = PiecesCollection.ElementAt(SecondGamer.ImageIndex); break; case NamesState.Types: CellTypes.Clear(); ((ISet <CellTypeDto>)e.NewValue).ToList().ForEach(c => CellTypes.Add(c)); FirstGamer.CellType = CellTypes[1]; SecondGamer.CellType = CellTypes[2]; break; case NamesState.CurrentGamerId: break; case NamesState.CurrentGamerIndex: CurrentUserIndex = (int)e.NewValue; break; case NamesState.CurrentGamer: var user = (UserDto)e.NewValue; if (FirstGamer.UserName == user.UserName) { CurrentUserIndex = 0; } else if (SecondGamer.UserName == user.UserName) { CurrentUserIndex = 1; } else { CurrentUserIndex = -1; } break; case NamesState.IsRevenge: IsRevenge = (bool)e.NewValue; break; case NamesState.CellType: CellDto cell = (CellDto)e.NewValue; cellsMatrix[cell.Row, cell.Column].CellType = cell.CellType; break; case NamesState.ChangeCellsCount: int[] cellsParams = (int[])e.NewValue; RowsCount = cellsParams[0]; ColumnsCount = cellsParams[1]; Cells.Clear(); cellsMatrix = new CellVM[RowsCount, ColumnsCount]; for (int row = 0; row < RowsCount; row++) { for (int col = 0; col < ColumnsCount; col++) { Cells.Add(cellsMatrix[row, col] = new CellVM() { Row = row, Column = col }); } } break; case NamesState.ChangeGamerIsTurn: UserDto newUser = (UserDto)e.NewValue; //UserDto oldUser = (UserDto)e.OldValue; //UserVM newUserVM = FirstGamer, oldUserVM = SecondGamer; if (FirstGamer.UserName == newUser.UserName) { FirstGamer.IsTurn = newUser.IsTurn; } else if (SecondGamer.UserName == newUser.UserName) { SecondGamer.IsTurn = newUser.IsTurn; } else { throw new ArgumentException($"Не существующее имя очередного игрока {newUser.UserName}", nameof(e)); } break; default: break; } }
public CellView(CellDto cell) : base(cell.Column, cell.Row, cell.CellType) { }
public void Save(CellDto cell) { this.cells.Save(MapperExtension.Mapper.Map <Cell>(cell)); }
/// <summary>Изменение типа содержания заданной ячейки с передачей нового /// типа в свойстве параметра cell</summary> /// <param name="cell">Заданная ячейка</param> void SetCellType(CellDto cell) => SetCellType(cell, cell.CellType);
public CellXML(CellDto cell) { Row = cell.Row; Column = cell.Column; CellType = cell.CellType.ToString(); }
public static Cell ToModel(this CellDto dto) => new Cell { Status = dto.Status.ToModel() };
protected virtual void OnCellUpdated(CellDto e) { CellUpdated?.Invoke(this, e); }