Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Галкин, Орлов ФТ301 #46

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 28 additions & 9 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
using System;
using System.Linq;
using Game.Domain;
using MongoDB.Driver;

namespace ConsoleApp
{
class Program
{
private readonly IUserRepository userRepo;
private readonly IGameRepository gameRepo;
private readonly Random random = new Random();
private readonly IGameTurnRepository gameTurnRepository;
private readonly Random random = new();

private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
gameRepo = new InMemoryGameRepository();
var db = new MongoClient("mongodb://localhost:27017").GetDatabase("game");
userRepo = new MongoUserRepository(db);
gameRepo = new MongoGameRepository(db);
gameTurnRepository = new MongoGameTurnRepository(db);
}

public static void Main(string[] args)
Expand Down Expand Up @@ -125,8 +129,8 @@ private bool HandleOneGameTurn(Guid humanUserId)

if (game.HaveDecisionOfEveryPlayer)
{
// TODO: Сохранить информацию о прошедшем туре в IGameTurnRepository. Сформировать информацию о закончившемся туре внутри FinishTurn и вернуть её сюда.
game.FinishTurn();
var gameTurnEntity = game.FinishTurn();
gameTurnRepository.Insert(gameTurnEntity);
}

ShowScore(game);
Expand All @@ -148,8 +152,6 @@ private PlayerDecision GetAiDecision()

private void UpdatePlayersWhenGameFinished(GameEntity game)
{
// Вместо этого кода можно написать специализированный метод в userRepo, который сделает все эти обновления за одну операцию UpdateMany.
// Вместо 4 запросов к БД будет 1, но усложнится репозиторий. В данном случае, это редкая операция, поэтому нет смысла оптимизировать.
foreach (var player in game.Players)
{
var playerUser = userRepo.FindById(player.UserId);
Expand Down Expand Up @@ -180,8 +182,25 @@ private void UpdatePlayersWhenGameFinished(GameEntity game)
private void ShowScore(GameEntity game)
{
var players = game.Players;
// TODO: Показать информацию про 5 последних туров: кто как ходил и кто в итоге выиграл. Прочитать эту информацию из IGameTurnRepository
var playersDictionary = players.ToDictionary(p => p.UserId, p => p.Name);
var lastFiveTurns = gameTurnRepository.GetLastTurns(game.Id, 5);
foreach (var turn in lastFiveTurns)
{
var winnerName = Guid.Empty != turn.WinnerId && playersDictionary.ContainsKey(turn.WinnerId)
? playersDictionary[turn.WinnerId]
: null;

var decisionsDescription = string.Join(" | ", turn.Decisions
.Select(x => $"Player {playersDictionary[Guid.Parse(x.Key)]} shows {x.Value}"));

var resultDescription = string.IsNullOrEmpty(winnerName)
? "Result: draw"
: $"Result: {winnerName} wins";

Console.WriteLine($"Turn {turn.TurnIndex}: {decisionsDescription}\n{resultDescription}");
}

Console.WriteLine($"Score: {players[0].Name} {players[0].Score} : {players[1].Score} {players[1].Name}");
}
}
}
}
14 changes: 9 additions & 5 deletions Game/Domain/GameEntity.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
public class GameEntity
{
[BsonElement]
private readonly List<Player> players;

public GameEntity(int turnsCount)
: this(Guid.Empty, GameStatus.WaitingToStart, turnsCount, 0, new List<Player>())
{
}


[BsonConstructor]
public GameEntity(Guid id, GameStatus status, int turnsCount, int currentTurnIndex, List<Player> players)
{
Id = id;
Expand All @@ -30,7 +33,8 @@ public Guid Id
}

public IReadOnlyList<Player> Players => players.AsReadOnly();


[BsonElement]
public int TurnsCount { get; }

public int CurrentTurnIndex { get; private set; }
Expand Down Expand Up @@ -88,8 +92,8 @@ public GameTurnEntity FinishTurn()
winnerId = player.UserId;
}
}
//TODO Заполнить все внутри GameTurnEntity, в том числе winnerId
var result = new GameTurnEntity();
var result = new GameTurnEntity(Guid.NewGuid(), Id, CurrentTurnIndex, winnerId,
Players.ToDictionary(p => p.UserId.ToString(), p=> p.Decision ?? throw new InvalidOperationException()));
// Это должно быть после создания GameTurnEntity
foreach (var player in Players)
player.Decision = null;
Expand Down
29 changes: 28 additions & 1 deletion Game/Domain/GameTurnEntity.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,34 @@
using System;
using System.Collections.Generic;
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
public class GameTurnEntity
{
//TODO: Придумать какие свойства должны быть в этом классе, чтобы сохранять всю информацию о закончившемся туре.
[BsonConstructor]
public GameTurnEntity(Guid id, Guid gameId, int turnIndex, Guid winnerId, Dictionary<string, PlayerDecision> decisions)
{
Id = id;
GameId = gameId;
TurnIndex = turnIndex;
WinnerId = winnerId;
Decisions = decisions;
}

[BsonElement]
public Guid Id { get; set; }

[BsonElement]
public Guid GameId { get; set; }

[BsonElement]
public int TurnIndex { get; set; }

[BsonElement]
public Guid WinnerId { get; set; }

[BsonElement]
public Dictionary<string, PlayerDecision> Decisions { get; set; }
}
}
6 changes: 5 additions & 1 deletion Game/Domain/IGameTurnRepository.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
using System;
using System.Collections.Generic;

