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

Цеханович Никита #26

Open
wants to merge 3 commits 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
17 changes: 12 additions & 5 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
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 MongoUserRepository userRepo;
private readonly MongoGameRepository gameRepo;
private readonly Random random = new Random();


[Obsolete("Obsolete")]
private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
gameRepo = new InMemoryGameRepository();
var mongoConnectionString = Environment.GetEnvironmentVariable("PROJECT5100_MONGO_CONNECTION_STRING")
?? "mongodb://localhost:27017";
var mongoClient = new MongoClient(mongoConnectionString);
var db = mongoClient.GetDatabase("game");

userRepo = new MongoUserRepository(db);
gameRepo = new MongoGameRepository(db);
}

public static void Main(string[] args)
Expand Down
12 changes: 10 additions & 2 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,21 +25,26 @@ 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)
{
if (Status != GameStatus.WaitingToStart)
Expand Down
29 changes: 21 additions & 8 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,55 @@

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

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

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

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

public void Update(GameEntity game)
{
throw new NotImplementedException();
if (FindById(game.Id) == null)
{
Insert(game);
}
else
{
gameCollection.ReplaceOne(gameCollection => gameCollection.Id == game.Id, game);
}
}

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

// Обновляет игру, если она находится в статусе GameStatus.WaitingToStart
public bool TryUpdateWaitingToStart(GameEntity game)
{
//TODO: Для проверки успешности используй IsAcknowledged и ModifiedCount из результата
throw new NotImplementedException();
var foundGame = FindById(game.Id);
if (foundGame is not { Status: GameStatus.WaitingToStart }) return false;
Update(game);
return true;
}
}
}
44 changes: 33 additions & 11 deletions Game/Domain/MongoUserRepositoty.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using MongoDB.Driver;
using MongoDB.Bson;

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

[Obsolete("Obsolete")]
public MongoUserRepository(IMongoDatabase database)
{
userCollection = database.GetCollection<UserEntity>(CollectionName);
userCollection.Indexes.CreateOne(
new IndexKeysDefinitionBuilder<UserEntity>().Ascending(nameof(UserEntity.Login)),
new CreateIndexOptions
{
Unique = true,
Name = "login_index"
});
}

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

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

public UserEntity GetOrCreateByLogin(string login)
{
//TODO: Это Find или Insert
throw new NotImplementedException();
return userCollection.Find(userEntity => userEntity.Login == login).FirstOrDefault() ?? Insert(new UserEntity
{
Login = login
});
}

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

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

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

return new PageList<UserEntity>(users, userCollection.Find(_ => true).CountDocuments(), pageNumber, pageSize);
}

// Не нужно реализовывать этот метод
Expand Down
6 changes: 6 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,27 +8,32 @@ 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>
/// Ход, который выбрал игрок
/// </summary>
[BsonElement]
public PlayerDecision? Decision { get; set; }

/// <summary>
/// Текущие очки в игре. Сколько туров выиграл этот игрок.
/// </summary>
[BsonElement]
public int Score { get; set; }
}
}