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

Александров, Кочергин, Заикин, Ковальчук #44

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
7 changes: 5 additions & 2 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using Game.Domain;
using MongoDB.Driver;

namespace ConsoleApp
{
Expand All @@ -9,11 +10,13 @@ class Program
private readonly IUserRepository userRepo;
private readonly IGameRepository gameRepo;
private readonly Random random = new Random();
private readonly string mongoConnectionString = Environment.GetEnvironmentVariable("PROJECT5100_MONGO_CONNECTION_STRING") ?? "mongodb://localhost:27017?maxConnecting=100";

private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
gameRepo = new InMemoryGameRepository();
var db = new MongoClient(mongoConnectionString).GetDatabase("game");
userRepo = new MongoUserRepository(db);
gameRepo = new MongoGameRepository(db);
}

public static void Main(string[] args)
Expand Down
9 changes: 9 additions & 0 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 @@ -22,19 +25,24 @@ public GameEntity(Guid id, GameStatus status, int turnsCount, int currentTurnInd
this.players = players;
}

[BsonElement]
public Guid Id
{
get;
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Local For MongoDB
private set;
}

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

[BsonElement]
public int TurnsCount { get; }

[BsonElement]
public int CurrentTurnIndex { get; private set; }

[BsonElement]
public GameStatus Status { get; private set; }

public void AddPlayer(UserEntity user)
Expand All @@ -59,6 +67,7 @@ public void Cancel()
Status = GameStatus.Canceled;
}

[BsonElement]
public bool HaveDecisionOfEveryPlayer => Players.All(p => p.Decision.HasValue);

public void SetPlayerDecision(Guid userId, PlayerDecision decision)
Expand Down
21 changes: 14 additions & 7 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,45 @@ namespace Game.Domain
public class MongoGameRepository : IGameRepository
{
public const string CollectionName = "games";
private readonly IMongoCollection<GameEntity> gameCollection;

public MongoGameRepository(IMongoDatabase db)
{
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 result = gameCollection.Find(game => game.Id == gameId);
return result.FirstOrDefault();
}

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

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

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

namespace Game.Domain
{
Expand All @@ -11,43 +13,60 @@ public class MongoUserRepository : IUserRepository
public MongoUserRepository(IMongoDatabase database)
{
userCollection = database.GetCollection<UserEntity>(CollectionName);
userCollection.Indexes.CreateOne(new CreateIndexModel<UserEntity>(
Builders<UserEntity>.IndexKeys.Ascending(u => u.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 result = userCollection.Find(user => user.Id == id);
return result.FirstOrDefault();
}

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

var userEntity = new UserEntity(Guid.NewGuid())
{
Login = login
};
Insert(userEntity);
return userEntity;
}

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

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

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

return new PageList<UserEntity>(items, 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