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

Мирошник и Морозов ФТ402, Бабинцев ФТ-304, Скоморохов ФТ-404 #47

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
15 changes: 10 additions & 5 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
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();

private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
gameRepo = new InMemoryGameRepository();
var mongoConnectionString = Environment.GetEnvironmentVariable("PROJECT5100_MONGO_CONNECTION_STRING")
?? "mongodb://localhost:27017?maxConnecting=100";
var mongoClient = new MongoClient(mongoConnectionString);
var dataBase = mongoClient.GetDatabase("game-tests");
userRepo = new MongoUserRepository(dataBase);
gameRepo = new MongoGameRepository(dataBase);
}

public static void Main(string[] args)
Expand Down Expand Up @@ -184,4 +189,4 @@ private void ShowScore(GameEntity game)
Console.WriteLine($"Score: {players[0].Name} {players[0].Score} : {players[1].Score} {players[1].Name}");
}
}
}
}
11 changes: 8 additions & 3 deletions Game/Domain/GameEntity.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -6,13 +7,15 @@ 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,21 @@ 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 Down
2 changes: 2 additions & 0 deletions Game/Domain/GameStatus.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
public enum GameStatus
Expand Down
23 changes: 17 additions & 6 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@

using System;
using System.Collections.Generic;
using DnsClient;
using MongoDB.Driver;

namespace Game.Domain
Expand All @@ -8,38 +10,47 @@ namespace Game.Domain
public class MongoGameRepository : IGameRepository
{
public const string CollectionName = "games";
public 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 gameEntity = gameCollection.Find(game => game.Id == gameId).FirstOrDefault();

return gameEntity;
}

public void Update(GameEntity game)
{
throw new NotImplementedException();
gameCollection.ReplaceOne(oldGame => oldGame.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 result = gameCollection.ReplaceOne(x => x.Id == game.Id && x.Status == GameStatus.WaitingToStart, game);
return result.IsAcknowledged && result.ModifiedCount > 0;
}
}
}
36 changes: 26 additions & 10 deletions Game/Domain/MongoUserRepositoty.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System;
using System.Collections.Generic;
using DnsClient;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Game.Domain
Expand All @@ -11,43 +14,56 @@ public class MongoUserRepository : IUserRepository
public MongoUserRepository(IMongoDatabase database)
{
userCollection = database.GetCollection<UserEntity>(CollectionName);
var keys = Builders<UserEntity>.IndexKeys.Ascending("Login");
var options = new CreateIndexOptions { Unique = true };
var indexModel = new CreateIndexModel<UserEntity>(keys, options);
userCollection.Indexes.CreateOne(indexModel);
}

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

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

public UserEntity GetOrCreateByLogin(string login)
{
//TODO: Это Find или Insert
throw new NotImplementedException();
var filter = Builders<UserEntity>.Filter.Eq("Login", login);
var user = userCollection.Find(filter).FirstOrDefault() ?? Insert(new UserEntity(Guid.Empty, login, "last", "first", 2, Guid.NewGuid()));
return user;
}

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

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();
int skip = (pageNumber - 1) * pageSize;
var filter = Builders<UserEntity>.Filter.Empty;
var sort = Builders<UserEntity>.Sort.Ascending("Login");
var cursor = userCollection.Find(filter).Sort(sort).Skip(skip).Limit(pageSize).ToCursor();
var documents = cursor.ToList();
long totalCount = userCollection.CountDocuments(filter);
return new PageList<UserEntity>(documents, totalCount, pageNumber, pageSize);

}

// Не нужно реализовывать этот метод
Expand Down
11 changes: 8 additions & 3 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,31 @@ 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; }
}
}
4 changes: 2 additions & 2 deletions Game/Domain/UserEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ public Guid Id
public string Login { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }

/// <summary>
/// Количество сыгранных игр
/// </summary>
public int GamesPlayed { get; set; }

/// <summary>
/// Идентификатор игры, в которой этот пользователь участвует.
/// Нужен, чтобы искать игру по первичному индексу, а не по полю Games.Players.UserId. В частности, чтобы не создавать дополнительный индекс на Games.Players.UserId
Expand Down