Тест
|
Ожидаемое поведение
|
Результат
|
Запустить три экземпляра приложения.
|
На трёх экземплярах появляется стартовое
меню.
|
Тест пройден.
|
На первом выбрать режим «Сетевая игра»,
выбрать «Создать комнату», выбрать 3 человека и размер матрицы 5. Нажать
кнопку «ОК».
|
На экране появляется форма с заданием
имени пользователя. При нажатиии «ОК» появляется сообщение «Ожидайте».
|
Тест пройден.
|
На клиентских приложениях выбрать
сетевой режим игры, подклучиться к серверу, нажать клавишу «ОК»
|
На экране появляется форма задания имени
пользователя и ip сервера. После нажатия «ОК» появляется надпись ожидание.
|
Тест пройден.
|
После подключения к серверу ещё 2
пользователей на всех 3 приложениях появляется список участников. Нажать
кнопку ОК
|
На экране появляется матрица 5 на пять.
Процесс игры аналогичен режиму на одним компьютере.
|
Тест пройден.
|
5. Руководство пользователя
Разработанное приложение является одновременно и
клиентским и серверным. При загрузке приложения появляется форма.
Рисунок 5.1. Внешний вид приложения
Можно выбрать два варианта игры: Игра на одном
компьютере и игра на по сети.
При выборе игры на одном компьютере появляется
форма настройки комнаты.
Рисунок 5.2 Настройки комнаты
На данном этапе можно указать количество игроков принимающих
участие в игре и размер матрицы.
При нажатии кнопки ОК появляется форма для ввода имён
пользователей.
Рисунок 5.3. Форма ввода имён пользователей
Затем происходит старт игры. Появляется матрица
для выбора букв и ввода слов.
Рисунок 5.4. Выбор ячейки для вставки буквы
В соответствии с правилами можно выбрать только
соседнюю ячейку для вставки букв. Затем с клавиатуры набирается буква и
нажимается метка «Принять».
Затем происходит выбор слова.
Рисунок 5.5. Выбор слова
Затем слово одобряется. Ход переходит следующему
пользователю. Так происходит пока вся матрица не становится заполненной. После
этого подводится итог игры и выводится сообщение о победителе.
Рисунок 5.6. Выбор слова
Заключение
В результате работы над курсовым проектом было
создано программное средство, представляющее собой сетевую игру «Балда».Игра
имеет дружественный интерфейс, два режима работы, высокую надёжность и
производительность.
Стоит отметить, что в данном приложении не
реализованы все возможности игры «Балда», а только наиболее важные. Тем не
менее этого набора хватает для полноценной работы с игрой.
В ходе работы над курсовым проектом мной были
изучены средства платформы.Net по работе с сетью и по работе с многопоточными
приложениями, т.к. приложение подобного типа требует параллельной работы с
несколькими пользователями, а также технология TCPClient и TCPListener.
В ходе работы так же укрепил знания по
технологиями.Net таким, как WinForms, сереализация объектов в Xml.
Приложение было сделано в соответствии с
принципами ООП. Широко использовалась событийная модель и делегаты.
Список использованных источников
1. Герберт Шилдт. Полный справочник по С#
- М.: Издательский дом "Вильямс", 2004. - 752 с.
. Эндрю Троелсен. Язык программирования C#
2010 и платформа.NET 4.0 - M.: Вильямс, 2010. -1392 c.
. Мэтью Мак-Дональд C# для профессионалов
- М.: Издательский дом "Вильямс", 2010. - 656 с.
. Википедия [Электронный ресурс]. -
Электронные данные. - Режим доступа: http://ru.wikipedia.org/wiki/
. WPF - Windows Presentation
Foundatin[Электронный ресурс]. - Электронные данные. - Режим доступа:
http://professorweb.ru/my/WPF/base_WPF/level1/info_WPF.php
. Windows Presentation
Foundation[Электронный ресурс]. - Электронные данные. - Режим доступа:
http://msdn.microsoft.com/ru-ru/library/ms754130.aspx
Приложение
Листинг класса NegotiationManager.
System;System.Collections.Generic;System.Drawing;System.Linq;System.Text;System.Threading.Tasks;System.Windows.Forms;BaldaClient.DisplayLogic;BaldaClient.NetworkManagment;BaldaClient.SettingsManagment;BaldaGameLogic.Delegates;BaldaGameLogic.GameLogic;BaldaGameLogic.GameModel;
BaldaClient.Negotiation
{class NegotiationManager
{
#region GameManagment
GameLogicManager gameLogicManager;DisplayManager
displayManager;NetworkManager networkManager;
SettingsManager SettingsManager { get; set;
}GameLogicControls GameLogicControls { get; set; }bool IsProcessServer { get;
set; }
BaldaAplicationForm MainForm
{; ;
}
String ProcessUserName { get; set; }
LogicCell previousLogicCell;
#endregion
#region GameLogicFlags
bool IsCellSelectionExpected
{{ return
gameLogicManager.IsCellSelectionExpected; }{
gameLogicManager.IsCellSelectionExpected = value; }
}
bool IsLetterSelectionExpected
{{ return
gameLogicManager.IsLetterSelectionExpected; }{ gameLogicManager.IsLetterSelectionExpected
= value; }
}
bool IsWordSelectionExpected
{{ return
gameLogicManager.IsWordSelectionExpected; }{
gameLogicManager.IsWordSelectionExpected = value; }
}
bool IsSelectedNetworkGameMode
{{ return
gameLogicManager.IsSelectedNetworkGameMode; }{ gameLogicManager.IsSelectedNetworkGameMode
= value; }
}
#endregion
List<Player> Players
{{ return gameLogicManager.Players; }{
gameLogicManager.Players = value; }
}
List<Player> TempPlayerList { get; set; }
NegotiationManager(BaldaAplicationForm mainForm)
{= mainForm;= new GameLogicManager();= new
NetworkManager(this);
}
void AddPlayerToTempPlayerList(String userName)
{(TempPlayerList == null)
{= new List<Player>();
}(TempPlayerList.FirstOrDefault(pl => pl.Name
== userName) == null)
{number = TempPlayerList.Count + 1;.Add(new
Player{Name = userName,Number = number});
}(gameLogicManager.Settings.PlayerCount ==
TempPlayerList.Count)
{.Players =
TempPlayerList;.CreateAllPlayersNameControls();
}
}
void BindGameManagers()
{.DisplayCells = displayManager.DisplayCells;.DisplayCellAsLight
= displayManager.DisplayCellsAsLight;.DisplayCurrentWord =
displayManager.DispalyCurrentWord;.DisplayCurrentPlayerName =
displayManager.DisplayCurrentPlayerName;.DisplayCurrentGuide =
displayManager.DisplayCurrentGuide;.DisplayCurrentError =
displayManager.DisplayCurrentError;.AddWordConfirmationButtons
=.GameForm.CreateWordConfirmationLabels;.RemoveConfirmationLabels =
GameLogicControls.GameForm.RemoveConfirmationLabels;.AddLetterConfirmationButtons
= GameLogicControls.GameForm.AddLetterConfirmationLabels;
}
void ConfigureGame()
{();.CreateGameLogicObjects();
}
void ConfigureGameSettings()
{.Settings = SettingsManager.GameLogicSettings;
}
void StartGame()
{.StartGame();.DrawFullMatrix();("БАЛДА");
}
void SetFirstWord(string word)
{.SetFirstWord(word);
}
void TrySelectCell(int xCor, int yCor)
{logicCell =
displayManager.GetLogicCellByCor(xCor, yCor);(logicCell!= null)
{(gameLogicManager.TrySelectCellForInsertingLetter(logicCell))
{= true;= false;
}
}
}
void SetLetterToCell(string letter)
{(gameLogicManager.LetterIsValidForInserting(letter))
{.SetLetterToCell(letter);
}
}
void TryAddNextCellToWordSelection(int xCor, int
yCor)
{logicCell =
displayManager.GetLogicCellByCor(xCor, yCor);
(logicCell!= null && previousLogicCell!=
logicCell)
{=
logicCell;(gameLogicManager.IsLogicCellValidForWordSelection(logicCell))
{.AddCellToWordSelection(logicCell);
}
}
}
void StopWordSelection()
{.StopWordSelection();
}
void ConfigureDisplaySettings()
{=DisplayManager(GameLogicControls,
SettingsManager.DisplaySettings, gameLogicManager.LogicCells);();
}
void CancelSelectedWord()
{.CancelSelectedWord();
}
void AcceptLetter()
{.AcceptLetter();
}
void CancelLetter()
{.CancelLetter();
}
void AcceptWord()
{.AcceptWord();
}
void CreateGameRoom(String userName)
{= true;=
userName;.CreateGameRoom();.ConnectToServer("localhost",userName);
}
void ConnectToRoom(String ipString, String
userName)
{.ConnectToServer(ipString,userName);.SendUserInformation(userName);
}
void ConfigureGameParameters(List<Player>
players, int size)
{gameLogicSettings = new GameSettings
{= size,= players.Count
};settingsManager = new SettingsManager
{= gameLogicSettings,= new DisplaySettings
{= Color.Black,= Color.Chartreuse,=
Color.Bisque,= Color.DarkOrange,= Color.Aqua,= 360 /
gameLogicSettings.MatrixSize - 2,= 2
}
};= settingsManager;();=
players;.CreateAllPlayersNameControls();
}
}
}abstract class FtpCommandParserBase
{readonly Dictionary<FtpCommand,
Action<FtpCommandParserBase, string>> CommandHandlers =Dictionary<FtpCommand,
Action<FtpCommandParserBase, string>>
{
{ FtpCommand.Abor, (parser, s) =>
parser.AborCommandHandler(s) },
{ FtpCommand.Cdup, (parser, s) =>
parser.CdupCommandHandler(s) },
{ FtpCommand.Cwd, (parser, s) =>
parser.CwdCommandHandler(s) },
{ FtpCommand.Dele, (parser, s) =>
parser.DeleCommandHandler(s) },
{ FtpCommand.List, (parser, s) =>
parser.ListCommandHandler(s) },
{ FtpCommand.Mdtm, (parser, s) =>
parser.MdtmCommandHandler(s) },
{ FtpCommand.Mkd, (parser, s) =>
parser.MkdCommandHandler(s) },
{ FtpCommand.Nlst, (parser, s) =>
parser.NlstCommandHandler(s) },
{ FtpCommand.Noop, (parser, s) =>
parser.NoopCommandHandler(s) },
{ FtpCommand.Pass, (parser, s) =>
parser.PassCommandHandler(s) },
{ FtpCommand.Pasv, (parser, s) =>
parser.PasvCommandHandler(s) },
{ FtpCommand.Port, (parser, s) =>
parser.PortCommandHandler(s) },
{ FtpCommand.Pwd, (parser, s) =>
parser.PwdCommandHandler(s) },
{ FtpCommand.Quit, (parser, s) =>
parser.QuitCommandHandler(s) },
{ FtpCommand.Rein, (parser, s) =>
parser.ReinCommandHandler(s) },
{ FtpCommand.Retr, (parser, s) =>
parser.RetrCommandHandler(s) },
{ FtpCommand.Rmd, (parser, s) =>
parser.RmdCommandHandler(s) },
{ FtpCommand.Rnfr, (parser, s) => parser.RnfrCommandHandler(s)
},
{ FtpCommand.Rnto, (parser, s) =>
parser.RntoCommandHandler(s) },
{ FtpCommand.Size, (parser, s) =>
parser.SizeCommandHandler(s) },
{ FtpCommand.Stor, (parser, s) =>
parser.StorCommandHandler(s) },
{ FtpCommand.Stou, (parser, s) => parser.StouCommandHandler(s)
},
{ FtpCommand.User, (parser, s) =>
parser.UserCommandHandler(s) }
};
#region Command delegatesvirtual Action
AborCommand { get; set; }virtual Action CdupCommand { get; set; }virtual
Action<string> CwdCommand { get; set; }virtual Action<string>
DeleCommand { get; set; }virtual Action<string> ListCommand { get; set;
}virtual Action<string> MdtmCommand { get; set; }virtual
Action<string> MkdCommand { get; set; }virtual Action<string>
NlstCommand { get; set; }virtual Action NoopCommand { get; set; }virtual
Action<string> PassCommand { get; set; }virtual Action PasvCommand { get;
set; }virtual Action<long, int> PortCommand { get; set; }virtual Action
PwdCommand { get; set; }virtual Action QuitCommand { get; set; }virtual Action
ReinCommand { get; set; }virtual Action<string> RetrCommand { get; set;
}virtual Action<string> RmdCommand { get; set; }virtual
Action<string> RnfrCommand { get; set; }virtual Action<string>
RntoCommand { get; set; }virtual Action<string> SizeCommand { get; set;
}virtual Action<string> StorCommand { get; set; }virtual
Action<string> StouCommand { get; set; }virtual Action<string>
UserCommand { get; set; }
#endregion
#region Command handlersabstract void
AborCommandHandler(string parameters);abstract void CdupCommandHandler(string
parameters);abstract void CwdCommandHandler(string parameters);abstract void
DeleCommandHandler(string parameters);abstract void ListCommandHandler(string
parameters);abstract void MdtmCommandHandler(string parameters);abstract void MkdCommandHandler(string
parameters);abstract void NlstCommandHandler(string parameters);abstract void
NoopCommandHandler(string parameters);abstract void PassCommandHandler(string
parameters);abstract void PasvCommandHandler(string parameters);abstract void
PortCommandHandler(string parameters);abstract void PwdCommandHandler(string
parameters);abstract void QuitCommandHandler(string parameters);abstract void
ReinCommandHandler(string parameters);abstract void RetrCommandHandler(string
parameters);abstract void RmdCommandHandler(string parameters);abstract void
RnfrCommandHandler(string parameters);abstract void RntoCommandHandler(string
parameters);abstract void SizeCommandHandler(string parameters);abstract void
StorCommandHandler(string parameters);abstract void StouCommandHandler(string
parameters);abstract void UserCommandHandler(string parameters);
#endregion
#region Methods
abstract void Parse(string message);
#endregion
}
class FtpCommandParser: FtpCommandParserBase
{
#region Fields
readonly Action<FtpCommand>
_onUnsupportedCommand;
#endregion
#region ctor
FtpCommandParser(Action<FtpCommand>
onUnsupportedCommandAction = null)
{(onUnsupportedCommandAction == null)
_onUnsupportedCommand = c => { throw new
UnsupportedFtpCommandException(c); };
_onUnsupportedCommand =
onUnsupportedCommandAction;
}
#endregion
#region Methods
#region Public methods
override void Parse(string message)
{= message.Trim(' ', '\n', '\r',
'\t');(string.IsNullOrEmpty(message));
[] parts = message.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
ftpCommand;(!FtpCommandHelper.Commands.TryGetValue(parts[0],
out ftpCommand))new UnknownFtpCommandException(parts[0]);
[ftpCommand](this, string.Join(" ",
parts.Skip(1)));
}
#endregion
#region Private methods
void InvokeCommand(FtpCommand command, Action
commandAction)
_onUnsupportedCommand(command);
}
void InvokeCommand(FtpCommand command,
Action<string> commandAction, string parameter)
{(commandAction!= null)
{(parameter == null)new
IncorrectFtpCommandFormatException(command);(parameter);
}
_onUnsupportedCommand(command);
}
#endregion
#region FtpCommandParserBase
#region Command handlers
override void AborCommandHandler(string
parameters)
{(FtpCommand.Abor, AborCommand);
}
override void CdupCommandHandler(string
parameters)
{(FtpCommand.Cdup, CdupCommand);
}
override void CwdCommandHandler(string
parameters)
{[] args = parameters.Split(new []{' '},
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Cwd, CwdCommand, args.Length
> 0? args[0]: null);
}
override void DeleCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Dele, DeleCommand,
args.Length > 0? args[0]: null);
}
override void ListCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.List, ListCommand,
args.Length > 0? args[0]: string.Empty);
}
override void MdtmCommandHandler(string parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Mdtm, MdtmCommand,
args.Length > 0? args[0]: null);
}
override void MkdCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Mkd,
MkdCommand, args.Length > 0? args[0]: null);
}
override void NlstCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Nlst, NlstCommand,
args.Length > 0? args[0]: string.Empty);
}
override void NoopCommandHandler(string
parameters)
{(FtpCommand.Noop, NoopCommand);
}
override void PassCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Pass, PassCommand,
args.Length > 0? args[0]: null);
}
override void PasvCommandHandler(string
parameters)
{(FtpCommand.Pasv, PasvCommand);
}
override void PortCommandHandler(string
parameters)
{[] args = parameters.Split(new[] {','},
StringSplitOptions.RemoveEmptyEntries);(args.Length < 6)new
IncorrectFtpCommandFormatException(FtpCommand.Port);
(PortCommand == null)
{
_onUnsupportedCommand(FtpCommand.Port);;
}
address = 0;port = 0;(int i = 0; i < 6; i++)
{part;(!byte.TryParse(args[i], out part))new
IncorrectFtpCommandFormatException(FtpCommand.Port);
(i < 4)+= part << (8 * i);= port * 256 +
part;
}
(address, port);
}
override void PwdCommandHandler(string
parameters)
{(FtpCommand.Pwd, PwdCommand);
}override void QuitCommandHandler(string
parameters)
{(FtpCommand.Quit, QuitCommand);
}
override void ReinCommandHandler(string
parameters)
{(FtpCommand.Rein, ReinCommand);
}
override void RetrCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Retr, RetrCommand,
args.Length > 0? args[0]: null);
}
override void RmdCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Rmd, RmdCommand, args.Length
> 0? args[0]: null);
}
override void RnfrCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Rnfr, RnfrCommand,
args.Length > 0? args[0]: null);
}
override void RntoCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Rnto, RntoCommand,
args.Length > 0? args[0]: null);
}
override void SizeCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Size, SizeCommand,
args.Length > 0? args[0]: null);
}
override void StorCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Stor, StorCommand,
args.Length > 0? args[0]: null);
}
override void StouCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.Stou, StouCommand,
args.Length > 0? args[0]: string.Empty);
}
override void UserCommandHandler(string
parameters)
{[] args = parameters.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);(FtpCommand.User, UserCommand,
args.Length > 0? args[0]: null);
}
#endregion
#endregion
#endregion
}
Листинг класса FileSystemWorker.cs
public class FileSystemWorker
{readonly string _rootDirectory;
UserRights _userRights;FileStream
_savingFile;FileStream _readingFile;const int BufferSize = 1048576; //1MBFileSystemWorker(string
rootDirectory)
{(!Directory.Exists(rootDirectory))new
DirectoryNotFoundException(rootDirectory);
_rootDirectory =
Path.GetFullPath(rootDirectory);.SetCurrentDirectory(_rootDirectory);
}
void InitUserRights(UserRights userRights)
{
_userRights = userRights;
}
void GoToParentDirectory()
{(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
currentPath =
CheckAndGetCurrentDirectory();(string.Compare(_rootDirectory, currentPath,
StringComparison.OrdinalIgnoreCase)!= 0).SetCurrentDirectory(Directory.GetParent(currentPath).FullName);
}
void GoToRootDirectory()
{(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
.SetCurrentDirectory(_rootDirectory);
}
void ChangeDirecroty(string directory)
{(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
newPath =
Path.Combine(CheckAndGetCurrentDirectory(), directory.TrimStart(new [] { '\\',
'/' }));(!Directory.Exists(newPath))new FileSystemAccessDeniedException();
.SetCurrentDirectory(newPath);
}
string CreateDirectory(string directory)
{(!_userRights.CanCreate())new
FileSystemAccessDeniedException();
path =
Path.Combine(CheckAndGetCurrentDirectory(), directory.TrimStart(new[] { '\\',
'/' }));
(Directory.Exists(path))new
FileSystemException(string.Format("Directory \"{0}\" already
exists", directory));
{.CreateDirectory(path);
}(IOException ex)
{new
FileSystemException(ex.Message.Replace(_rootDirectory, ""));
}path.Replace(_rootDirectory, "");
}
void RemoveDirectory(string directory)
{(!_userRights.CanCreate())new
FileSystemAccessDeniedException();
path =
Path.Combine(CheckAndGetCurrentDirectory(), directory.TrimStart(new[] { '\\',
'/' }));
{.Delete(path);
}(IOException)
{new FileSystemAccessDeniedException();
}
}
string GetCurrentDirectory()
{path =
CheckAndGetCurrentDirectory().Replace(_rootDirectory,
"");Path.IsPathRooted(path)? path: "\\" + path;
}
void DeleteFile(string fileName)
{(!_userRights.CanCreate())new
FileSystemAccessDeniedException();
filePath = Path.Combine(CheckAndGetCurrentDirectory(),
fileName.TrimStart(new [] { '\\', '/' }));(!File.Exists(filePath))new
FileSystemAccessDeniedException();
{.Delete(filePath);
}(IOException ex)
{new
FileSystemException(ex.Message.Replace(_rootDirectory, ""));
}
}
void RenameFile(string fileName, string
newFileName)
{(!_userRights.CanCreate())new
FileSystemAccessDeniedException();
oldFilePath =
Path.Combine(CheckAndGetCurrentDirectory(), fileName.TrimStart(new[] { '\\',
'/' }));(!File.Exists(oldFilePath))new FileSystemAccessDeniedException();
newFilePath =
Path.Combine(CheckAndGetCurrentDirectory(), newFileName.TrimStart(new[] { '\\',
'/' }));(File.Exists(newFilePath))new
FileSystemException(string.Format("File \"{0}\" already
exists", newFileName));
{.Move(oldFilePath, newFilePath);
}(IOException ex)
{new
FileSystemException(ex.Message.Replace(_rootDirectory, ""));
}
}
string BeginWriteFile(string fileName, bool
newNameIfExists = false)
{(_savingFile!= null)new Exception("Previous
file not saved");
(!_userRights.CanUpload())new FileSystemAccessDeniedException();
filePath =
Path.Combine(CheckAndGetCurrentDirectory(), fileName.TrimStart(new [] { '\\',
'/' }));(File.Exists(filePath) || string.IsNullOrWhiteSpace(fileName))
{(!newNameIfExists)new
FileSystemAccessDeniedException();
= Guid.NewGuid().ToString().Substring(0, 8);=
Path.Combine(CheckAndGetCurrentDirectory(), fileName.TrimStart(new [] { '\\',
'/' }));
}
_savingFile = new FileStream(filePath,
FileMode.CreateNew, FileAccess.Write, FileShare.None,
BufferSize,.SequentialScan);
fileName;
}
void WriteData(byte[] data, int size)
{(_savingFile == null ||!_savingFile.CanWrite)new
Exception("File not accessible to write");
_savingFile.Write(data, 0, size);
}
void EndWriteFile()
{(_savingFile == null)new Exception("File
not opened");
_savingFile.Close();
_savingFile = null;
}
void BeginReadFile(string fileName)
{(_readingFile!= null)new
Exception("Previous file not closed");
(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
filePath =
Path.Combine(CheckAndGetCurrentDirectory(), fileName.TrimStart(new[] { '\\',
'/' }));(!File.Exists(filePath))new FileSystemAccessDeniedException();
_readingFile = new FileStream(filePath,
FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize,.SequentialScan);
}
int ReadData(byte[] buffer, int size)
{(_readingFile == null
||!_readingFile.CanRead)new Exception("File not accessible to read");
_readingFile.Read(buffer, 0, size);
}void EndReadFile()
{(_readingFile == null)new Exception("File
not opened");
_readingFile.Close();
_readingFile = null;
}
bool FileExists(string fileName)
{File.Exists(Path.Combine(CheckAndGetCurrentDirectory(),
fileName.TrimStart(new[] { '\\', '/' })));
}
bool CanRenameFile()
{_userRights.CanCreate();
}
bool CanUploadFile()
{_userRights.CanUpload();
}
bool CanDownloadFile()
{_userRights.CanDownload();
}DateTime GetFileModifiedDate(string fileName)
{(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
filePath =
Path.Combine(CheckAndGetCurrentDirectory(), fileName.TrimStart(new[] { '\\',
'/' }));(!File.Exists(filePath))new FileSystemAccessDeniedException();
File.GetLastWriteTime(filePath);
}
long GetFileSize(string fileName)
{(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
filePath =
Path.Combine(CheckAndGetCurrentDirectory(), fileName.TrimStart(new[] { '\\',
'/' }));(!File.Exists(filePath))new FileSystemAccessDeniedException();
{new FileInfo(filePath).Length;
}(IOException ex)
{new FileSystemException(ex.Message.Replace(_rootDirectory,
""));
}
}
string[] GetFileInfo(string fileName, bool
onlyNames = false)
{(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
<FileInfo> files = new
List<FileInfo>();<DirectoryInfo> directories = new
List<DirectoryInfo>();
currentDirectory =
CheckAndGetCurrentDirectory();filePath = string.IsNullOrWhiteSpace(fileName)
? currentDirectory
: Path.Combine(currentDirectory,
fileName.TrimStart(new[] {'\\', '/'}));
(File.Exists(filePath))
{.Add(new FileInfo(filePath));
}if (Directory.Exists(filePath))
{.AddRange(Directory.GetFiles(filePath).Select(v
=> new FileInfo(v)));.AddRange(Directory.GetDirectories(filePath).Select(v
=> new DirectoryInfo(v)));
}
{new FileSystemAccessDeniedException();
}
<FileInfo, string>
getFileInfo;<DirectoryInfo, string> getDirectoryInfo;(onlyNames)
{==>
string.Format("\t{0}", f.Name.Replace(_rootDirectory,
""));==> string.Format("dir\t{0}",
d.Name.Replace(_rootDirectory, ""));
}
{==>
string.Format("\t{0}\t{1}\t{2}", f.Name.Replace(_rootDirectory,
""), f.Length, f.LastWriteTime);==>
string.Format("dir\t{0}\t{1}\t{2}", d.Name.Replace(_rootDirectory,
""), "", d.LastWriteTime);
}
<string>
result = new List<string>();.AddRange(.Select(=>
getFileInfo(v)));.AddRange(.Select(=> getDirectoryInfo(v)));
result.ToArray();
}
private string CheckAndGetCurrentDirectory()
{(!_userRights.CanDownload())new
FileSystemAccessDeniedException();
currentDirectory =
Directory.GetCurrentDirectory();(!currentDirectory.StartsWith(_rootDirectory))new
Exception("Incorrect working directory");
currentDirectory;
}
}
Листинг класса DisplayManager
using
System;System.Collections.Generic;System.Drawing;System.Drawing.Drawing2D;System.Linq;System.Text;System.Windows.Forms;BaldaClient.DisplayModel;BaldaGameLogic.GameLogic;BaldaGameLogic.GameModel;
BaldaClient.DisplayLogic
{class DisplayManager
{
#region Properties for
bindingsGameLogicControls GameControls { get; set; }
#endregion
#region gameLogicFields
List<LogicCell>
logicCells;List<DisplayCell> displayCells;DisplayCell
previousSelectedCell;
Dictionary<LogicCell,
DisplayCell> cellDictionary;
#endregion
#region forDisplayFields
int cellBackgroundOffset;int
cellBackgroundSize;int cellTextOffset;PictureBox pb;Graphics gr;Pen pen;Brush
primaryBrush;Brush lightBrush;Brush textBrush;Font font;Label
selectedWordLabel;DisplaySettings displaySettings;
#endregionDisplayCell
selectedCellForLetter;
LogicCell SelectedCellForLetter
{{ return
(selectedCellForLetter!= null)? selectedCellForLetter.LogicCell: null; }
}
DisplayManager(GameLogicControls
gameLogicControls, DisplaySettings displaySettings, List<LogicCell>
logiccells)
{.GameControls =
gameLogicControls;.pb = gameLogicControls.pictureBox;.selectedWordLabel =
gameLogicControls.SelectedWordLabel;.Refresh();=
pb.CreateGraphics();.displaySettings = displaySettings;= new
Pen(displaySettings.cellBorderColor, displaySettings.MatrixCellBorderWidth);=
new SolidBrush(displaySettings.cellBackgroundColor);= new
SolidBrush(displaySettings.selectedCellBackroundColor);= new
SolidBrush(displaySettings.cellLetterColor);= new
Font(FontFamily.GenericMonospace, (displaySettings.MatrixCellSize / 2),
FontStyle.Bold);= displaySettings.MatrixCellBorderWidth/2;=
displaySettings.MatrixCellSize - displaySettings.MatrixCellBorderWidth;=
displaySettings.MatrixCellBorderWidth/2 + 6;= logiccells;();
}
void CreateDisplayCells()
{= new
List<DisplayCell>();= new Dictionary<LogicCell,
DisplayCell>();.ForEach(lc =>
{dispayCell = new DisplayCell
{= lc,= (lc.X - 1)*displaySettings.MatrixCellSize
+ cellBackgroundOffset,= (lc.Y - 1)*displaySettings.MatrixCellSize +
cellBackgroundOffset,
};.Add(dispayCell);.Add(lc,
dispayCell);
});
}
void DrawCell(DisplayCell cell,
Brush backGroundBrush)
{
{(cell!= null)
{.DrawRectangle(pen, cell.offsetX,
cell.offsetY, displaySettings.MatrixCellSize,
displaySettings.MatrixCellSize);.FillRectangle(backGroundBrush, cell.offsetX +
cellBackgroundOffset, cell.offsetY + cellBackgroundOffset,,
cellBackgroundSize);(!String.IsNullOrEmpty(cell.LogicCell.Letter)).DrawString(cell.LogicCell.Letter,
font, textBrush, cell.offsetX + cellTextOffset,.offsetY + cellTextOffset);
}
}(Exception ex)
{ex;
}
}
void DrawLightCell(DisplayCell
cell)
{
}
void DrawFullMatrix()
{.ForEach(cell =>
DrawCell(cell, primaryBrush));
}
void
DisplayCells(List<LogicCell> logCells)
{.ForEach(lc=>
DrawCell(cellDictionary[lc],primaryBrush));
}void
DisplayCellsAsLight(List<LogicCell> logCells)
{.ForEach(lc =>
DrawCell(cellDictionary[lc], lightBrush));
}
bool
SelectCellForInsertingLetter(int xCor, int yCor)
{(previousSelectedCell!= null)
{(previousSelectedCell,primaryBrush);
}(xCor,yCor);true;
}
void LightCellByCor(int xCor,
int yCor)
{cell =
GetDisplayCellByCor(xCor, yCor);= cell;(cell,lightBrush);
}
DisplayCell
GetDisplayCellByCor(int xCor, int yCor)
{logicX = xCor /
displaySettings.MatrixCellSize + 1;logicY = yCor /
displaySettings.MatrixCellSize + 1;GetCellByLogicCor(logicX, logicY);
}DisplayCell
GetCellByLogicCor(int x, int y)
{displayCells.FirstOrDefault(cell
=> (cell.LogicCell.X == x) && (cell.LogicCell.Y == y));
}
LogicCell GetLogicCellByCor(int
x, int y)
{logicX = x /
displaySettings.MatrixCellSize + 1;logicY = y / displaySettings.MatrixCellSize
+ 1;displayCell = GetCellByLogicCor(logicX, logicY);(displayCell!=null)?
displayCell.LogicCell: null;
}
void DispalyCurrentWord(string
message)
{.Text = message;
}
void
DisplayCurrentPlayerName(string message)
{.CurrentPlayerLabel.Text =
message;
}
void DisplayCurrentGuide(string
message)
{.GuideLabel.Text = message;
}
void DisplayCurrentError(string
message)
{.ErrorLabel.Text = message;
}
}
}System;System.Collections.Generic;System.IO;System.Linq;System.Net;System.Net.Sockets;System.Text;System.Threading;System.Threading.Tasks;System.Windows.Forms;
delegate void
HandleMassageActivity(String message);
BaldaClient.NetworkModel
{class NetworkClient:
IDisposable
{StreamWriter
swSender;StreamReader srReceiver;TcpClient tcpServer;delegate void
UpdateLogCallback(string strMessage);delegate void
CloseConnectionCallback(string strReason);Thread thrMessaging;IPAddress
ipAddr;bool Connected;
HandleMassageActivity
HandleMessage;
NetworkClient(HandleMassageActivity
handleMessage)
{.HandleMessage = handleMessage;
}
void ConnectToServer(String
ipString,String userName)
{(Connected == false)
{(ipString,userName);
}
{("Disconnected at user's
request.");
}
}
void InitializeConnection(String
ipString, String userName)
{= new
TcpClient();.Connect("localhost", 1986);= true;= new
StreamWriter(tcpServer.GetStream());.WriteLine(userName);.Flush();= new
Thread(new ThreadStart(ReceiveMessages));.Start();
}
void ReceiveMessages()
{= new
StreamReader(tcpServer.GetStream());ConResponse =
srReceiver.ReadLine();(ConResponse[0] == '1')
{("Connected Successfully!");
}
{Reason = "Not Connected:
";+= ConResponse.Substring(2, ConResponse.Length - 2);(Reason);;
}(Connected)
{newMessage =
srReceiver.ReadLine();(newMessage);
}
}
void UpdateLog(string
strMessage)
{.WriteLine(strMessage);
}void CloseConnection(string Reason)
{
=
false;.Close();.Close();.Close();
}
void SendMessage(String message)
{.WriteLine(message);.Flush();
}
void Dispose()
{(Connected == true)
}
}
}
}System;System.Collections.Generic;System.Linq;System.Text;BaldaGameLogic.Delegates;BaldaGameLogic.GameModel;
BaldaGameLogic.GameLogic
{
class GameLogicManager
{GameSettings Settings { get;
set; }List<LogicCell> LogicCells { get; private set;
}List<LogicCell> MainWordLogicCells { get; private set; }LogicCell selectedCell;
List<Player> Players {
get; set; }List<LogicCell> SelectedCellsForWord;String selectedWord {
get; set; }
PlayerGameStatistic
GameStatistic { get; set; }
Player activePlayer;
#region GameLogicFlags
bool IsCellSelectionExpected {
get; set; }
bool IsLetterSelectionExpected {
get; set; }
bool IsWordSelectionExpected {
get; set; }bool IsSelectedNetworkGameMode { get; set; }
bool IsWordSelected { get; set;
}
bool IsPreviousInvalid;
#endregion
#region GameLogicDelegates
DisplayMatrixCells DisplayCells
{ private get; set; }
DisplayMatrixCells
DisplayCellAsLight { private get; set; }
DisplayMessage
DisplayCurrentWord { private get; set; }
DisplayMessage
DisplayCurrentPlayerName { private get; set; }
DisplayMessage DisplayCurrentGuide
{ private get; set; }
DisplayMessage
DisplayCurrentError { private get; set; }
DispalyAction
AddWordConfirmationButtons { private get; set; }
DispalyAction
RemoveConfirmationLabels { private get; set; }
DispalyAction
AddLetterConfirmationButtons { private get; set; }
ConditionAction IsWordExist {
private get; set; }
#endregion
void CreateGameLogicObjects()
{();();= new
List<LogicCell>();
}
void CreatePlayersObjects()
{= new List<Player>();(int
i = 1; i <= Settings.PlayerCount; i++)
{.Add(new Player {Number = i,
Name = String.Empty});
}= new
PlayerGameStatistic(Players);
}
void CreateLogicCells()
{= new
List<LogicCell>();(int i = 1; i <= Settings.MatrixSize; i++)
{(int j = 1; j <=
Settings.MatrixSize; j++)
{.Add(new LogicCell
{= i,= j,= String.Empty
});
}
}middleRowIndex =
Settings.MatrixSize / 2 + 1;= new List<LogicCell>();.Where(cell =>
cell.Y == middleRowIndex)
.ToList()
.ForEach(cell => {
MainWordLogicCells.Add(cell);.IsMainWorldCell = true;
});
}
void SetFirstWord(String
mainWord)
{(mainWord.Length!=
Settings.MatrixSize)
{new Exception("Start wold
more then matrix size");
}mainWorldBuilder = new
StringBuilder(mainWord);(int i = 0; i < Settings.MatrixSize; i++)
{[i].Letter =
mainWorldBuilder[i].ToString();(MainWordLogicCells);
}
}
void StartGame()
{= Players.First(pl =>
pl.Number == 1);();
}
bool
TrySelectCellForInsertingLetter(LogicCell logCell)
{(!String.IsNullOrEmpty(logCell.Letter))
{(GamePlayMessages.CellMustBeEmpty);false;
}(!IsOneOfNeigborsContainsLetter(logCell))
{(GamePlayMessages.NeighborMustContainLetter);false;
}
= logCell;(new
List<LogicCell> { logCell
});(String.Empty);(GamePlayMessages.InsertLetter);true;
}
bool
LetterIsValidForInserting(string letter)
{true;
}
public void
SetLetterToCell(string letter)
{.Letter = letter;= false;=
false;(new List<LogicCell>{selectedCell});(letter);();
}
bool
IsLogicCellValidForWordSelection(LogicCell logCell)
{(SelectedCellsForWord!= null)
{(String.IsNullOrEmpty(logCell.Letter))
{= true;false;
}(SelectedCellsForWord.Contains(logCell)
&& (SelectedCellsForWord.Last()!= logCell))
{
{(logCell);=
false;(GetCurentSelectedWord());
}false;
}(SelectedCellsForWord.Contains(logCell)
&& (SelectedCellsForWord.Last() == logCell))
{false;
}(SelectedCellsForWord.Count!=
0)
{(!IsLogicCellsNeighbors(logCell,SelectedCellsForWord.Last()))
{false;
}
}
}true;
}
bool
IsLogicCellsNeighbors(LogicCell firstCell, LogicCell secondCell)
{((firstCell == null) ||
(secondCell == null))
{false;
}neighbors =
GetNeighborsForCell(firstCell);neighbors.Contains(secondCell);
}
private List<LogicCell>
GetNeighborsForCell(LogicCell logicCell)
{high =
GetCellByLogicCor(logicCell.X, logicCell.Y + 1);low =
GetCellByLogicCor(logicCell.X, logicCell.Y - 1);left =
GetCellByLogicCor(logicCell.X - 1, logicCell.Y);right =
GetCellByLogicCor(logicCell.X + 1, logicCell.Y);list = new
List<LogicCell>(); (high!=null) list.Add(high);(low!= null)
list.Add(low);(left!= null) list.Add(left);(right!= null) list.Add(right);list;
}
bool
IsOneOfNeigborsContainsLetter(LogicCell logicCell)
{flag=false;(logicCell).ForEach(lc
=>
{(lc!= null)
{(!String.IsNullOrEmpty(lc.Letter))
{= true;
}
}
});flag;
}
private LogicCell
GetCellByLogicCor(int x, int y)
{LogicCells.FirstOrDefault(lc
=> (lc.X == x) && (lc.Y == y));
}
void HandleDoubleCellInWordSelection(LogicCell
cell)
{index =
SelectedCellsForWord.IndexOf(cell);temp =
SelectedCellsForWord.Take(index+1).ToList();(int i = index+1; i <
SelectedCellsForWord.Count; i++)
{(new
List<LogicCell>{SelectedCellsForWord[i]});
}= temp;
}
void
AddCellToWordSelection(LogicCell logicCell)
{ .Add(logicCell);(new
List<LogicCell>(){logicCell});(GetCurentSelectedWord());
}
string GetCurentSelectedWord()
{selectedWord =
String.Empty;.ForEach(cell=>selectedWord += cell.Letter);selectedWord;
}
void StopWordSelection()
{(IsSelectedWordContainsSelectedCell())
{();
}
{(GamePlayMessages.WordMustContainSelectedCell);
}
}
bool
IsSelectedWordContainsSelectedCell()
{(SelectedCellsForWord!= null)
{(SelectedCellsForWord.Count!=
0)
{(selectedCell!= null)
{SelectedCellsForWord.Contains(selectedCell);
}
}
}false;
}
#region GamePlayAction
void CancelSelectedWord()
{();(SelectedCellsForWord);=
null;= String.Empty;();
}
void CancelLetter()
{.Letter = String.Empty;(new
List<LogicCell>{selectedCell});= null;();
}
void AcceptLetter()
{();
}
void AcceptWord()
{.SetWordToPlayer(activePlayer,
selectedWord);();(SelectedCellsForWord);= null;();();
}
#endregion
#region SetGamePlayStage
void SetWordSelectionStage()
{();= new
List<LogicCell>();= true;(String.Empty);(GamePlayMessages.SelectWord);(String.Empty);
}
void SetCellCelectionStage()
{();=
true;(activePlayer.Name);(GamePlayMessages.SelectCellForLetter);(String.Empty);(String.Empty);
}
private void
SetAcceptLetterStage()
{();();(selectedCell.Letter);(GamePlayMessages.AcceptLetter);(String.Empty);
}
void SetAcceptWordStage()
{= false;=
GetCurentSelectedWord();(selectedWord);(String.Empty);(GamePlayMessages.AcceptWord);();
}
#endregion
void SetNextActivePlayer()
{index =
Players.IndexOf(activePlayer);(index == (Players.Count - 1))
{= Players.First();
}
{= Players[index + 1];
}(activePlayer.Name);
}
}
}