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

Унисихин Никита ФТ-304 #24

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
3 changes: 2 additions & 1 deletion ConsoleApp/ConsoleApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<LangVersion>9</LangVersion>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Game\Game.csproj" />
<ProjectReference Include="..\Tests\Tests.csproj" />
</ItemGroup>

</Project>
31 changes: 26 additions & 5 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Game.Domain;
using JetBrains.Annotations;
using Tests;

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

private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
gameRepo = new InMemoryGameRepository();
var db = TestMongoDatabase.Create();
userRepo = new MongoUserRepository(db, false);
gameRepo = new MongoGameRepository(db, false);
gameTurnRepo = new MongoGameTurnRepository(db, false);
}

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

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

ShowScore(game);
Expand Down Expand Up @@ -180,8 +186,23 @@ private void UpdatePlayersWhenGameFinished(GameEntity game)
private void ShowScore(GameEntity game)
{
var players = game.Players;
// TODO: Показать информацию про 5 последних туров: кто как ходил и кто в итоге выиграл. Прочитать эту информацию из IGameTurnRepository
var lastTurns = gameTurnRepo.FindLastTurns(game.Id);
foreach (var lastTurn in lastTurns)
{
var winner = GetWinner(players, lastTurn.WinnerId);
Console.WriteLine($"Turn {lastTurn.TurnIndex}: {players[0].Name} {lastTurn.FirstPlayerDecision} : {players[1].Name} {lastTurn.SecondPlayerDecision}");
Console.WriteLine($"Turn result: {(winner is null ? "draw" : $"{winner.Name} win")}");
}
Console.WriteLine($"Score: {players[0].Name} {players[0].Score} : {players[1].Score} {players[1].Name}");
}

[CanBeNull]
private Player GetWinner(IReadOnlyList<Player> players, Guid winnerId)
{
if (winnerId == Guid.Empty)
return null;

return players[0].UserId == winnerId ? players[0] : players[1];
}
}
}
10 changes: 6 additions & 4 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 @@ -31,6 +34,7 @@ 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,9 +92,7 @@ public GameTurnEntity FinishTurn()
winnerId = player.UserId;
}
}
//TODO Заполнить все внутри GameTurnEntity, в том числе winnerId
var result = new GameTurnEntity();
// Это должно быть после создания GameTurnEntity
var result = new GameTurnEntity(Id, winnerId, Players[0].Decision!.Value, Players[1].Decision!.Value, CurrentTurnIndex);
foreach (var player in Players)
player.Decision = null;
CurrentTurnIndex++;
Expand Down
30 changes: 29 additions & 1 deletion Game/Domain/GameTurnEntity.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,35 @@
using System;
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
public class GameTurnEntity
{
//TODO: Придумать какие свойства должны быть в этом классе, чтобы сохранять всю информацию о закончившемся туре.
public Guid Id { get; set; }

[BsonElement]
public Guid GameId { get; }

[BsonElement]
public Guid WinnerId { get; }

[BsonElement]
public PlayerDecision FirstPlayerDecision { get; }

[BsonElement]
public PlayerDecision SecondPlayerDecision { get; }

[BsonElement]
public int TurnIndex { get; }

[BsonConstructor]
public GameTurnEntity(Guid gameId, Guid winnerId, PlayerDecision firstPlayerDecision, PlayerDecision secondPlayerDecision, int turnIndex)
{
GameId = gameId;
WinnerId = winnerId;
FirstPlayerDecision = firstPlayerDecision;
SecondPlayerDecision = secondPlayerDecision;
TurnIndex = turnIndex;
}
}
}
7 changes: 6 additions & 1 deletion Game/Domain/IGameTurnRepository.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
using System;
using System.Collections.Generic;

namespace Game.Domain
{
public interface IGameTurnRepository
{
// TODO: Спроектировать интерфейс исходя из потребностей ConsoleApp
GameTurnEntity Insert(GameTurnEntity turn);

IList<GameTurnEntity> FindLastTurns(Guid gameId, int turnsCount = 5);
}
}
28 changes: 20 additions & 8 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,51 @@ 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 db, bool dropCollection = true)
{
if (dropCollection)
db.DropCollection(CollectionName);

gameCollection = db.GetCollection<GameEntity>(CollectionName);
}

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