namespace Game.Domain
{
public interface IGameTurnRepository
{
// TODO: Спроектировать интерфейс исходя из потребностей ConsoleApp
GameTurnEntity Insert(GameTurnEntity gameTurn);
List<GameTurnEntity> GetLastTurns(Guid gameId, int maxCountTurns);
}
}
21 changes: 12 additions & 9 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,45 @@

namespace Game.Domain
{
// TODO Сделать по аналогии с MongoUserRepository
public class MongoGameRepository : IGameRepository
{
private readonly IMongoCollection<GameEntity> gameCollection;
public const string CollectionName = "games";

public MongoGameRepository(IMongoDatabase db)
public MongoGameRepository(IMongoDatabase database)
{
gameCollection = database.GetCollection<GameEntity>(CollectionName);
}

public GameEntity Insert(GameEntity game)
{
throw new NotImplementedException();
gameCollection.InsertOne(game);
return game;
}

public GameEntity FindById(Guid gameId)
{
throw new NotImplementedException();
return gameCollection.Find(x => x.Id == gameId).SingleOrDefault();
}

public void Update(GameEntity game)
{
throw new NotImplementedException();
gameCollection.ReplaceOne(x => x.Id == game.Id, game);
}

// Возвращает не более чем limit игр со статусом GameStatus.WaitingToStart
public IList<GameEntity> FindWaitingToStart(int limit)
{
//TODO: Используй Find и Limit
throw new NotImplementedException();
return gameCollection.Find(x => x.Status == GameStatus.WaitingToStart)
.Limit(limit)
.ToList();
}

// Обновляет игру, если она находится в статусе GameStatus.WaitingToStart
public bool TryUpdateWaitingToStart(GameEntity game)
{
//TODO: Для проверки успешности используй IsAcknowledged и ModifiedCount из результата
throw new NotImplementedException();
var replaceResult = gameCollection.ReplaceOne(x => x.Id == game.Id && x.Status == GameStatus.WaitingToStart, game);
return replaceResult.IsAcknowledged && replaceResult.ModifiedCount > 0;
}
}
}
32 changes: 32 additions & 0 deletions Game/Domain/MongoGameTurnRepository.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,38 @@
using System;
using System.Collections.Generic;
using MongoDB.Driver;