public GameEntity FindById(Guid gameId)
{
throw new NotImplementedException();
var filter = Builders<GameEntity>.Filter.Eq(g => g.Id, gameId);
return gameCollection.Find(filter).FirstOrDefault();
}

public void Update(GameEntity game)
{
throw new NotImplementedException();
var filter = Builders<GameEntity>.Filter.Eq(g => g.Id, game.Id);
gameCollection.ReplaceOne(filter, game);
}

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

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

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

public MongoGameTurnRepository(IMongoDatabase db, bool dropCollection = true)
{
if (dropCollection)
db.DropCollection(CollectionName);

turnsCollection = db.GetCollection<GameTurnEntity>(CollectionName);

var indexBuilder = Builders<GameTurnEntity>.IndexKeys.Ascending(entity => entity.GameId);
var createIndexModel = new CreateIndexModel<GameTurnEntity>(indexBuilder);
turnsCollection.Indexes.CreateOne(createIndexModel);
indexBuilder = Builders<GameTurnEntity>.IndexKeys.Descending(entity => entity.TurnIndex);
createIndexModel = new CreateIndexModel<GameTurnEntity>(indexBuilder);
turnsCollection.Indexes.CreateOne(createIndexModel);
}


public GameTurnEntity Insert(GameTurnEntity turn)
{
turnsCollection.InsertOne(turn);
return turn;
}

public IList<GameTurnEntity> FindLastTurns(Guid gameId, int turnsCount = 5)
{
var filterBuilder = Builders<GameTurnEntity>.Filter;
var filter = filterBuilder.Eq(entity => entity.GameId, gameId);
var lastTurns = turnsCollection.Find(filter).SortByDescending(t => t.TurnIndex).Limit(turnsCount).ToList();
lastTurns.Reverse();
return lastTurns;
}
}
}
51 changes: 39 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 @@ -8,46 +9,72 @@ public class MongoUserRepository : IUserRepository
private readonly IMongoCollection<UserEntity> userCollection;
public const string CollectionName = "users";

public MongoUserRepository(IMongoDatabase database)
public MongoUserRepository(IMongoDatabase database, bool dropCollection = true)
{
if (dropCollection)
database.DropCollection(CollectionName);

userCollection = database.GetCollection<UserEntity>(CollectionName);
userCollection.Indexes.CreateOne(Builders<UserEntity>.IndexKeys.Ascending(e => e.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();
var filter = new BsonDocument("_id", id);
return userCollection.Find(filter).FirstOrDefault();
}

public UserEntity GetOrCreateByLogin(string login)
{
//TODO: Это Find или Insert
throw new NotImplementedException();
var filter = new BsonDocument("Login", login);
var user = userCollection.Find(filter).FirstOrDefault();
if (user is null)
{
user = new UserEntity { Login = login };
try
{
userCollection.InsertOne(user);
}
catch (MongoWriteException)
{
user = userCollection.Find(filter).FirstOrDefault();
}
}

return user;
}

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

public void Delete(Guid id)
{
throw new NotImplementedException();
var filter = new BsonDocument("_id", id);
userCollection.DeleteOne(filter);
}

// Для вывода списка всех пользователей (упорядоченных по логину)
// страницы нумеруются с единицы
public PageList<UserEntity> GetPage(int pageNumber, int pageSize)
{
//TODO: Тебе понадобятся SortBy, Skip и Limit
throw new NotImplementedException();
var findResult = userCollection.Find(FilterDefinition<UserEntity>.Empty)
.SortBy(entity => entity.Login)
.Skip((pageNumber - 1) * pageSize)
.Limit(pageSize);
return new PageList<UserEntity>(
findResult.ToList(),
userCollection.CountDocuments(FilterDefinition<UserEntity>.Empty),
pageNumber,
pageSize);
}

// Не нужно реализовывать этот метод
Expand Down
5 changes: 5 additions & 0 deletions 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,21 @@ 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
Loading