namespace Game.Domain
{
public class MongoGameTurnRepository : IGameTurnRepository
{
private readonly IMongoCollection<GameTurnEntity> gameTurnCollection;
public const string CollectionName = "gameTurns";

public MongoGameTurnRepository(IMongoDatabase database)
{
gameTurnCollection = database.GetCollection<GameTurnEntity>(CollectionName);
gameTurnCollection.Indexes.CreateOne(new CreateIndexModel<GameTurnEntity>(
Builders<GameTurnEntity>.IndexKeys.Ascending(x => x.GameId)
.Ascending(x => x.TurnIndex)));
}

public GameTurnEntity Insert(GameTurnEntity gameTurn)
{
gameTurnCollection.InsertOne(gameTurn);
return gameTurn;
}

public List<GameTurnEntity> GetLastTurns(Guid gameId, int maxCountTurns)
{
var lastTurns = gameTurnCollection
.Find(x => x.GameId == gameId)
.SortByDescending(x => x.TurnIndex)
.Limit(maxCountTurns)
.ToList();

lastTurns.Reverse();
return lastTurns;
}
}
}
45 changes: 33 additions & 12 deletions Game/Domain/MongoUserRepositoty.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Game.Domain
Expand All @@ -7,47 +8,67 @@ public class MongoUserRepository : IUserRepository
{
private readonly IMongoCollection<UserEntity> userCollection;
public const string CollectionName = "users";

private static readonly object lockObject = new();

public MongoUserRepository(IMongoDatabase database)
{
userCollection = database.GetCollection<UserEntity>(CollectionName);
userCollection.Indexes.CreateOne(new CreateIndexModel<UserEntity>(
Builders<UserEntity>.IndexKeys.Ascending(x => x.Login),
new CreateIndexOptions { Unique = true }));
}

public UserEntity Insert(UserEntity user)
{
//TODO: Ищи в документации InsertXXX.
throw new NotImplementedException();
userCollection.InsertOne(user);
return user;
}

public UserEntity FindById(Guid id)
{
//TODO: Ищи в документации FindXXX
throw new NotImplementedException();
return userCollection.Find(x => x.Id == id).FirstOrDefault();
}

public UserEntity GetOrCreateByLogin(string login)
{
//TODO: Это Find или Insert
throw new NotImplementedException();
lock(lockObject)
{
var user = userCollection.Find(x => x.Login == login).FirstOrDefault();
if (user is not null)
{
return user;
}

user = new UserEntity(login);
Insert(user);

return user;
}
}

public void Update(UserEntity user)
{
//TODO: Ищи в документации ReplaceXXX
throw new NotImplementedException();
userCollection.ReplaceOne(x => x.Id == user.Id, user);
}

public void Delete(Guid id)
{
throw new NotImplementedException();
userCollection.DeleteOne(x => x.Id == id);
}

// Для вывода списка всех пользователей (упорядоченных по логину)
// страницы нумеруются с единицы
public PageList<UserEntity> GetPage(int pageNumber, int pageSize)
{
//TODO: Тебе понадобятся SortBy, Skip и Limit
throw new NotImplementedException();
var totalCount = userCollection.CountDocuments(x => true);

var users = userCollection.Find(x => true)
.SortBy(x => x.Login)
.Skip((pageNumber - 1) * pageSize)
.Limit(pageSize)
.ToList();

return new PageList<UserEntity>(users, totalCount, pageNumber, pageSize);
}

// Не нужно реализовывать этот метод
Expand Down
6 changes: 5 additions & 1 deletion Game/Domain/Player.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
Expand All @@ -7,17 +8,20 @@ namespace Game.Domain
/// </summary>
public class Player
{
[BsonConstructor]
public Player(Guid userId, string name)
{
UserId = userId;
Name = name;
}


[BsonElement]
public Guid UserId { get; }

/// <summary>
/// Снэпшот имени игрока на момент старта игры. Считайте, что это такое требование к игре.
/// </summary>
[BsonElement]
public string Name { get; }

/// <summary>
Expand Down
6 changes: 6 additions & 0 deletions Game/Domain/UserEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ public UserEntity(Guid id, string login, string lastName, string firstName, int
CurrentGameId = currentGameId;
}

public UserEntity(string login)
{
Id = new Guid();
Login = login;
}

public Guid Id
{
get;
Expand Down
Loading