text stringlengths 1 2.12k | source dict |
|---|---|
c#, .net, hash-map
var node = new HierarchicalNode<T>(item, parent);
dict.Add(key, node);
}
GetDescendantsOfByKey() and GetAncestorsOfByKey() here you should check if the passed key exists.
public IEnumerable<T> GetDescendantsOfByKey(Key key)
{
if (!dict.TryGetValue(key, out var node))
{
throw new KeyNotFoundException($"An object with the key[{ key }] doesn't exists");
}
return node.GetDescendants();
}
public IEnumerable<T> GetAncestorsOfByKey(Key key)
{
if (!dict.TryGetValue(key, out var node))
{
throw new KeyNotFoundException($"An object with the key[{ key }] doesn't exists");
}
return node.GetAncestors();
}
The Func<T, Key> getParentKey; should have an access modifier as well. | {
"domain": "codereview.stackexchange",
"id": 44909,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map",
"url": null
} |
c#, multithreading, asynchronous
Title: Single worker, multiple async callers in different threads
Question: My use case is this:
There is a long running process that I want to ensure is only ever running at most only a single time.
Multiple consumers from different threads may wait on the calculation.
If the process is not running, the first consumer triggers it.
Here is the code:
public class Worker {
private int _working;
private TaskCompletionSource? _tcs;
public async Task DoWorkAsync() {
var triggerWork = false;
if (Interlocked.CompareExchange(ref _working, 1, 0) == 0) {
triggerWork = true;
_tcs = new TaskCompletionSource();
}
if (!triggerWork) {
await _tcs!.Task;
/*
* Point of interest: previous worker might have just finished,
* and a new worker might have started - but that is ok because
* "DoWorkInternalAsync" is a transactioned operation.
*/
return;
}
await DoWorkInternalAsync();
_tcs!.SetResult();
_working = 0;
}
private async Task DoWorkInternalAsync() {
// Do work
}
}
I would like a review for my code for efficiency and correctness, and also I'd be happy to hear suggestions on how to do it more succinctly (perhaps with the use of a library or some BCL class I might have missed)
Thanks
Answer: Your code looks ok with respect to correctness, but I have not tested it.
One option to make it shorter is to cache the task directly. As you have Task (and not ValueTask) you may await it many times.
So more like this:
public class Worker
{
private object _lock = new();
private Task<int>? _task;
public Task<int> DoWorkAsync()
{
return _task ?? SetTaskIfNull();
Task<int> SetTaskIfNull()
{
lock (_lock)
return _task ??= DoWorkInternalAsync();
}
} | {
"domain": "codereview.stackexchange",
"id": 44910,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, asynchronous",
"url": null
} |
c#, multithreading, asynchronous
private async Task<int> DoWorkInternalAsync()
{
await Console.Out.WriteLineAsync("Start calc");
await Task.Delay(1000);
await Console.Out.WriteLineAsync("Calc done");
return 10;
}
}
You do not need to await on the child operation when you only want to return the task. This means you can use the lock statement and the code will be easier to read.
The first null check avoid the lock, if the task is already there. The second null check prevents duplicate creation.
So it appears that you want to restart the calculation in case that there is only a completed one?
Then I'd suggest this:
public class Worker
{
private object _lock = new();
private Task<int>? _task;
public Task<int> DoWorkAsync()
{
lock(_lock)
{
// null would mean that this thread is the first
// true means we need to restart
if ((_task?.IsCompleted) != false)
_task = DoWorkInternalAsync(1);
return _task;
}
}
private async Task<int> DoWorkInternalAsync(int v)
{
await Console.Out.WriteLineAsync("Start calc");
await Task.Delay(1000);
await Console.Out.WriteLineAsync("Calc done");
return v;
}
} | {
"domain": "codereview.stackexchange",
"id": 44910,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, asynchronous",
"url": null
} |
beginner, rust
Title: Disprove Euler's sum-of-powers conjecture
Question: Problem statement: In 1769 Leonhard Euler formulated a generalized version of Fermat's Last Theorem, conjecturing that at least \$n\$ \$\text{n}_{\text{th}}\$ powers are needed to obtain a sum that is itself an \$\text{n}_{\text{th}}\$ power, for \$n > 2\$. Write a program to disprove Euler's conjecture (which stood until 1967). That is, find \$a\$, \$b\$, \$c\$, \$d\$, and \$e\$ such that \$a^5 + b^5 + c^5 + d^5 = e^5\$.
This is one of my self-imposed challenges in Rust to become better at it. The problem was taken from Sedgewick Exercise 1.3.46.
Here is my code:
use clap::Parser;
use std::ops::RangeFrom;
use std::process::exit;
type Euler = Vec<(usize, usize, usize, usize, usize)>;
const VALID_SEARCH_UPPER_BOUNDS: RangeFrom<usize> = 1..;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
search_upper_bound: usize,
}
fn main() {
let arguments = Arguments::parse();
let search_upper_bound = arguments.search_upper_bound;
let Ok(numbers) = disprove_euler_conjecture(search_upper_bound) else {
eprintln!("Search upper bound must be at least {}.", VALID_SEARCH_UPPER_BOUNDS.start);
exit(1);
};
if numbers.is_empty() {
eprintln!("Search upper bound is too small.")
} else {
for tuple in numbers {
let a = tuple.0;
let b = tuple.1;
let c = tuple.2;
let d = tuple.3;
let e = tuple.4;
println!("{a}⁵ + {b}⁵ + {c}⁵ + {d}⁵ = {e}⁵");
}
}
}
fn disprove_euler_conjecture(search_upper_bound: usize) -> Result<Euler, String> {
if !VALID_SEARCH_UPPER_BOUNDS.contains(&search_upper_bound) {
return Err(format!(
"Search upper bound must be at least {}.",
VALID_SEARCH_UPPER_BOUNDS.start,
));
}
let mut numbers: Vec<(usize, usize, usize, usize, usize)> = Vec::new(); | {
"domain": "codereview.stackexchange",
"id": 44911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
let mut numbers: Vec<(usize, usize, usize, usize, usize)> = Vec::new();
for e in 1..search_upper_bound {
let e5 = e.pow(5);
for a in 1..search_upper_bound {
let a5 = a.pow(5);
if a5 > e5 {
break;
}
for b in a..search_upper_bound {
let b5 = b.pow(5);
if a5 + b5 > e5 {
break;
}
for c in b..search_upper_bound {
let c5 = c.pow(5);
if a5 + b5 + c5 > e5 {
break;
}
for d in c..search_upper_bound {
let d5 = d.pow(5);
if a5 + b5 + c5 + d5 > e5 {
break;
}
if a5 + b5 + c5 + d5 == e5 {
numbers.push((a, b, c, d, e));
}
}
}
}
}
}
Ok(numbers)
}
Is there any way that I can improve my code?
Answer: Another good question, and much of the advice I gave on your previous one applies. I’ll try to repeat myself as little as possible.
The Loops Could be Improved
Currently you have a deeply-nested loop whose layers all have code like
for a in 1..search_upper_bound {
let a5 = a.pow(5);
if a5 > e5 {
break;
} | {
"domain": "codereview.stackexchange",
"id": 44911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
if a5 > e5 {
break;
}
This performs two checks and conditional branches per iteration, which are slow. A vectorizing or parallelizing compiler probably won’t know what to do with it, either.
It also means that the declared range of the loop is actively misleading, and the actual termination check is a break inside the loop, where a maintainer might not think to look. It would be better to compute the bounds of the search before starting it, and set the range of the loop to that. Next best would be to set the range to 1,,, a.., b.. or something like that, or even use a loop with no condition, to make it obvious that something within the loop must break.
Eliminate at Least One Level of the Loop
What jumps out at me is, there’s a valid Diophantine solution for a⁵ + b⁵ + c⁵ + d⁵ = e⁵, if and only if, for some a, there is a solution to b⁵ + c⁵ + d⁵ = e⁵ - a⁵, there’s a solution to that if and only if, given a and b, there’s a solution for c⁵ + d⁵ = e⁵ - a⁵ - b⁵. and at that point, given c, you can directly solve for d.
Consider a Tail-Recursive Implementation
I wouldn’t recommend this as easily in Rust as I would in a language that guaranteed tail-call optimization. However, the four steps of the algorithm I outlined above could be expressed as four helper functions, three of which might be one-liners using flat_map. That would be easier to read and maintain.
Use Pattern Destructuring
You currently have:
for tuple in numbers {
let a = tuple.0;
let b = tuple.1;
let c = tuple.2;
let d = tuple.3;
let e = tuple.4;
This could be:
for (a,b,c,d,e) in numbers { | {
"domain": "codereview.stackexchange",
"id": 44911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
Avoid Passing Unrecoverable Logic Errors up the Stack
Currently, you’re returning a Result that can only fail if the search is called with an incorrect set of bounds. But that is a logic error, not something you want to have to check every call for. It could happen at runtime, if you’re reading the bounds from user input, but in this case, I think I would have disprove_euler_conjecture just panic if called with invalid inputs. In fact, is there a compelling reason the bound needs to be user-specified at all? The function just searches for a counterexample, and could treat any suggestion you give it about a bound as an advisory hint.
The caller is currently checking for this error anyway (in fact, it completely ignores the Err value and assumes there’s only one kind of error, an indication that this should actually be an Option instead of a Result), and aborting, so there’s no benefit to returning Err in this program. In fact, that’s worse for debugging, because you’ve partially unwound the stack and lost both the value that caused the bug and the line of code where it was detected! If you had instead called panic! within disprove_euler_conjecture, you can often set RUST_BACKTRACE=1 and get a lot of the information reproducing the bug in a debugger would have given you. Although you never want the end user to see a panic, it’s a great way to catch logic errors that should be eliminated.
In the rare situation that you are reading in the bound dynamically at runtime, the caller can check the value.
Consider a More Intuitive Return Type
You currently return a Result where failure to find a counterexample is represented by Ok (vec![]). It’s counterintuitive to have to unwrap the return object and then also check that the unwrapped value is valid. You also are searching the entire space first and then finding all counterexamples, rather than stopping when you find the first.
The return type should probably be Option<(usize, usize, usize, usize, usize)>. | {
"domain": "codereview.stackexchange",
"id": 44911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
The return type should probably be Option<(usize, usize, usize, usize, usize)>.
Prefer Iterator Expressions to Appending
There would be some new syntax to learn if you turn the loop into an expression with type impl Iterator<Item = (usize, usize, usize, usize, usize)>, but that have several advantages.
One is that iterators can evaluate lazily and short-circuit when they find a counterexample. That probably removes the motivation for you to implement this as a function that searches a block and can restart at a certain range. You’re probably only doing it that way because you have to search the whole range before returning any results.
Another is that you can easily take the same code to generate the solutions and have it return a short-circuiting Option by adding .nth(1) at the end, or fill any collection with them by adding .collect(). Or you could call Iterator::for_each on it, or use it as the range expression of a for loop, to print each value found immediately and keep searching. It’s extremely flexible!
Another is that you can often get an expression that it’s easier to prove correct than a loop whose termination conditions are buried in a break statement nested five levels deep.
Mainly, though, mutable variables can have several categories of bugs that immutable state cannot, so you should be getting some significant benefit from mutable data to make up for that. | {
"domain": "codereview.stackexchange",
"id": 44911,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
c#, game, mvc, winforms, chess
Title: 2-Player Chess in WinForms V.2 (With Separation of Concerns)
Question: Introduction
After getting initial feedback on my first working version of this Chess WinForms game here, I have used the suggestions and comments from there to come up with this new version, trying to follow the MVC design pattern.
Here is the Github repo (as of writing, is under the Separating_Concerns branch):
https://github.com/Shinglington/prjChessForms
Code
I've split up this section into parts based on the MVC design pattern.
Model
Compared to my previous post, a Chess object now does not handle the UI.
Chess
using prjChessForms.Controller;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
namespace prjChessForms.MyChessLibrary
{
enum PromotionOption
{
Queen,
Rook,
Knight,
Bishop,
}
class Chess
{
public event EventHandler<PieceSelectionChangedEventArgs> PieceSelectionChanged;
public event EventHandler<PlayerTimerTickEventArgs> PlayerTimerTick;
public event EventHandler<PlayerCapturedPiecesChangedEventArgs> PlayerCapturedPiecesChanged;
public event EventHandler<PromotionEventArgs> PlayerPromotion;
public event EventHandler<GameOverEventArgs> GameOver;
private Board _board;
private System.Timers.Timer _timer;
private CancellationTokenSource cts = new CancellationTokenSource();
private GameResult _result;
private Player[] _players;
private int _turnCount; | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private Player[] _players;
private int _turnCount;
private SemaphoreSlim _semaphoreReceiveClick = new SemaphoreSlim(0, 1);
private Coords _clickedCoords;
private PromotionOption _selectedPromotion;
private bool _waitingForClick, _waitingForPromotion;
public Chess()
{
CreatePlayers(new TimeSpan(0, 10, 0));
_board = new Board(_players);
_timer = new System.Timers.Timer(1000);
_waitingForClick = false;
}
public Player CurrentPlayer { get { return _players[_turnCount % 2]; } }
public Player WhitePlayer { get { return _players[0]; } }
public Player BlackPlayer { get { return _players[1]; } }
public Square[,] BoardSquares { get { return _board.GetSquares(); } }
public Piece GetPieceAt(Coords coords) => _board.GetPieceAt(coords);
public Coords GetCoordsOf(Piece piece) => _board.GetCoordsOfPiece(piece);
public async Task StartGame()
{
await Play(cts.Token);
OnGameOver();
}
public void SendCoords(Coords coords)
{
if (_waitingForClick)
{
Debug.WriteLine("Model received coords input of {0}", coords);
_clickedCoords = coords;
_semaphoreReceiveClick.Release();
}
}
public void SendPromotion(PromotionOption option)
{
if (_waitingForPromotion)
{
Debug.WriteLine("Promotion received to {0}", option.ToString());
_selectedPromotion = option;
_semaphoreReceiveClick.Release();
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public void AttachModelObserver(IModelObserver observer)
{
_board.PieceInSquareChanged += new EventHandler<PieceChangedEventArgs>(observer.OnPieceInSquareChanged);
PieceSelectionChanged += new EventHandler<PieceSelectionChangedEventArgs>(observer.OnPieceSelectionChanged);
PlayerTimerTick += new EventHandler<PlayerTimerTickEventArgs>(observer.OnPlayerTimerTick);
PlayerCapturedPiecesChanged += new EventHandler<PlayerCapturedPiecesChangedEventArgs>(observer.OnPlayerCapturedPiecesChanged);
PlayerPromotion += new EventHandler<PromotionEventArgs>(observer.OnPromotion);
GameOver += new EventHandler<GameOverEventArgs>(observer.OnGameOver);
foreach(Square s in _board.GetSquares())
{
observer.OnPieceInSquareChanged(this, new PieceChangedEventArgs(s, s.Piece));
}
observer.OnPlayerTimerTick(this, new PlayerTimerTickEventArgs(WhitePlayer));
observer.OnPlayerTimerTick(this, new PlayerTimerTickEventArgs(BlackPlayer));
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private async Task Play(CancellationToken cToken)
{
_turnCount = 0;
_result = GameResult.Unfinished;
_timer.Elapsed += OnPlayerTimerTick;
while (_result == GameResult.Unfinished)
{
try
{
ChessMove move = await GetChessMove(cToken);
CapturePiece(Rulebook.MakeMove(_board, CurrentPlayer, move));
ChangeSelection(null);
if (Rulebook.RequiresPromotion(_board, move.EndCoords))
{
await Promotion(move.EndCoords, cToken);
}
_turnCount++;
_result = Rulebook.GetGameResult(_board, CurrentPlayer);
}
catch when (cToken.IsCancellationRequested)
{
Debug.WriteLine("Cancelled Play");
_waitingForClick = false;
_result = GameResult.Time;
}
}
_timer.Elapsed -= OnPlayerTimerTick;
cts.Cancel();
}
private async Task<ChessMove> GetChessMove(CancellationToken cToken)
{
Coords fromCoords = Coords.Null;
Coords toCoords = Coords.Null;
ChessMove move = new ChessMove();
bool completeInput = false;
_waitingForClick = true;
_timer.Start();
while (!completeInput)
{
Debug.WriteLine("Waiting for click");
await _semaphoreReceiveClick.WaitAsync(cToken);
Debug.WriteLine("Received click at {0}", _clickedCoords); | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
if (GetPieceAt(_clickedCoords) != null && GetPieceAt(_clickedCoords).Owner.Equals(CurrentPlayer))
{
ChangeSelection(GetPieceAt(_clickedCoords));
fromCoords = _clickedCoords;
toCoords = Coords.Null;
}
else if (!fromCoords.Equals(Coords.Null))
{
toCoords = _clickedCoords;
}
// Check if move is valid now
if (!toCoords.IsNull && !fromCoords.IsNull && Rulebook.CheckLegalMove(_board, CurrentPlayer, new ChessMove(fromCoords, toCoords)))
{
move = new ChessMove(fromCoords, toCoords);
completeInput = true;
}
else
{
toCoords = Coords.Null;
}
}
_waitingForClick = false;
_timer.Stop();
return move;
}
private void CreatePlayers(TimeSpan time)
{
_players = new Player[2];
_players[0] = new HumanPlayer(PieceColour.White, time);
_players[1] = new HumanPlayer(PieceColour.Black, time);
}
private void OnPlayerTimerTick(object sender, ElapsedEventArgs e)
{
TimeSpan interval = new TimeSpan(0, 0, 1);
if (CurrentPlayer.RemainingTime.Subtract(interval) < TimeSpan.Zero)
{
_timer.Elapsed -= OnPlayerTimerTick;
cts.Cancel();
}
else
{
CurrentPlayer.TickTime(interval);
if (PlayerTimerTick != null)
{
PlayerTimerTick.Invoke(this, new PlayerTimerTickEventArgs(CurrentPlayer));
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private void OnGameOver()
{
cts.Cancel();
Player winner = null;
if (_result == GameResult.Checkmate || _result == GameResult.Time)
{
winner = CurrentPlayer == _players[0] ? _players[1] : _players[0];
}
if (GameOver != null)
{
GameOver.Invoke(this, new GameOverEventArgs(_result, winner));
}
}
private void CapturePiece(Piece p)
{
if (p != null)
{
CurrentPlayer.AddCapturedPiece(p);
if (PlayerCapturedPiecesChanged != null)
{
PlayerCapturedPiecesChanged.Invoke(this, new PlayerCapturedPiecesChangedEventArgs(CurrentPlayer, p));
}
}
}
private void ChangeSelection(Piece selectedPiece)
{
if (PieceSelectionChanged != null)
{
List<Coords> endCoords = new List<Coords>();
Coords selectedCoords = new Coords();
if (selectedPiece != null)
{
selectedCoords = GetCoordsOf(selectedPiece);
foreach (ChessMove m in Rulebook.GetPossibleMoves(_board, selectedPiece))
{
endCoords.Add(m.EndCoords);
}
}
PieceSelectionChanged.Invoke(this, new PieceSelectionChangedEventArgs(selectedPiece, selectedCoords, endCoords));
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private async Task Promotion(Coords promotionCoords, CancellationToken cToken)
{
Player owner = GetPieceAt(promotionCoords).Owner;
Piece promotedPiece = new Queen(owner);
if (PlayerPromotion != null)
{
PlayerPromotion.Invoke(this, new PromotionEventArgs(owner.Colour, promotionCoords));
_waitingForPromotion = true;
await _semaphoreReceiveClick.WaitAsync(cToken);
_waitingForPromotion = false;
switch (_selectedPromotion)
{
case PromotionOption.Knight:
promotedPiece = new Knight(owner);
break;
case PromotionOption.Bishop:
promotedPiece = new Bishop(owner);
break;
case PromotionOption.Rook:
promotedPiece = new Rook(owner);
break;
}
}
_board.GetSquareAt(promotionCoords).Piece = promotedPiece;
}
}
}
Board
using System;
using System.Collections.Generic;
namespace prjChessForms.MyChessLibrary
{
class Board
{
public event EventHandler<PieceChangedEventArgs> PieceInSquareChanged;
private const int ROW_COUNT = 8;
private const int COL_COUNT = 8;
private Player[] _players;
private Square[,] _squares;
public Board(Player[] players)
{
_players = players;
SetupBoard();
}
public int RowCount { get { return ROW_COUNT; } }
public int ColumnCount { get { return COL_COUNT; } } | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public void MakeMove(ChessMove Move)
{
Coords StartCoords = Move.StartCoords;
Coords EndCoords = Move.EndCoords;
Piece p = GetPieceAt(StartCoords);
if (p != null)
{
GetSquareAt(EndCoords).Piece = p;
GetSquareAt(StartCoords).Piece = null;
p.HasMoved = true;
}
}
public King GetKing(PieceColour colour)
{
King king = null;
foreach (Piece p in GetPieces(colour))
{
if (p.GetType() == typeof(King))
{
king = (King)p;
break;
}
}
return king;
}
public List<Piece> GetPieces(PieceColour colour)
{
List<Piece> pieces = new List<Piece>();
Piece p;
for (int y = 0; y < ROW_COUNT; y++)
{
for (int x = 0; x < COL_COUNT; x++)
{
p = GetPieceAt(new Coords(x, y));
if (p != null && p.Colour == colour)
{
pieces.Add(p);
}
}
}
return pieces;
}
public Piece GetPieceAt(Coords coords)
{
return (GetSquareAt(coords).Piece);
}
public Coords GetCoordsOfPiece(Piece piece)
{
if (piece == null)
{
throw new ArgumentNullException();
}
foreach (Square s in GetSquares())
{
if (s.Piece == piece)
{
return s.Coords;
}
}
throw new Exception("Piece could not be located");
}
public Square[,] GetSquares()
{
return _squares;
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public Square[,] GetSquares()
{
return _squares;
}
public Square GetSquareAt(Coords coords)
{
return _squares[coords.X, coords.Y];
}
public void RemoveGhostPawns()
{
foreach (Square s in GetSquares())
{
if (s.GetGhostPawn() != null)
{
s.Piece = null;
}
}
}
public bool CheckMoveInCheck(Player player, ChessMove move)
{
Coords start = move.StartCoords;
Coords end = move.EndCoords;
bool startPieceHasMoved = GetPieceAt(start).HasMoved;
Piece originalEndPiece = GetPieceAt(end);
MakeMove(move);
bool SelfCheck = Rulebook.IsInCheck(this, player);
MakeMove(new ChessMove(end, start));
GetSquareAt(start).Piece.HasMoved = startPieceHasMoved;
GetSquareAt(end).Piece = originalEndPiece;
return SelfCheck;
}
private void SetupBoard()
{
_squares = new Square[COL_COUNT, ROW_COUNT];
Square s;
for (int y = 0; y < ROW_COUNT; y++)
{
for (int x = 0; x < COL_COUNT; x++)
{
s = new Square(x, y);
s.PieceChanged += OnPieceInSquareChanged;
_squares[x, y] = s;
}
}
AddDefaultPieces();
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private void AddDefaultPieces()
{
char[,] defaultPieces =
{
{ 'P','P','P','P','P','P','P','P'},
{ 'R','N','B','Q','K','B','N','R'}
};
Player player;
Square square;
for (int i = 0; i < 2; i++)
{
player = _players[i];
for (int y = 0; y < 2; y++)
{
for (int x = 0; x < COL_COUNT; x++)
{
if (player.Colour == PieceColour.White)
{
square = GetSquareAt(new Coords(x, 1 - y));
}
else
{
square = GetSquareAt(new Coords(x, ROW_COUNT - 2 + y));
}
AddPiece(defaultPieces[y, x], player, square);
}
}
}
}
private void AddPiece(char pieceType, Player player, Square square)
{
Piece p = null;
switch (pieceType)
{
case 'P':
p = new Pawn(player);
break;
case 'N':
p = new Knight(player);
break;
case 'B':
p = new Bishop(player);
break;
case 'R':
p = new Rook(player);
break;
case 'Q':
p = new Queen(player);
break;
case 'K':
p = new King(player);
break;
default:
throw new ArgumentException("Unrecognised pieceType");
}
square.Piece = p;
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private void OnPieceInSquareChanged(object sender, PieceChangedEventArgs e)
{
if (PieceInSquareChanged != null)
{
PieceInSquareChanged.Invoke(this, e);
}
}
}
}
Square
using System;
namespace prjChessForms.MyChessLibrary
{
class Square
{
public EventHandler<PieceChangedEventArgs> PieceChanged;
private Piece _piece;
public Square(int x, int y)
{
Coords = new Coords(x, y);
_piece = null;
}
public Piece Piece
{
get
{
if (_piece != null && _piece.GetType() == typeof(GhostPawn))
{
return null;
}
return _piece;
}
set
{
_piece = value;
if (PieceChanged != null)
{
PieceChanged.Invoke(this, new PieceChangedEventArgs(this, Piece));
}
}
}
public Coords Coords { get; }
public GhostPawn GetGhostPawn()
{
return (_piece != null && _piece.GetType() == typeof(GhostPawn)) ? (GhostPawn)_piece : null;
}
}
}
Piece
using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.CompilerServices; | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
namespace prjChessForms.MyChessLibrary
{
public enum PieceColour
{
White,
Black
}
abstract class Piece
{
public Piece(Player player)
{
Owner = player;
string imageName = Colour.ToString() + "_" + this.GetType().Name;
try
{
Image = (Image)Properties.Resources.ResourceManager.GetObject(imageName);
}
catch
{
Image = null;
}
}
public bool HasMoved { get; set; }
public Player Owner { get; }
public Image Image { get; }
public PieceColour Colour { get { return Owner.Colour; } }
public string Name { get { return GetType().Name; } }
public string Fullname { get { return $"{Colour} {Name}"; } }
public override string ToString()
{
return Fullname;
}
public abstract bool CanMove(Board board, Coords startCoords, Coords endCoords);
}
class Pawn : Piece
{
public Pawn(Player player) : base(player) { } | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
class Pawn : Piece
{
public Pawn(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
int direction = yChange > 0 ? 1 : -1;
if (direction != (Owner.Colour == PieceColour.White ? 1 : -1))
{
return false;
}
if (xChange == 0 && board.GetPieceAt(endCoords) == null)
{
if (Math.Abs(yChange) == 1)
{
allowed = true;
}
else if (Math.Abs(yChange) == 2 && !HasMoved
&& board.GetPieceAt(new Coords(startCoords.X, startCoords.Y + direction)) == null)
{
allowed = true;
}
}
if (Math.Abs(xChange) == 1 && Math.Abs(yChange) == 1)
{
if (board.GetPieceAt(endCoords) != null)
{
allowed = true;
}
}
return allowed;
}
}
class GhostPawn : Piece
{
public GhostPawn(Player player, Pawn referencedPawn) : base(player)
{
LinkedPawn = referencedPawn;
}
public Pawn LinkedPawn { get; }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
return false;
}
}
class Knight : Piece
{
public Knight(Player player) : base(player) { } | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
class Knight : Piece
{
public Knight(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = Math.Abs(endCoords.X - startCoords.X);
int yChange = Math.Abs(endCoords.Y - startCoords.Y);
if ((xChange == 2 && yChange == 1) || (xChange == 1 && yChange == 2))
{
allowed = true;
}
return allowed;
}
}
class Bishop : Piece
{
public Bishop(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (Math.Abs(xChange) == Math.Abs(yChange))
{
allowed = true;
int xDirection = xChange > 0 ? 1 : -1;
int yDirection = yChange > 0 ? 1 : -1;
for (int delta = 1; delta < Math.Abs(xChange); delta += 1)
{
Coords checkCoords = new Coords(startCoords.X + delta * xDirection, startCoords.Y + delta * yDirection);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
}
}
class Rook : Piece
{
public Rook(Player player) : base(player) { } | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
class Rook : Piece
{
public Rook(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (xChange == 0 && yChange != 0)
{
allowed = true;
int direction = yChange > 0 ? 1 : -1;
for (int deltaY = 1; deltaY < Math.Abs(yChange); deltaY += 1)
{
Coords checkCoords = new Coords(startCoords.X, startCoords.Y + deltaY * direction);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
else if (yChange == 0 && xChange != 0)
{
allowed = true;
int direction = xChange > 0 ? 1 : -1;
for (int deltaX = 1; deltaX < Math.Abs(xChange); deltaX += 1)
{
Coords checkCoords = new Coords(startCoords.X + deltaX * direction, startCoords.Y);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
}
}
class Queen : Piece
{
public Queen(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
return BishopMove(board, startCoords, endCoords) || RookMove(board, startCoords, endCoords);
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private bool BishopMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (Math.Abs(xChange) == Math.Abs(yChange))
{
allowed = true;
int xDirection = xChange > 0 ? 1 : -1;
int yDirection = yChange > 0 ? 1 : -1;
for (int delta = 1; delta < Math.Abs(xChange); delta += 1)
{
Coords checkCoords = new Coords(startCoords.X + delta * xDirection, startCoords.Y + delta * yDirection);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
}
private bool RookMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (xChange == 0 && yChange != 0)
{
allowed = true;
int direction = yChange > 0 ? 1 : -1;
for (int deltaY = 1; deltaY < Math.Abs(yChange); deltaY += 1)
{
Coords checkCoords = new Coords(startCoords.X, startCoords.Y + deltaY * direction);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
}
else if (yChange == 0 && xChange != 0)
{
allowed = true;
int direction = xChange > 0 ? 1 : -1;
for (int deltaX = 1; deltaX < Math.Abs(xChange); deltaX += 1)
{
Coords checkCoords = new Coords(startCoords.X + deltaX * direction, startCoords.Y);
if (board.GetPieceAt(checkCoords) != null)
{
allowed = false;
break;
}
}
}
return allowed;
}
}
class King : Piece
{
public King(Player player) : base(player) { }
public override bool CanMove(Board board, Coords startCoords, Coords endCoords)
{
bool allowed = false;
int xChange = endCoords.X - startCoords.X;
int yChange = endCoords.Y - startCoords.Y;
if (Math.Abs(xChange) <= 1 && Math.Abs(yChange) <= 1)
{
allowed = true;
}
return allowed;
}
}
}
Player
using System;
using System.Collections.Generic;
namespace prjChessForms.MyChessLibrary
{
abstract class Player
{
public Player(PieceColour colour, TimeSpan initialTime)
{
Colour = colour;
RemainingTime = initialTime;
CapturedPieces = new List<Piece>();
}
public TimeSpan RemainingTime { get; private set; }
public PieceColour Colour { get; }
public List<Piece> CapturedPieces { get; private set; }
public void TickTime(TimeSpan time)
{
RemainingTime = RemainingTime.Subtract(time);
}
public void AddCapturedPiece(Piece piece)
{
CapturedPieces.Add(piece);
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
}
class HumanPlayer : Player
{
public HumanPlayer(PieceColour colour, TimeSpan initialTime) : base(colour, initialTime) { }
}
class ComputerPlayer : Player
{
public ComputerPlayer(PieceColour colour, TimeSpan initialTime) : base(colour, initialTime) { }
}
}
Rulebook
using System;
using System.Collections.Generic;
namespace prjChessForms.MyChessLibrary
{
public enum GameResult
{
Unfinished,
Checkmate,
Stalemate,
Time
}
public struct ChessMove
{
public ChessMove(Coords startCoords, Coords endCoords)
{
StartCoords = startCoords;
EndCoords = endCoords;
}
public Coords StartCoords { get; }
public Coords EndCoords { get; }
public override string ToString()
{
return StartCoords.ToString() + " -> " + EndCoords.ToString();
}
}
class Rulebook
{
public static Piece MakeMove(Board board, Player player, ChessMove move)
{
if (!CheckLegalMove(board, player, move))
{
throw new ArgumentException(string.Format("Move {0} is not a valid move", move));
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
Piece capturedPiece = board.GetPieceAt(move.EndCoords);
if (IsEnPassant(board, move))
{
GhostPawn ghostPawn = board.GetSquareAt(move.EndCoords).GetGhostPawn();
Coords linkedPawnCoords = board.GetCoordsOfPiece(ghostPawn.LinkedPawn);
capturedPiece = ghostPawn.LinkedPawn;
board.GetSquareAt(linkedPawnCoords).Piece = null;
}
// Remove ghost pawns
board.RemoveGhostPawns();
if (IsDoublePawnMove(board, move))
{
Coords ghostPawnCoords = new Coords(move.StartCoords.X, move.StartCoords.Y + (move.EndCoords.Y - move.StartCoords.Y) / 2);
board.GetSquareAt(ghostPawnCoords).Piece = new GhostPawn(player, (Pawn)board.GetPieceAt(move.StartCoords));
}
else if (IsCastle(board, move))
{
int direction = move.EndCoords.X - move.StartCoords.X > 0 ? 1 : -1;
Coords rookCoords = direction > 0 ? new Coords(board.ColumnCount - 1, move.StartCoords.Y) : new Coords(0, move.StartCoords.Y);
board.MakeMove(new ChessMove(rookCoords, new Coords(move.EndCoords.X + direction * -1, move.EndCoords.Y)));
}
board.MakeMove(move);
return capturedPiece;
}
public static bool CheckLegalMove(Board board, Player player, ChessMove move)
{
Coords start = move.StartCoords;
Coords end = move.EndCoords; | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
bool legal = false;
Piece movedPiece = board.GetPieceAt(start);
Piece capturedPiece = board.GetPieceAt(end);
if (movedPiece != null && movedPiece.Colour == player.Colour && !start.Equals(end))
{
if (IsEnPassant(board, move) || IsCastle(board, move))
{
legal = true;
}
else if (movedPiece.CanMove(board, start, end))
{
if (capturedPiece == null || (capturedPiece.Colour != player.Colour))
{
if (!board.CheckMoveInCheck(player, move))
{
legal = true;
}
}
}
}
return legal;
}
public static List<ChessMove> GetPossibleMoves(Board board, Piece p)
{
List<ChessMove> possibleMoves = new List<ChessMove>();
Coords pieceCoords = board.GetCoordsOfPiece(p);
if (board.GetPieceAt(pieceCoords) != null)
{
Piece piece = board.GetPieceAt(pieceCoords);
ChessMove move;
for (int y = 0; y < board.RowCount; y++)
{
for (int x = 0; x < board.ColumnCount; x++)
{
move = new ChessMove(pieceCoords, new Coords(x, y));
if (CheckLegalMove(board, piece.Owner, move))
{
possibleMoves.Add(move);
}
}
}
}
return possibleMoves;
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public static GameResult GetGameResult(Board board, Player current)
{
if (IsInStalemate(board, current))
{
return GameResult.Stalemate;
}
else if (IsInCheckmate(board, current))
{
return GameResult.Checkmate;
}
else
{
return GameResult.Unfinished;
}
}
public static bool IsInCheck(Board board, Player currentPlayer)
{
bool check = false;
King king = board.GetKing(currentPlayer.Colour);
if (king == null)
{
return true;
}
Coords kingCoords = board.GetCoordsOfPiece(king);
foreach (Square square in board.GetSquares())
{
if (square.Piece != null && square.Piece.Owner != currentPlayer)
{
if (CheckLegalMove(board, square.Piece.Owner, new ChessMove(square.Coords, kingCoords)))
{
check = true;
break;
}
}
}
return check;
}
public static bool RequiresPromotion(Board board, Coords pieceCoords)
{
bool requiresPromotion = false;
Piece p = board.GetPieceAt(pieceCoords);
if (p.GetType() == typeof(Pawn))
{
if (pieceCoords.Y == 0 || pieceCoords.Y == board.RowCount - 1)
{
requiresPromotion = true;
}
}
return requiresPromotion;
}
private static bool IsInCheckmate(Board board, Player currentPlayer)
{
if (!IsInCheck(board, currentPlayer))
{
return false;
}
return !CheckIfThereAreRemainingLegalMoves(board, currentPlayer);
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private static bool IsInStalemate(Board board, Player currentPlayer)
{
if (IsInCheck(board, currentPlayer))
{
return false;
}
return !CheckIfThereAreRemainingLegalMoves(board, currentPlayer);
}
private static bool CheckIfThereAreRemainingLegalMoves(Board board, Player currentPlayer)
{
bool anyLegalMoves = false;
foreach (Piece p in board.GetPieces(currentPlayer.Colour))
{
List<ChessMove> moves = GetPossibleMoves(board, p);
if (moves.Count > 0)
{
anyLegalMoves = true;
break;
}
}
return anyLegalMoves;
}
private static bool IsDoublePawnMove(Board board, ChessMove move)
{
if (board.GetPieceAt(move.StartCoords).GetType() == typeof(Pawn))
{
if (Math.Abs(move.EndCoords.Y - move.StartCoords.Y) == 2)
{
return true;
}
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private static bool IsCastle(Board board, ChessMove move)
{
bool isCastleMove = false;
if (board.GetPieceAt(move.StartCoords).GetType() == typeof(King) && !board.GetPieceAt(move.StartCoords).HasMoved)
{
if (Math.Abs(move.EndCoords.Y - move.StartCoords.Y) == 0 && Math.Abs(move.EndCoords.X - move.StartCoords.X) == 2)
{
int direction = move.EndCoords.X - move.StartCoords.X > 0 ? 1 : -1;
Coords rookCoords = direction > 0 ? new Coords(board.ColumnCount - 1, move.StartCoords.Y) : new Coords(0, move.StartCoords.Y);
Piece p = board.GetPieceAt(rookCoords);
if (p != null && p.GetType() == typeof(Rook) && !p.HasMoved)
{
isCastleMove = true;
Coords currCoords = new Coords(move.StartCoords.X + direction, move.StartCoords.Y);
while (!currCoords.Equals(rookCoords))
{
if (board.GetPieceAt(currCoords) != null || board.CheckMoveInCheck(p.Owner, new ChessMove(move.StartCoords, currCoords)))
{
isCastleMove = false;
break;
}
currCoords = new Coords(currCoords.X + direction, currCoords.Y);
}
}
}
}
return isCastleMove;
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private static bool IsEnPassant(Board board, ChessMove move)
{
if (board.GetPieceAt(move.StartCoords).GetType() == typeof(Pawn))
{
Pawn piece = (Pawn)board.GetPieceAt(move.StartCoords);
int legalDirection = (piece.Colour == PieceColour.White ? 1 : -1);
if (Math.Abs(move.EndCoords.X - move.StartCoords.X) == 1 && move.EndCoords.Y - move.StartCoords.Y == legalDirection)
{
GhostPawn ghostPawn = board.GetSquareAt(move.EndCoords).GetGhostPawn();
if (ghostPawn != null && ghostPawn.Colour != piece.Colour)
{
return true;
}
}
}
return false;
}
}
}
Coords
namespace prjChessForms.MyChessLibrary
{
public struct Coords
{
public static readonly Coords Null = new Coords(-1, -1);
public Coords(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
public bool IsNull => this.Equals(Null);
public override string ToString() => $"{(char)('a' + X)}{Y + 1}";
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != typeof(Coords))
{
return false;
}
else
{
Coords other = (Coords)obj;
return other.X == X && other.Y == Y;
}
}
}
}
ChessEventArgs
using System;
using System.Collections.Generic;
namespace prjChessForms.MyChessLibrary
{
class PieceChangedEventArgs : EventArgs
{
public PieceChangedEventArgs(Square square, Piece newPiece)
{
NewPiece = newPiece;
Square = square;
}
public Square Square { get; set; }
public Piece NewPiece { get; set; }
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
class PieceSelectionChangedEventArgs : EventArgs
{
public PieceSelectionChangedEventArgs(Piece piece, Coords selectedPieceCoords, List<Coords> validMoves)
{
SelectedPiece = piece;
SelectedPieceCoords = selectedPieceCoords;
PossibleEndCoords = validMoves;
}
public Piece SelectedPiece { get; set; }
public Coords SelectedPieceCoords { get; set; }
public List<Coords> PossibleEndCoords { get; set; }
}
class PlayerTimerTickEventArgs : EventArgs
{
public PlayerTimerTickEventArgs(Player player)
{
CurrentPlayer = player;
PlayerRemainingTime = player.RemainingTime;
}
public Player CurrentPlayer { get; set; }
public TimeSpan PlayerRemainingTime { get; set; }
}
class PlayerCapturedPiecesChangedEventArgs : EventArgs
{
public PlayerCapturedPiecesChangedEventArgs(Player player, Piece capturedPiece)
{
Player = player;
CapturedPiece = capturedPiece;
}
public Player Player { get; set; }
public Piece CapturedPiece { get; set; }
}
class PromotionEventArgs : EventArgs
{
public PromotionEventArgs(PieceColour colour, Coords coords)
{
PromotingCoords = coords;
PromotingColour = colour;
}
public Coords PromotingCoords { get; set; }
public PieceColour PromotingColour { get; set; }
}
class GameOverEventArgs : EventArgs
{
public GameOverEventArgs(GameResult result, Player winner)
{
Result = result;
Winner = winner;
}
public GameResult Result { get; set; }
public Player Winner { get; set; }
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
View
The view mainly invokes events which are received by the controller, but also realises an interface IModelObserver, which allows the view to be updated when the model changes.
IModelObserver
using prjChessForms.MyChessLibrary;
namespace prjChessForms.Controller
{
interface IModelObserver
{
void OnPieceInSquareChanged(object sender, PieceChangedEventArgs e);
void OnPieceSelectionChanged(object sender, PieceSelectionChangedEventArgs e);
void OnPlayerCapturedPiecesChanged(object sender, PlayerCapturedPiecesChangedEventArgs e);
void OnPlayerTimerTick(object sender, PlayerTimerTickEventArgs e);
void OnGameOver(object sender, GameOverEventArgs e);
void OnPromotion(object sender, PromotionEventArgs e);
}
}
ChessForm
using prjChessForms.Controller;
using prjChessForms.MyChessLibrary;
using System;
using System.Windows.Forms;
namespace prjChessForms.PresentationUI
{
partial class ChessForm : Form, IModelObserver
{
public EventHandler<SquareClickedEventArgs> SquareClicked;
public EventHandler<PromotionSelectedEventArgs> PromotionSelected;
private TableLayoutPanel _layoutPanel;
private BoardTableLayoutPanel _boardPanel;
private PromotionSelectionPanel _promotionPanel;
private PlayerInformationPanel _whiteInfo;
private PlayerInformationPanel _blackInfo;
public ChessForm()
{
InitializeComponent();
SetupControls();
}
public ChessController Controller { get; set; }
public void OnPieceInSquareChanged(object sender, PieceChangedEventArgs e)
{
_boardPanel.UpdateSquare(e.Square.Coords, e.NewPiece);
}
public void OnPieceSelectionChanged(object sender, PieceSelectionChangedEventArgs e)
{
_boardPanel.UpdateHighlights(e.SelectedPiece, e.SelectedPieceCoords, e.PossibleEndCoords);
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public void OnPlayerCapturedPiecesChanged(object sender, PlayerCapturedPiecesChangedEventArgs e)
{
switch (e.Player.Colour)
{
case PieceColour.White:
_whiteInfo.UpdateCapturedPieces(e.CapturedPiece);
break;
case PieceColour.Black:
_blackInfo.UpdateCapturedPieces(e.CapturedPiece);
break;
}
}
public void OnPromotion(object sender, PromotionEventArgs e)
{
_promotionPanel = new PromotionSelectionPanel(e.PromotingColour);
_promotionPanel.PromotionSelected += OnPromotionSelected;
_promotionPanel.Show();
}
public void OnGameOver(object sender, GameOverEventArgs e)
{
if (e.Winner == null)
{
MessageBox.Show("Draw", e.Result.ToString());
}
else
{
MessageBox.Show(e.Winner.Colour.ToString() + " Wins!", e.Result.ToString());
}
}
public void OnPlayerTimerTick(object sender, PlayerTimerTickEventArgs e)
{
switch (e.CurrentPlayer.Colour)
{
case PieceColour.White:
_whiteInfo.UpdateTime(e.PlayerRemainingTime);
break;
case PieceColour.Black:
_blackInfo.UpdateTime(e.PlayerRemainingTime);
break;
}
}
private void SetupControls()
{
SetupLayoutPanel();
SetupBoard();
SetupPlayerInfo();
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private void SetupLayoutPanel()
{
_layoutPanel = new TableLayoutPanel()
{
Parent = this,
Dock = DockStyle.Fill,
Padding = new Padding(0)
};
_layoutPanel.ColumnStyles.Clear();
_layoutPanel.RowStyles.Clear();
_layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 90));
_layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 10));
_layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 10));
_layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 80));
_layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 10));
}
private void SetupBoard()
{
_boardPanel = new BoardTableLayoutPanel(this)
{
Parent = _layoutPanel,
Dock = DockStyle.Fill,
};
_boardPanel.SquareClicked += OnBoardClicked;
_layoutPanel.SetCellPosition(_boardPanel, new TableLayoutPanelCellPosition(0, 1));
}
private void SetupPlayerInfo()
{
_whiteInfo = new PlayerInformationPanel(PieceColour.White)
{
Parent = _layoutPanel,
Dock = DockStyle.Fill,
};
_layoutPanel.SetCellPosition(_whiteInfo, new TableLayoutPanelCellPosition(0, 2));
_blackInfo = new PlayerInformationPanel(PieceColour.Black)
{
Parent = _layoutPanel,
Dock = DockStyle.Fill,
};
_layoutPanel.SetCellPosition(_blackInfo, new TableLayoutPanelCellPosition(0, 0));
}
private void OnBoardClicked(object sender, SquareClickedEventArgs e)
{
if (SquareClicked != null)
{
SquareClicked.Invoke(this, e);
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private void OnPromotionSelected(object sender, PromotionSelectedEventArgs e)
{
if (PromotionSelected != null)
{
_promotionPanel.Hide();
_promotionPanel = null;
PromotionSelected.Invoke(this, e);
}
}
}
}
BoardTableLayoutPanel
using prjChessForms.MyChessLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace prjChessForms.PresentationUI
{
class BoardTableLayoutPanel : TableLayoutPanel
{
public EventHandler<SquareClickedEventArgs> SquareClicked;
private const int ROWCOUNT = 8;
private const int COLUMNCOUNT = 8;
private Button[,] _buttons;
public BoardTableLayoutPanel(ChessForm parentForm)
{
ParentForm = parentForm;
ColumnCount = COLUMNCOUNT;
RowCount = ROWCOUNT;
SetupRowsAndColumns();
Display();
}
public ChessForm ParentForm { get; }
public void Display(bool flippedPerspective = false)
{
for (int x = 0; x < ColumnCount; x++)
{
for (int y = 0; y < RowCount; y++)
{
if (flippedPerspective)
{
SetCellPosition(_buttons[x, y], new TableLayoutPanelCellPosition(x, y));
}
else
{
SetCellPosition(_buttons[x, y], new TableLayoutPanelCellPosition(x, RowCount - 1 - y));
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public Coords GetCoordsOf(Button button)
{
for (int y = 0; y < _buttons.GetLength(1); y++)
{
for (int x = 0; x < _buttons.GetLength(0); x++)
{
if (_buttons[x, y] == button)
{
return new Coords(x, y);
}
}
}
throw new ArgumentException("Button could not be found");
}
public void UpdateSquares(Square[,] squares, Piece selectedPiece, List<Coords> possibleMoves)
{
for (int y = 0; y < squares.GetLength(1); y++)
{
for (int x = 0; x < squares.GetLength(0); x++)
{
Piece piece = squares[x, y].Piece;
Button button = _buttons[x, y];
if (piece != null)
{
button.Image = piece.Image;
if (piece.Equals(selectedPiece))
{
button.BackColor = Color.Blue;
}
else if (possibleMoves.Contains(new Coords(x, y)))
{
button.BackColor = Color.Green;
}
else
{
button.BackColor = DefaultBackColor;
}
}
else
{
button.Image = null;
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public void UpdateHighlights(Piece selectedPiece, Coords selectedCoords, List<Coords> possibleMoves)
{
for (int y = 0; y < _buttons.GetLength(1); y++)
{
for (int x = 0; x < _buttons.GetLength(0); x++)
{
Button button = _buttons[x, y];
if (selectedPiece != null && selectedCoords.Equals(new Coords(x, y)))
{
button.BackColor = Color.Blue;
}
else if (possibleMoves.Contains(new Coords(x, y)))
{
button.BackColor = Color.Green;
}
else
{
button.BackColor = DefaultBackColor;
}
}
}
}
public void UpdateSquare(Coords coords, Piece piece)
{
_buttons[coords.X, coords.Y].Image = piece != null ? piece.Image : null;
}
private void SetupRowsAndColumns()
{
RowStyles.Clear();
ColumnStyles.Clear();
_buttons = new Button[ColumnCount, RowCount];
for (int x = 0; x < ColumnCount; x++)
{
ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100 / ColumnCount));
for (int y = 0; y < RowCount; y++)
{
RowStyles.Add(new RowStyle(SizeType.Percent, 100 / RowCount));
Button button = new Button()
{
Parent = this,
Dock = DockStyle.Fill,
};
button.Click += OnSquareClicked;
_buttons[x, y] = button;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private void OnSquareClicked(object sender, EventArgs e)
{
Button button = (Button)sender;
SquareClicked.Invoke(this, new SquareClickedEventArgs(GetCoordsOf(button)));
}
}
}
PlayerInformationPanel
using prjChessForms.MyChessLibrary;
using System;
using System.Windows.Forms;
namespace prjChessForms.PresentationUI
{
class PlayerInformationPanel : TableLayoutPanel
{
private Label _colourLabel;
private Label _timeLabel;
private CapturedPiecesPanel _capturedPieces;
public PlayerInformationPanel(PieceColour colour)
{
PieceColour = colour;
SetupPanel();
}
public PieceColour PieceColour { get; }
public void UpdateTime(TimeSpan remainingTime)
{
string text = remainingTime.ToString();
if (_timeLabel.InvokeRequired)
{
Action safeWrite = delegate { UpdateTime(remainingTime); };
_timeLabel.Invoke(safeWrite);
}
else
{
_timeLabel.Text = text;
}
}
public void UpdateCapturedPieces(Piece capturedPiece)
{
_capturedPieces.AddCapturedPiece(capturedPiece);
}
private void SetupPanel()
{
RowStyles.Clear();
ColumnStyles.Clear();
RowStyles.Add(new RowStyle(SizeType.Percent, 100));
ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20));
ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 60));
ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20));
SetupCapturedPieces();
SetupLabel();
SetupTimer();
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
SetupCapturedPieces();
SetupLabel();
SetupTimer();
}
private void SetupLabel()
{
_colourLabel = new Label
{
Text = PieceColour.ToString(),
Parent = this,
Dock = DockStyle.Fill,
};
SetCellPosition(_colourLabel, new TableLayoutPanelCellPosition(0, 0));
}
private void SetupCapturedPieces()
{
_capturedPieces = new CapturedPiecesPanel(PieceColour)
{
Parent = this,
Dock = DockStyle.Fill,
Padding = new Padding(0),
};
SetCellPosition(_capturedPieces, new TableLayoutPanelCellPosition(1, 0));
}
private void SetupTimer()
{
_timeLabel = new Label()
{
Text = TimeSpan.Zero.ToString(),
Parent = this,
Dock = DockStyle.Fill,
};
SetCellPosition(_timeLabel, new TableLayoutPanelCellPosition(2, 0));
}
}
}
PromotionSelectionPanel
using prjChessForms.MyChessLibrary;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace prjChessForms.PresentationUI
{
class PromotionSelectionPanel : Form
{
public EventHandler<PromotionSelectedEventArgs> PromotionSelected;
private TableLayoutPanel _panel;
private PromotionOption _selectedPromotion;
public PromotionSelectionPanel(PieceColour colour)
{
PieceColour = colour;
SetupPanel();
SetupButtons();
}
public PieceColour PieceColour { get; } | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
public PromotionOption SelectedPromotionOption
{
get { return _selectedPromotion; }
set
{
_selectedPromotion = value;
if (PromotionSelected != null)
{
PromotionSelected.Invoke(this, new PromotionSelectedEventArgs(_selectedPromotion));
}
}
}
private void OnSelectionButtonClicked(PromotionOption option) => SelectedPromotionOption = option;
private void SetupPanel()
{
_panel = new TableLayoutPanel()
{
Parent = this,
Dock = DockStyle.Fill,
};
_panel.RowStyles.Clear();
_panel.ColumnStyles.Clear();
_panel.RowStyles.Add(new RowStyle(SizeType.Percent, 50));
_panel.RowStyles.Add(new RowStyle(SizeType.Percent, 50));
_panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
_panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
}
private void SetupButtons()
{
Button button;
int i = 0;
foreach (PromotionOption option in Enum.GetValues(typeof(PromotionOption)))
{
button = new Button()
{
Parent = _panel,
Image = (Image)Properties.Resources.ResourceManager.GetObject(PieceColour.ToString() + "_" + option.ToString()),
Dock = DockStyle.Fill
};
_panel.SetCellPosition(button, new TableLayoutPanelCellPosition(i / 2, i % 2));
button.Click += (sender, e) => OnSelectionButtonClicked(option);
i++;
}
}
}
}
CapturedPiecesPanel
using prjChessForms.MyChessLibrary;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms; | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
namespace prjChessForms.PresentationUI
{
internal class CapturedPiecesPanel : TableLayoutPanel
{
private Dictionary<string, int> _capturedPieceCounts;
public CapturedPiecesPanel(PieceColour colour)
{
CapturedPieceColour = colour == PieceColour.White ? PieceColour.Black : PieceColour.White;
_capturedPieceCounts = new Dictionary<string, int>()
{
{"Pawn", 0},
{"Bishop", 0},
{"Knight", 0 },
{"Rook", 0},
{"Queen", 0}
};
RowStyles.Clear();
ColumnStyles.Clear();
RowStyles.Add(new RowStyle(SizeType.Percent, 100));
for (int i = 0; i < 5; i++)
{
ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20));
}
}
public PieceColour CapturedPieceColour { get; }
public void AddCapturedPiece(Piece piece)
{
_capturedPieceCounts[piece.Name]++;
UpdateDisplayPanel();
}
private void UpdateDisplayPanel()
{
Controls.Clear();
int tableIndex = 0;
for (int i = 0; i < 5; i++)
{
KeyValuePair<string, int> keyValuePair = _capturedPieceCounts.ElementAt(i);
if (keyValuePair.Value > 0)
{
Control p = CreatePieceCaptureCounter(keyValuePair.Key);
SetCellPosition(p, new TableLayoutPanelCellPosition(tableIndex, 0));
tableIndex++;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private Control CreatePieceCaptureCounter(string pieceName)
{
int count = _capturedPieceCounts[pieceName];
Label p = new Label()
{
Parent = this,
Dock = DockStyle.Fill,
Image = (Image)Properties.Resources.ResourceManager.GetObject(CapturedPieceColour.ToString() + "_" + pieceName),
Text = "x" + count.ToString()
};
return p;
}
}
}
PresentationEventArgs
using prjChessForms.MyChessLibrary;
using System;
namespace prjChessForms.PresentationUI
{
class SquareClickedEventArgs : EventArgs
{
public SquareClickedEventArgs(Coords coords)
{
ClickedCoords = coords;
}
public Coords ClickedCoords { get; set; }
}
class PromotionSelectedEventArgs : EventArgs
{
public PromotionSelectedEventArgs(PromotionOption option)
{
SelectedOption = option;
}
public PromotionOption SelectedOption { get; set; }
}
}
Controller
The controller sends inputs from the view to the model, and attaches the view as an IModelObserver to the model.
ChessController
using prjChessForms.MyChessLibrary;
using prjChessForms.PresentationUI;
namespace prjChessForms.Controller
{
class ChessController
{
private Chess _chessModel;
private ChessForm _chessView;
public ChessController(Chess chessModel, ChessForm chessView)
{
_chessModel = chessModel;
_chessView = chessView;
_chessView.Controller = this;
_chessModel.AttachModelObserver(_chessView);
_chessView.SquareClicked += OnBoardClickReceived;
_chessView.PromotionSelected += OnPromotionReceived;
_chessModel.StartGame();
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
private void OnBoardClickReceived(object sender, SquareClickedEventArgs e)
{
_chessModel.SendCoords(e.ClickedCoords);
}
private void OnPromotionReceived(object sender, PromotionSelectedEventArgs e)
{
_chessModel.SendPromotion(e.SelectedOption);
}
}
}
Program
using prjChessForms.Controller;
using prjChessForms.MyChessLibrary;
using prjChessForms.PresentationUI;
using System;
using System.Windows.Forms;
namespace prjChessForms
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Chess game = new Chess();
ChessForm form = new ChessForm();
ChessController controller = new ChessController(game, form);
Application.Run(form);
}
}
}
Thoughts
This is my first time learning about and following the MVC design pattern, so I am looking forward to getting feedback about it.
One other flaw that I am aware of is some inconsistent spacing between properties and one liner methods. While I have (hopefully) consistently made it so that there is one empty line between methods, I am not sure what is the best practice for properties.
Sorry that I haven't put many comments on each class, and hopefully it isn't too difficult to understand what each part of my code does.
Answer: I will update this answer when I have more time, maybe during the weekend, but you deserve feedback for such effort! | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
While your naming of classes is not bad, you method names leave a little something to be desired. Remember clean code, is code other people can easily understand, and "AddDefaultPieces" doesn't really explain what is going to happen.
"PopulatePiecesNewGame" is likely a better choice as it better conveys what the method actually does. The other name is too generic, for such a specific task, especially because chess has many modes, default setting for king of the hill is very different.
You don't follow SOLID. This makes your code very hard to test. Especially automated tests. I would recommend watching some uncle bob lectures, his stories are great, but focus on the meat and potatoes, and get his definition of the five letters of SOLID.
Looking at AddDefaultPieces
First you loop through players.
Then you loop through y that has to be less than 2? When you use i as an index, it is usual to choose the next letter to be j. Y would indicate a y coordinate, but the max values is 2 so that makes no sense.
The you loop through the column count. Where you confirm the player color is the same as pieceColor.White. (Poor naming, the player.Color is actually a pieceColor, so why not name it player.PieceColor?) That makes no sense.
Then you get a square, Through some pretty obscure parameter sets.,depending on player color. Especially how the black pieces are placed is a bit strange to figure out. There has to be a more easily readable way to place these pieces in just as efficient a manner.
Say:
void PlaceWhitePieces() {
SquareA2 = new Square(1,2);
SquareA2.Piece = new Pawn(playerWhite);
SquareB2 = new Square(2,2);
SquareB2.Piece = new Pawn(playerWhite);
etc.
}
void PlaceBlackPiecces() {
} | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c#, game, mvc, winforms, chess
etc.
}
void PlaceBlackPiecces() {
}
This is also a second point: the notation in chess is x axes = letters, A - H
and y axis Numbers 1-8.
Why create custom coordinates that then operate on digits only? At least put an abstract layer above it, to hide from the code-reviewer that there is an actual math based coordinate set under the normal notation. This will make it easier to read the code.
Generally switch cases are considered a bad idea, because if you need to add a new type, then you have to revisit all places where that switch case is implemented to correct a change.
This might not be relevant for a chess game? But that doesn't mean you shouldn't think about how you would normally avoid a switch case statement. Especially when it isn't needed.
I will try to rewrite this so it becomes more apparent what I mean during the weekend.
I think I would change the amount of maths you are required to do, into a more readable format also.
I would suggest you instead make "ValidMoveToCoordinates" a set of coord that are calculated every time a piece is moved, so those validMoves are calculated when a piece is moved, not as part of the Move action.
(This would also allow you to change the color of the squares that are possible destinations, much easier)
I am not sure I copied your code correctly, because just copy/pasting the code into my own project causes the capture mechanism to fail; also you cannot "deselect" after touching a piece (even in real chess, you are allowed to touch a piece - it is only after you let the piece go, that the move is required).
But this maybe be sloppy copying on my part.
However this is something to consider, until the weekend, where I hope I will have time to do, if not a complete, then at least a partial rewrite of what I think it should look like to be cleaner. | {
"domain": "codereview.stackexchange",
"id": 44912,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, mvc, winforms, chess",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
Title: Get files downloaded asynchronously after double clicking on list item (C++)
Question: The problem I am trying to solve as an exercise is as follows:
I have a UI running in the main thread, specifically a list view with many items. Each item represents a file that the user can download. To do so, you need to double-click on the item and the download process should start.
I don't want the download process to block the UI thread, so the only solution I see is to run the download process in a separate thread (separate from the main thread in which the UI loop runs).
However, the user might want to cancel the download.
I came up with the following design:
if you double-click on an item, start the download thread by passing to the function executed by the tread the caller (the list view in my case) and some additional info such as the item index in the list view and the filename.
When the thread starts it registers itself by calling the RegisterThread method on the List instance that started the thread. The thread enters the download loop (use something like recv to get batches of data until the download is complete) but on each iteration of the loop it asks list view whether it should keep running by calling list->ShouldThreadStop.
I am using 2 maps in the List class to keep track of the item index-thread id relation and the thread id and bool flag (that indicates whether a given thread should keep running) relation. When the thread ends (end of download or requested to stop), it needs to call a Deregister method on List to remove appropriate entries in the maps.
In the review process from peers and C++ gurus I am particular interested in the following points: | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
In the review process from peers and C++ gurus I am particular interested in the following points:
This is a rather common feature (a list of files to download). Do you think the solution of creating a separate thread to handle the download process is the most appropriate approach?
Is my design for registering/deregistering the thread so that the calling instance (list in my case) can stop the thread the best approach too? Is there a better pattern for this?
Do you see issues with this design (besides that, I don't check bounds here for the index and don't necessarily handle cases where I look up in the map without checking if the entry exists). I am more interested in the bigger picture. While a bit involved, there's no simpler, more "correct" (assuming there's something fundamentally wrong with the chosen approach)? But this is why I am posting here).
One thing that worries me is what happens if a user deletes an item in the list corresponding to a file that's being downloaded. But I can also determine whether a thread runs for that item and cancel it if needed. The thread itself should not rely on data that would be in the list while running (passing the filename as a reference might be an issue, so I can pass it by value).
As a side note, am I using the mutex right here? Is there a better way?
I value and appreciate you spending time on this code and sharing your knowledge and experience.
Here is the code:
// clang++ -std=c++2b -pthread -o list_view list_view.cc
#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <string>
#include <map>
#include <chrono>
#include <atomic>
#include <mutex>
#include <csignal>
class List;
void DownloadFile(List* list, uint32_t index, const std::string& filename); | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
class List;
void DownloadFile(List* list, uint32_t index, const std::string& filename);
class List {
public:
List() {
filenames_.insert(filenames_.begin(), {"a.bin", "b.bin", "c.bin", "d.bin"});
}
void DoubleClick(uint32_t index) {
std::thread th(DownloadFile, this, index, filenames_[index]);
th.detach();
}
void RegisterThread(uint32_t index, std::thread::id id) {
std::lock_guard<std::mutex> lock(mutex_);
//if (should_stop_map_.find(id) != should_stop_map_.end())
should_stop_map_[id] = false;
index_to_thread_id_[index] = id;
}
void DeregisterThread(int index) {
std::lock_guard<std::mutex> lock(mutex_);
std::thread::id id = index_to_thread_id_[index];
should_stop_map_.erase(id);
index_to_thread_id_.erase(index);
}
bool ShouldThreadStop(std::thread::id id) {
std::lock_guard<std::mutex> lock(mutex_);
if (should_stop_map_.find(id) != should_stop_map_.end()) {
return should_stop_map_[id];
}
return false;
}
void StopThreadByIndex(uint32_t index) {
std::lock_guard<std::mutex> lock(mutex_);
std::thread::id id = index_to_thread_id_[index];
if (should_stop_map_.find(id) != should_stop_map_.end())
should_stop_map_[id] = true;
}
std::vector<std::string> filenames_;
std::map<std::thread::id, std::atomic<bool>> should_stop_map_;
std::map<uint32_t, std::thread::id> index_to_thread_id_;
std::mutex mutex_;
}; | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
void DownloadFile(List* list, uint32_t index, const std::string& filename) {
list->RegisterThread(index, std::this_thread::get_id());
std::cerr << "Start to download: " << filename << std::endl;
int i = 0;
while (!list->ShouldThreadStop(std::this_thread::get_id()) && i++ < 10) {
// to simulate some data received from a server
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
list->DeregisterThread(index);
std::cerr << "I am either done or was stoped. Progress: " << i << ", index: " << index << std::endl;
}
List list;
void SignalHandler(int singint) {
std::cerr << list.should_stop_map_.size() << " " <<
list.index_to_thread_id_.size() << std::endl;
exit(singint);
}
int main() {
signal(SIGINT, SignalHandler);
list.DoubleClick(2);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
list.DoubleClick(0);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
list.StopThreadByIndex(2);
for (;;) {}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
Answer: I’m going to start the review by answering the questions briefly, then afterwards, expand a bit. So…:
Questions
Creating a separate thread to handle the download process is the most appropriate approach?
No.
Remember that std::thread is not really the same as a “thread” in most other modern languages. In most languages, a “thread” is just an abstraction that may or may not map to a concrete “thing” (operating system thread or processor thread or whatever). These are sometimes called “green threads”. A lot of times, the language’s run-time creates a fixed number of “real” threads in a thread pool, and then the “green threads” you create in the code are scheduled on that pool as needed. But a std::thread is a literal, real, operating system thread.
That has some important implications. In most modern languages, because “green threads” are not real threads, they can be pretty lightweight. You can make millions of threads in Haskell or Python (using CPython under the hood at least), and your computer will shrug and keep on trucking… because there are only, say, 4 or 8 real threads, and those millions of “threads” are just tasks in a queue that get bounced around those real threads. But in C++, if you made millions of std::thread… you will very likely bring your system to its knees.
Thus, making a std::thread for each task is… not a great idea. | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
Thus, making a std::thread for each task is… not a great idea.
std::thread is meant to be a very low-level tool. You generally shouldn’t be using it (directly) in higher-level code… like UI code. You should be using higher-level abstractions, like tasks. The standard library has std::packaged_task for that. @G.Sliepen also mentioned using std::promise and std::future directly which… well, I mean, they’re kinda mid-level abstractions. But, generally, the standard library’s concurrency facilities are still very poor, and primarily low-level, building block stuff. That’s because we’re waiting on executors (or something like them). The idea is that in the future, you will be able to create a thread pool, get a scheduler for that thread pool, then schedule your tasks (with std::packaged_task or whatever) using that scheduler. All the juggling and scheduling of those tasks will be handled automatically.
But that’s the future. In the now, you’ll pretty much have to roll most of that yourself. More on that later.
Registering/deregistering the thread so that the calling instance can stop the thread the best approach too? Is there a better pattern for this?
Well, the pattern is okay. Your implementation is a bit… not good.
@G.Sliepen already mentioned that detaching threads is usually a bad idea. Indeed, I would suggest using std::thread at all is a bad idea. If anything you should use std::jthread.
It’s a little back-assward to throw away the thread handle, and instead give the thread a handle to the caller and expect it to check back on whether it should stop or what work it should be doing, not to mention doing all other management tasks. Ideally, you want your tasks (or threads) to be self-contained, and responsible only for their own stuff. This jibes with your intuition as well. | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
(As an aside, I generally suggest that if you find yourself making a design that involves manually “registering” and “un-registering” stuff… you really should stop and rethink that design. Not always… but… it is a bit of a design smell. At the very least, a function named DeregisterThread is pretty much a flashing red light with an alarm klaxon, and a voice repeating: “R-A-I-I… R-A-I-I…”)
Consider instead a design that keeps a map of download tasks, where each task is self-contained. That, in essence, makes each task “self-registering”, simply by virtue of being an item in the map. I’ll just use the filename as the key, but you could use a list index (but that’s brittle!) or something else.
auto download_file(std::stop_token stop_token, std::string const& filename)
{
// Presumably safe to use a reference to the filename, because the list
// should outlive the task... but do be careful, because, for example,
// if you mess with the vector of filenames by adding/removing/reordering
// stuff, that could be a problem!
//
// If it might be a problem, just take it by value. | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
std::cerr << "Start to download: " << filename << "\n";
auto i = 0
while (not stop_token.stop_requested() and i++ < 10)
std::this_thread::sleep_for(std::chrono::milliseconds(300));
std::cerr << "I am either done or was stoped. Progress: " << i << ", filename: " << filename << "\n";
}
class list
{
std::vector<std::string> filenames_;
std::unordered_map<std::string, std::jthread> tasks_;
// Everything cleans up perfectly, automatically. jthread is magical!
//
// Note though, this will cancel any unfinished downloads. If you want
// them to complete, you need a destructor that joins all unfinished
// task threads.
~list() = default;
auto double_click(std::size_t index) -> void
{
// do the requisite checks, of course:
// * check the index is valid...
// * check the filename isn’t already being downloaded...
// * etc....
auto const& filename = filenames_[index];
tasks[filename] = std::jthread{download_file, std::cref(filename)};
}
auto stop_thread_by_index(std::size_t index) -> void
{
// do the requisite checks, of course:
// * check the index is valid...
// * check the filename is being downloaded...
// * etc....
tasks_[filename_[index]].request_stop();
}
}; | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
tasks_[filename_[index]].request_stop();
}
};
Do you see issues with this design?
Aside from the stuff mentioned elsewhere, I think you have separation of responsibilities issues going on.
If this class is supposed to represent a UI list, then it shouldn’t also have a responsibility to be a download manager. The list class should have one responsibility: maintaining its list. It should keep track of the items in the list, responding to UI events (click, double-click, drag, etc.) by adding/removing/reordering its items… and that’s about it. It could (and should) support hooking callbacks into events, so you could take a list and have it initiate a download on double-click… but it shouldn’t, itself, have those extra responsibilities.
And, then, also, your download manager shouldn’t also have the responsibilities of being a task scheduler. It should support adding a download… cancelling a download… and maybe setting/resetting download priorities and getting the current state and progress of a download. But managing concurrency? That should be something else’s responsibility (specifically, a task scheduler).
So, for example, you probably want:
a task manager… which internally holds a thread pool and a list of tasks
a download manager… which takes download requests, and turns them into tasks that get passed to the task manager;
and then a UI list class… which takes UI events and turns them into download requests.
So, like:
// Abstract task:
class task
{
std::stop_token _stop_token;
public:
virtual ~task() = default;
// Cancellation support.
auto set_stop_token(std::stop_token stop_token) noexcept { _stop_token = stop_token; }
auto get_stop_token() const noexcept { return _stop_token; }
virtual auto run() = 0;
};
// Task scheduler:
class task_scheduler
{
std::vector<std::jthread> _threads; | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
// Task scheduler:
class task_scheduler
{
std::vector<std::jthread> _threads;
// If you had a proper concurrent queue, which you should, you wouldn't
// need the mutex. (A standard concurrent queue is forthcoming.)
std::unique_ptr<std::mutex> _task_list_mutex;
std::unique_ptr<std::queue<std::shared_ptr<task>>> _task_list;
static auto thread_function(
std::stop_token stop_token,
std::mutex& task_list_mutex,
std::queue<std::shared_ptr<task>>& task_list)
{
while (not stop_token.stop_requested())
{
auto const task = []()
{
auto lock = std::scoped_lock(task_lisk_mutex);
// This very simple scheduler just takes the next task in
// order.
//
// A more sophisticated implementation may use priorities,
// and may identify different types of tasks for different
// threads, or may use thread affinities... whatever.
if (not task_list.empty())
{
auto task = task_list.front();
task_list.pop();
return task;
}
return std::shared_ptr<task>{};
}();
if (task)
{
task->set_stop_token(stop_token);
task->run();
}
}
}
public:
task_scheduler()
: _task_list_mutex{std::make_unique<std::mutex>()}
, _task_list{std::make_unique<std::queue<std::shared_ptr<task>>>()}
{
std::ranges::generate_n(
std::back_inserter(_threads),
/* figure out the number of threads you want */,
[&mutex = *_task_list_mutex, &tasks = *_task_list] ()
{
return std::jthread{thread_function, std::ref(mutex), std::ref(tasks)};
}
);
} | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
// By default, any unfinished and not started tasks will be cancelled or
// discared. If you want all tasks to finish, you need to write a
// destructor that waits for the task queue to be empty, and all threads
// in the pool to join.
~task_scheduler() = default;
// Note: As written this class behaves properly. It won’t allow copies,
// it can be safely moved.
auto schedule(std::shared_ptr<task> task)
{
auto lock = std::scoped_lock(*_task_list_mutex);
_task_list->push(std::move(task));
}
};
class download_manager
{
class download_task : public task
{
std::string _filename;
public:
explicit download_task(std::string filename)
: _filename{std::move(filename)}
{}
auto run() -> void override
{
auto const stop_token = get_stop_token();
// Might need an iostreams mutex if you want to write to std::cerr
// concurrently.
std::cerr << "Start to download: " << _filename << "\n";
auto i = 0
while (not stop_token.stop_requested() and i++ < 10)
std::this_thread::sleep_for(std::chrono::milliseconds(300));
std::cerr << "I am either done or was stoped. Progress: " << i << ", filename: " << _filename << "\n";
}
};
// Note: no concurrency support, but easily added.
std::vector<std::weak_ptr<download_task>> _tasks;
public:
using handle_type = download_task*;
// Note: need to delete copying.
auto schedule_download(task_manager& scheduler, std::string filename) -> handle_type
{
// Clean up finished tasks:
std::erase_if(_tasks, [](auto&& p) { return p.expired(); });
auto task = std::make_shared<download_task>(std::move(filename));
_tasks.emplace_back(task);
scheduler.schedule(task);
return task.get();
} | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
scheduler.schedule(task);
return task.get();
}
auto cancel_download(handle_type handle)
{
std::erase_if(_tasks, [handle](auto&& task)
{
auto p = task.lock();
return (not p) or (p.get() == handle))
});
}
};
So your downloading list class would simply get a reference to a download manager, and in the on-double-click item event or whatever, it would do _download_manager.schedule_download(scheduler, filename). It would keep track of the handle, and if the user requests a cancellation, call cancel_download(handle). The download manager handles everything else, or passes the buck to the schedule.
(already covered)
(already covered)
As a side note, am I using the mutex right here? Is there a better way?
It doesn’t look wrong in the technical sense, but it does seem inefficient and unwise.
You shouldn’t allow threads to modify the maps. That way lies madness. That’s too many fingers in the broth. The list should be the only thing that controls those maps.
At most, the thread only needs two things: the filename, and the cancellation token (which, in your case, is an atomic bool, which is fine). There is no need to give it control over the list as well.
But the list needs to know when the download is done, and it needs to be able to cancel the download. Rather than maintaining a bunch of maps and trying to keep it in sync, you could do this:
class list
{
// I'll just use tuples to be quick and hacky, but you should probably
// create proper types.
std::vector<
std::tuple<
std::string, // the filename in the list
std::unique_ptr< // data needed only if downloading is initiated
std::tuple<
std::future<void>, // or you can keep a handle to the thread
std::atomic_flag // cancellation token
>
>
>
> _data; | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
static auto thread_func(std::string filename, std::promise<void> promise, std::atomic_flag& cancelled)
{
try
{
std::cerr << "Start to download: " << filename << "\n";
auto i = 0
while (not cancelled.test(std::memory_order::acquire) and i++ < 10)
std::this_thread::sleep_for(std::chrono::milliseconds(300));
std::cerr << "I am either done or was stoped. Progress: " << i << ", filename: " << filename << "\n";
promise.set_value_at_thread_exit();
}
catch (...)
{
promise.set_exception_at_thread_exit(std::current_exception());
}
}
public:
list()
{
for (auto&& filenames : {"a.bin", "b.bin", "c.bin", "d.bin"})
_data.emplace_back(filename);
}
~list()
{
for (auto&& [filename, download_data] : _data)
{
if (download_data)
{
auto&& [future, cancel] = *download_data;
cancel.test_and_set(std::memory_order::release); // if you want to cancel in-progress downloads
future.wait();
}
}
}
auto double_click(std::size_t index)
{
// As always, with any public function, do your diligence:
// * is index valid?
// * is it already downloading?
// * etc....
auto&& [filename, download_data] = _data[index];
auto temp_data = std::make_unique<std::tuple<std::future<void>, std::atomic_flag>();
auto&& [future, cancel] = *temp_data;
auto promise = std::promise<void>{};
future = promise.get_future();
auto thread = std::thread{thread_func, filename, std::move(promise), std:ref(cancel)};
thread.detach();
download_data = std::move(temp_data);
} | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
download_data = std::move(temp_data);
}
auto stop_thread_by_index(std::size_t index)
{
if (auto download_data = std::get<1>(_data[index]); download_data != nullptr)
std::get<std::atomic_flag>(*download_data).test_and_set(std::memory_order::release);
}
};
The list items are stored as tuples, consisting of a string and a pointer to “extra” data… in this case, data about any downloads that have been requested. Any item with a non-nullptr data pointer has a download pending, in progress, or completed. That means that there is extra, unnecessary data stored for any list item that isn’t being downloaded… but seriously, it’s just one pointer, and the amount of code is saves you with all that extra management of maps and crap, it amortizes away many times over.
Now, in the code above I’ve just used a bunch of raw types: tuples and futures and so on. You should really make proper dedicated types for each download task. Here’s an example of what a better interface might look like:
class download_task
: public task // inherit from a generic task interface, that can be
// passed to a scheduler
{
public:
// Might actually want different observers for the request filename/URL,
// and the target filename.
auto filename() const -> std::string;
auto filename_view() const noexcept -> std::string_view;
enum class status_type
{
unknown, // task is created, but not scheduled
pending, // task is scheduled, but not started
starting, // starting download (connecting, checking for space on destination, etc....)
in_progress, // download actually happening
complete, // self-explanatory
cancelled // self-explanatory
};
auto status() const noexcept -> status_type; | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
struct progress_type
{
std::size_t current = 0;
std::size_t total = -1; // -1 if we don’t know the download size
// (could also use optional<size_t>)
};
auto progress() const noexcept -> progress_type;
auto cancel() noexcept -> void;
auto get_future() noexcept -> std::future<void>;
// The actual “run” function, from the task interface, would do the
// download, periodically checking whether it has been cancelled.
};
I think that’s enough to allow anything you might want with a download function:
scheduling
cancellation
progress display
waiting on the result (with a std::future, you can use any kind of wait function, such as waiting indefinitely, waiting for a short period, etc.
Your list can hold a vector of tuples of filenames and shared (or weak) pointers to download tasks. That way you can iterate through the list to display the filenames and download status (if any), but otherwise, the downloading and scheduling are the business of other, dedicated classes.
This is, of course, not the only solution, and maybe not even the best for your specific use case. But it is certainly a lot less complex and and error-prone than holding a bunch of maps that you have to keep in sync, and allowing multiple components to modify those maps.
I would suggest you think in terms of interfaces, rather than implementations. Look at the current interface of your list class:
class List
{
public:
List(); // fine
void DoubleClick(uint32_t index); // fine
void StopThreadByIndex(uint32_t index); // fine, but poorly named
//
// should probably be CancelDownload
// or something like that | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
c++, multithreading, design-patterns, asynchronous
// These have no business being in the public interface.
//
// At the very least, you would need to make them private and make
// DownloadFile a friend... but even that is still ugly, because external
// entities shouldn’t have any need to much with the list of List. I mean
// the whole point of List is to keep a list, so it makes little sense to
// allow other entities to do that work.
void RegisterThread(uint32_t index, std::thread::id id);
void DeregisterThread(int index);
// There is no reason any external entity should need this information.
bool ShouldThreadStop(std::thread::id id);
};
That’s not a UI list interface. It is, if anything, a download manager class interface. That’s your problem domain whispering to you that you need to restructure your design. | {
"domain": "codereview.stackexchange",
"id": 44913,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, design-patterns, asynchronous",
"url": null
} |
beginner, rust
Title: Simulate number of children until parents have at least one of either sex
Question: Problem statement: A couple beginning a family decides to keep having children until they have at least one of either sex. Estimate the average number of children they will have via simulation. Also estimate the most common outcome. Assume that the probability \$p\$ of having a boy or girl is \$\frac{1}{2}\$.
This is one of my self-imposed challenges in Rust to become better at it. The problem was taken from Sedgewick Web Exercise 1.3.13
Here is my code:
use clap::Parser;
use rand::rngs::ThreadRng;
use rand::Rng;
use std::collections::HashMap;
use std::ops::RangeFrom;
use std::process::exit;
const VALID_TRIAL_NUMBERS: RangeFrom<u32> = 1..;
#[derive(Debug, Parser)]
struct Arguments {
#[arg(index = 1)]
number_of_trials: u32,
}
fn main() {
let arguments = Arguments::parse();
let number_of_trials: u32 = arguments.number_of_trials;
let mut rng = rand::thread_rng();
let Ok(frequencies) = simulate_many_families(number_of_trials, &mut rng) else {
eprintln!("Number of trials must be at least {}.", VALID_TRIAL_NUMBERS.start);
exit(1);
};
let average_children_number = calculate_average_children_number(number_of_trials, &frequencies);
println!("Result of the simulation after {number_of_trials} trials:");
println!("Average number of children is {average_children_number}.");
if let Some(most_common_outcome) = find_most_common_outcome(&frequencies) {
println!("The most common outcome is having {most_common_outcome} children.");
} else {
eprintln!("The frequencies HashMap is empty.");
}
}
fn find_most_common_outcome(frequencies: &HashMap<u32, u32>) -> Option<u32> {
let most_common_outcome: Option<u32> = frequencies
.iter()
.max_by_key(|(&_key, &value)| value)
.map(|(&key, &_value)| key);
most_common_outcome
} | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
fn calculate_average_children_number(
number_of_trials: u32,
frequencies: &HashMap<u32, u32>,
) -> f64 {
let average_children_number: f64 = f64::round(
f64::from(frequencies.iter().map(|(x, y)| x * y).sum::<u32>())
/ f64::from(number_of_trials),
);
average_children_number
}
fn simulate_many_families(
number_of_trials: u32,
rng: &mut ThreadRng,
) -> Result<HashMap<u32, u32>, String> {
if !VALID_TRIAL_NUMBERS.contains(&number_of_trials) {
return Err(format!(
"Number of trials must be at least {}.",
VALID_TRIAL_NUMBERS.start
));
}
let mut frequencies: HashMap<u32, u32> = HashMap::new();
for _ in 0..number_of_trials {
let number_of_children = simulate_one_family(rng);
let count = frequencies.entry(number_of_children).or_insert(0);
*count += 1;
}
Ok(frequencies)
}
fn simulate_one_family(rng: &mut ThreadRng) -> u32 {
let mut number_of_boys: u32 = 0;
let mut number_of_girls: u32 = 0;
while number_of_boys < 1 || number_of_girls < 1 {
let child: u32 = rng.gen_range(0..=1);
match child {
0 => number_of_boys += 1,
1 => number_of_girls += 1,
_ => (),
}
}
number_of_boys + number_of_girls
}
Is there any way that I can improve my code?
Answer: This looks pretty good. It’s already been factored into functions that each do one thing.
As before, I’m going to suggest a way to do this with iterators and higher-order functions, because I’m weird and love functional programming. But first, let’s look at a way you might refactor the program.
Currently, you have a function
fn simulate_one_family(rng: &mut ThreadRng) -> u32 | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
(Minor nit: I usually name a function like this according to the value it returns, and would name it simulate_one_family if it were primarily a side-effect function, but that’s a matter of style. It’s clear enough what this does.)
This is a great building block to start with, but pretend for the moment the team leader tells you, “We want to sum up the results of billions of trials, and a u32 could overflow, so change the return type to u64. We already have an iterator over infinite random bool values. Use that instead of ThreadRng. I’ll send you the documentation later.” that isn’t a big change to the interface:
fn simulate_one_family(rng: &mut impl Iterator<Item = bool>) -> u64
Inside the function, you currently have a while loop with two pieces of mutable state, number_of_boys and number_of_girls. You guessed it: I’m going to recommend you turn that into an iterator expression. This is a good candidate for Iterator::scan.
fn simulate_one_family(rng: &mut impl Iterator<Item = bool>) -> u64 {
rng.scan(
(0u64, 0u64),
move |(number_of_girls, number_of_boys), is_boy| {
if *number_of_girls > 0 && *number_of_boys > 0 {
None
} else if u64::MAX - *number_of_girls < *number_of_boys {
panic!("Either the most-improbable thing ever has happened, or the program has a logic error.");
} else if is_boy {
*number_of_boys += 1;
Some(*number_of_girls + *number_of_boys)
} else {
*number_of_girls +=1;
Some(*number_of_girls + *number_of_boys)
}
},
)
.last()
.expect("Logic error: There should have been at least two kids.")
} | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
This is a pretty close translation of your algorithm, with a few embellishments. Examining the second argument of scan first, it’s a closure |(number_of_girls, number_of_boys), is_boy| that returns an Option.
You can see where number_of_girls and number_of_boys went: they make up the state of the algorithm, and a scan takes the state as a single object. So they got packed into a tuple. This is actually passed by &mut instead of being moved.
A bigger change is that the closure in scan now gets a single random bit, is_boy, from the iterator rng. The code to generate that bit has been moved elsewhere, into the impl Iterator of rng’s type, whatever that is.
Back up to the first argument of scan, this is the initial value of the state: both number_of_girls and number_of_boys are initialized to zero.
The body of the closure is a conditional expression. A scan generates a sequence of values until it finishes with None, so the first test is whether to stop. This is equivalent to the loop condition of the original while. Next, I added a pro forma check that the families didn’t get so large, they overflow a u64, but you should be more worried that your computer will be hit by a meteor that was struck by lightning. The last two cases both increment the proper variable and add the total number of kids to the sequence. Finally, we take the last value of this sequence that isn’t None, and unwrap it, because we know the sequence cannot be empty. (There must be at least two kids before we stop.)
It has some advantages in terms of flexibility (you could, for example, feed a depterministic RNG, or some arbitrary non-random sequence of bits to it, without changing the code), without a real increase in complexity, although that might fall under YAGNI. | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
The main function is pretty different; The biggest change was taking out all the other helpers and ran multiple simulations using repeat_with, followed by take to limit it to a finite size. Your for loop will still work, but generally, collect on an iterator, will be more efficient than appending values one at a time to a mut Vec. Here, I just fed the iterator to .sum() instead of storing the values in memory at all.
I’d generally recommend using static single assignments and irrefutable patterns where possible. You’ll notice several necessary exceptions to this rule in the code. Some of the helpers in the original have been refactored into two or three lines in main.
Of course, I lied when I said we already had the iterator. It’s not in the rand crate you were using. We actually need to write it ourselves. That’s not the main focus here; a scan just needs its inputs in the form of an iterator. This consists of a struct to hold the state, a .next() function to get random bits, and From and Default to initialize it.
Finally, the problem specified simulating the results, but I’ll briefly mention the closed form solution. Let’s do a little combinatorics.
As I noted above, there have to be at least two children for there to be both a boy and a girl. There will be no more kids than that if this happens with the second child, plus one more if it has not happened until after the second child, plus one more than that if it has not happened until after the third, plus one more than that if it has not happened after the fourth, and so on. | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
Out of the 2**k possible outcomes of having k kids, only two don’t include a boy and a girl: k girls, or k boys. So, the probability of it not having happened after two kids is 2/2² = 1/2, the probability of it not having happened after three kids is 2/2³ = 1/4, and after k kids. is 1/2**(k - 1). The expected value is therefore 2 + 1/2 + 1/4 + 1/8 ... = 3. I use this to print how close to the theoretical expected value the results were.
Update: Branchless Code
The version above has an if is_boy test, where is_boy is an unpredictable branch. Those are hugely slow on some CPUs. Others can mitigate the misprediction penalty by using conditional moves.
More efficient is to write branchless code. Here is a version that removes the final branch, and calculates the number of girls and boys to add to the family from the value of the flag:
pub fn simulate_one_family(rng: &mut impl Iterator<Item = bool>) -> u64 {
rng.scan(
(0u64, 0u64),
move |(number_of_girls, number_of_boys), is_boy| {
if *number_of_girls > 0 && *number_of_boys > 0 {
None
} else if u64::MAX - *number_of_girls < *number_of_boys {
panic!("Either the most-improbable thing ever has happened, or the program has a logic error.")
} else {
*number_of_girls += 1 - is_boy as u64;
*number_of_boys += is_boy as u64;
Some (*number_of_girls + *number_of_boys)
}
},
)
.last()
.expect("Logic error: There should have been at least two kids.")
} | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
This generates better code, using sete and setne followed by add instead of cmove, on rustc 1.70.0 with -C opt-level=3 -C target-cpu=x86-64-v3. The relevant part of the loop, minus the RNG code, now looks like:
test rbx, rbx
je .LBB13_89
.LBB13_88:
test r14, r14
jne .LBB13_92
.LBB13_89:
mov r8, rbx
add r8, r14
jb .LBB13_90
xor r8d, r8d
xor r9d, r9d
test rdx, r10
sete r8b
setne r9b
add rbx, r8
add r14, r9
lea rdi, [r14, +, rbx]
In this assembly, rbx holds *number_of_girls, r14 holds *number_of_boys, test rdx, r10 checks is_boy and rdi holds the return value.
The first two branches check *number_of_girls > 0 and *number_of_boys > 0. The third is the overflow check. These should all be predictable by the CPU. The remaining code, to update *number_of_girls, *number_of_boys and the return value, has no branch instructions. This is surrounded by inlined iterator code.
Putting it All Together
extern crate rand;
/* Represents an iterator over infinite random `bool` values generatrd by
* a (pseudo-)RNG. A little more complicated than it needed to be, because
* it uses every bit of entropy that the RNG returns.
*
* This is intended to be used through the traits it implements. You should
* not access the members directly.
*/
struct RandBoolIter<RNG: rand::RngCore> {
rng: RNG,
rand_bits: u64,
bit_counter: u8,
}
/* Creates an iterator from a RNG. The returned object will load 64 random
* bits into its state the first time next() is called on it.
*/
impl<RNG: rand::RngCore> From<RNG> for RandBoolIter<RNG> {
fn from(rng: RNG) -> RandBoolIter<RNG> {
RandBoolIter {
rng: rng,
rand_bits: 0,
bit_counter: u64::BITS as u8,
}
}
}
// Like from, but uses the default RNG of its type.
impl<RNG: rand::RngCore + Default> RandBoolIter<RNG> {
fn new() -> RandBoolIter<RNG> {
Self::from(RNG::default())
}
} | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
// Also allow a default RandBoolIter.
impl<RNG: rand::RngCore + Default> Default for RandBoolIter<RNG> {
fn default() -> Self {
Self::from(RNG::default())
}
}
impl<RNG: rand::RngCore> Iterator for RandBoolIter<RNG> {
type Item = bool;
fn next(&mut self) -> Option<bool> {
if self.bit_counter == u64::BITS as u8 {
self.rand_bits = self.rng.next_u64();
self.bit_counter = 0;
} else {
self.bit_counter += 1;
}
Some(self.rand_bits & (1u64 << self.bit_counter) != 0)
}
}
pub fn simulate_one_family(rng: &mut impl Iterator<Item = bool>) -> u64 {
rng.scan(
(0u64, 0u64),
move |(number_of_girls, number_of_boys), is_boy| {
if *number_of_girls > 0 && *number_of_boys > 0 {
None
} else if u64::MAX - *number_of_girls < *number_of_boys {
panic!("Either the most-improbable thing ever has happened, or the program has a logic error.")
} else {
*number_of_girls += 1 - is_boy as u64;
*number_of_boys += is_boy as u64;
Some (*number_of_girls + *number_of_boys)
}
},
)
.last()
.expect("Logic error: There should have been at least two kids.")
} | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
pub fn main() {
let args: Vec<String> = std::env::args().collect();
let n_trials: usize = if let [_, arg1] = &args[..] {
if let Ok(n) = arg1.parse() {
n
} else {
eprintln! {"The number of trials must be an unsigned integer."};
std::process::exit(1);
}
} else {
eprintln!("The program must be called with one argument, the number of trials.");
std::process::exit(1);
};
let mut random_bits = RandBoolIter::<rand::rngs::ThreadRng>::default();
let sum_of_results: u64 = std::iter::repeat_with(|| simulate_one_family(&mut random_bits))
.take(n_trials)
.sum();
let mean = sum_of_results as f64 / n_trials as f64;
print!("The mean of {} trials was {}, ", n_trials, mean);
const EXPECTED: f64 = 3.0;
println!("which is within ±{}% of the expected value.",
f64::abs(100.0*(mean-EXPECTED)/EXPECTED));
}
``` | {
"domain": "codereview.stackexchange",
"id": 44914,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
python, tkinter, sudoku
Title: Messy Sudoku solver
Question: I have made a simple Sudoku solver in python and TKinter. However, I have used code from many different sources, so it is not neat. I can only write ugly code, so it is just about impossible for me to neaten it fully. I have made a start, but it is still bad. Here's what I have so far:
## IMPORTS ##
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
## VARIABLES ##
count = 0
## METHODS ## | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
python, tkinter, sudoku
def board_to_list(board):
entryboard = [[],[],[],[],[],[],[],[],[]]
for row in range(9):
for item in range(9):
try:
if (board[row][item].get() == ""):
entryboard[row].append(-1)
elif not(int(board[row][item].get()) in [1,2,3,4,5,6,7,8,9]):
raise ValueError
else:
entryboard[row].append(int(board[row][item].get()))
except:
showinfo(message="Invalid sudoku")
return False
return entryboard
def find_next_empty(puzzle):
for row in range(9):
for column in range(9):
if puzzle[row][column] == -1:
return row, column
return None, None
def is_valid(puzzle, guess, row, col):
row_vals = puzzle[row]
if guess in row_vals:
return False
col_vals = [puzzle[i][col] for i in range(9)]
if guess in col_vals:
return False
row_start = (row // 3) * 3
col_start = (col // 3) * 3
for r in range(row_start, row_start + 3):
for c in range(col_start, col_start + 3):
if puzzle[r][c] == guess:
return False
return True
def solve_sudoku(puzzle):
global count
row, col = find_next_empty(puzzle)
if row is None and col is None:
return True
for guess in range(1,10):
count += 1
if is_valid(puzzle, guess, row, col):
puzzle[row][col] = guess
if solve_sudoku(puzzle):
return True
puzzle[row][col] = -1
return False
def is_impossible(puzzle):
for i in range(9):
row = {}
column = {}
block = {}
row_cube = 3 * (i//3)
column_cube = 3 * (i%3)
for j in range(9):
if puzzle[i][j]!= -1 and puzzle[i][j] in row:
return False
row[puzzle[i][j]] = 1
if puzzle[j][i]!=-1 and puzzle[j][i] in column:
return False | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
python, tkinter, sudoku
if puzzle[j][i]!=-1 and puzzle[j][i] in column:
return False
column[puzzle[j][i]] = 1
rc= row_cube+j//3
cc = column_cube + j%3
if puzzle[rc][cc] in block and puzzle[rc][cc]!=-1:
return False
block[puzzle[rc][cc]]=1
return True
def handle_solve_click(event):
global count
count = 0
entryboard = board_to_list(board)
if not entryboard:
return False
if not(is_impossible(entryboard)):
showinfo(message="Invalid sudoku")
return False
solve_sudoku(entryboard)
time = count/5
while time > 10000:
time -= 1000
print(time)
pb.start(round(time/100))
window.after(round(time), show_solution, entryboard)
window.after(10, update_progress_bar)
def show_solution(entryboard):
count = 0
for row in range(9):
for item in range(9):
board[row][item].delete(0, tk.END)
board[row][item].insert(0, entryboard[row][item])
print("+" + "---+"*9)
for i, row in enumerate(entryboard):
print(("|" + " {} {} {} |"*3).format(*[x if x != -1 else " " for x in row]))
if i % 3 == 2:
print("+" + "---+"*9)
else:
print("+" + " +"*9)
pb.stop()
pb['value'] = 100
def handle_clear_click(event):
for row in range(9):
for item in range(9):
board[row][item].delete(0, tk.END)
pb['value'] = 0
progress['text'] = "0.0%"
def handle_hint_click(event):
entryboard = board_to_list(board)
otherboard = board_to_list(board)
if not(entryboard):
return False
if not(is_impossible(entryboard)):
showinfo(message="Impossible")
return False
solve_sudoku(entryboard)
for row in range(9):
for item in range(9):
if otherboard[row][item] != entryboard[row][item]:
board[row][item].delete(0, tk.END) | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
python, tkinter, sudoku
board[row][item].delete(0, tk.END)
board[row][item].insert(0, entryboard[row][item])
return True
showinfo(message="Already solved")
def update_progress_bar():
if pb['value'] < 100:
progress['text'] = f"{pb['value']}%"
window.after(10, update_progress_bar)
else:
pb['value'] = 100
progress['text'] = "Complete" | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
python, tkinter, sudoku
## MAIN LOOP ##
if __name__ == "__main__":
window = tk.Tk()
board = [[],[],[],[],[],[],[],[],[]]
entryboard = [[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,]]
sudoku_frame = tk.Frame(relief=tk.SUNKEN, borderwidth=5)
for row in range(9):
for item in range(9):
myentry = tk.Entry(master=sudoku_frame, width=1)
row_start = (row // 3)
col_start = (item // 3)
rowpos = row_start + row
colpos = col_start + item + 1
myentry.grid(row=rowpos, column=colpos)
board[row].append(myentry)
sudoku_frame.pack()
progress_frame = tk.Frame()
pb = ttk.Progressbar(master=progress_frame, orient='horizontal', mode='determinate', length=280)
pb.grid(row=0, column=0)
progress = tk.Label(master=progress_frame, text="0.0%")
progress.grid(row=1, column=0)
progress_frame.pack(pady=15)
button_frame = tk.Frame(relief=tk.RIDGE, borderwidth=5)
solve_btn = tk.Button(master=button_frame, text="Solve", relief=tk.FLAT, borderwidth=2)
solve_btn.bind("<Button-1>", handle_solve_click)
solve_btn.grid(row=0,column=0)
clear_btn = tk.Button(master=button_frame, text="Clear", relief=tk.FLAT, borderwidth=2)
clear_btn.bind("<Button-1>", handle_clear_click)
clear_btn.grid(row=0, column=1)
hint_btn = tk.Button(master=button_frame, text="Hint", relief=tk.FLAT, borderwidth=2)
hint_btn.bind("<Button-1>", handle_hint_click)
hint_btn.grid(row=0, column=3)
button_frame.pack()
window.mainloop()
Answer: First, your program works. So that's a great place to start.
Some cosmetic comments: | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
python, tkinter, sudoku
Answer: First, your program works. So that's a great place to start.
Some cosmetic comments:
Put blank lines between your functions. This helps people reading your code to know when something new is happening.
Put spaces between operators like +, -, ==, !=, etc. to make the lines easier to read.
The sudoku boxes in the GUI window are rather narrow and difficult to click on and enter numbers. Making the boxes wider and the text entry centered looks better: myentry = tk.Entry(master=sudoku_frame, width=3, justify='center')
Initializing repetitive structures
In several places, you initialize sudoku data with literal lists and lists of lists like these:
board = [[],[],[],[],[],[],[],[],[]]
entryboard = [[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,],[-1,-1,-1,-1,-1,-1,-1,-1,-1,]]
You can use list comprehension to create these structures. The resulting code is shorter and easier to read.
board = [[] for _ in range(9)]
entryboard = [[-1 for _ in range(9)] for _ in range(9)]
The variable _ is often used as a dummy variable where we don't care about its value. We just need it to store the current value out of range(9).
Similar changes can be made to entryboard in board_to_list(). In that same function, elif not(int(board[row][item].get()) in [1,2,3,4,5,6,7,8,9]): can be written elif not(int(board[row][item].get()) in range(1, 10):
Initializing the entry grid
I don't understand the math being done in the loop creating all the tk.Entry widgets. This seems to work just as well.
for row in range(9):
for item in range(9):
myentry = tk.Entry(master=sudoku_frame, width=3, justify='center')
myentry.grid(row=row, column=item)
board[row].append(myentry) | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
python, tkinter, sudoku
Global variables
I'm not talking about count at the top. That variable is modified in several functions and is declared global in those functions. That's fine and suits its purpose.
I'm mostly talking about the board variable that is created on the second line of the if __name__ == "__main__": block. This variable holds all of the text entry widgets that are used to both allow the user to enter numbers and display numbers when the GUI solves a cell. In almost all functions, the board variable is the one created at the bottom of the code. There's no indication where the board variable is defined when looking at the function. I understand that the bind() method that binds the functions to button clicks only take an Event as its only argument, but there's a way to sneak the board and any other variables you need into the callback.
As an example, let's look at the handle_clear_click() function. First, change the parameters of the called function to take a board argument.
def handle_clear_click(event, board, pb, progress):
for row in range(9):
for item in range(9):
board[row][item].delete(0, tk.END)
pb['value'] = 0
progress['text'] = "0.0%"
Then, instead of directly passing just the function to the bind() call, create a lambda expression that provides the parameters that the bind() call cannot.
clear_btn.bind("<Button-1>", lambda event: handle_clear_click(event, board, pb, progress)) | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
python, tkinter, sudoku
Now, there's no ambiguity in where the variables board, pb, and progress come from. Plus, this allows for easier changes later on. What if you want to allow work on more than one sudoku board in the same GUI? While that may not be likely for this program, other programs you write will have to juggle multiple sets of data.
Do the same thing for the other two buttons: Solve and Hint.
Unused data
The entryboard variable in the if __name__ == "__main__": block is not used anywhere, so you can delete it. The line count = 0 in show_solution() either needs to be deleted or have global put before it to reset the global count variable.
Several functions' return values that are not used. For example, handle_solve_click() returns False when the puzzle cannot be solved and nothing (implicitly None) otherwise. These return values don't do anything useful, so a simple return statement with nothing after it is fine.
def handle_solve_click(event):
global count
count = 0
entryboard = board_to_list(board)
if not entryboard:
return
if is_impossible(entryboard):
showinfo(message="Invalid sudoku")
return
solve_sudoku(entryboard)
time = count/5
while time > 10000:
time -= 1000
print(time)
pb.start(round(time/100))
window.after(round(time), show_solution, entryboard)
window.after(10, update_progress_bar)
Semantic bug
The function is_impossible() returns False when the puzzle is impossible to solve. This is the reverse of what I would expect given the name. I would switch True and False in all the return values of this function and fix the handle_hint_click() and handle_solve_click() functions so that the lines if not(is_impossible(entryboard)): do not have a not. The other choice is to rename the function is_possible(). | {
"domain": "codereview.stackexchange",
"id": 44915,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, sudoku",
"url": null
} |
java
Title: Java code showing page labels from PDF files
Question: I'm writing simple application changing page labels in pdf files. First step is to interpret and show page labels. Here's the code doing this.
It uses PDFBox library. I don't think there is a need to know this library. I think that my piece of code should be easy to understand. However, I think that there is some code duplication (even thought IntelliJ doesn't find one) and some if/else could be rewritten to make the code easier to read. I didn't use any design pattern but I feel that some could be of use.
I am interested in any type of comments but especially suggestions on how to use better design and employ some design patterns if applicable. However, all kinds of feedback like style issues, missed corner cases, performance, logical organisation, etc. are welcomed.
Please find me code below:
Class with main logic:
@RequiredArgsConstructor
public class PageLabelIterator {
private static final char[] ASCII_CHARS =
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z'};
private final PDDocument document;
@SneakyThrows
public List<Label> print() {
final PDPageLabels pageLabels = document.getDocumentCatalog().getPageLabels();
final List<Label> labels = new ArrayList<>();
for (int i = 0; i < document.getNumberOfPages(); i++) {
final PDPageLabelRange range = pageLabels.getPageLabelRange(i);
if (range == null) {
continue;
}
final COSDictionary rangeDict = range.getCOSObject();
// get page label
String pageLabel = ((COSString) rangeDict.getDictionaryObject(COSName.P)).getString();
// after label there could be suffix
final String suffix = getSuffix(rangeDict); | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
// add it or empty string instead
pageLabel += suffix;
final Label label = new Label(i + 1, pageLabel, LabelStyle.fromPdfBoxString(range.getStyle()));
labels.add(label);
}
return labels;
}
private String getSuffix(final COSDictionary rangeDict) {
final COSBase numberingStyle = rangeDict.getDictionaryObject(COSName.S);
// if numbering style is not present then return empty string
if (!(numberingStyle instanceof COSName)) {
return "";
} | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
// Letters
if (numberingStyle.equals(COSName.A) || numberingStyle.equals(COSName.getPDFName("a"))) {
final COSBase number = rangeDict.getDictionaryObject(COSName.ST);
if (number instanceof COSInteger cosInteger) {
if (numberingStyle.equals(COSName.A)) {
return Character.toString(ASCII_CHARS[cosInteger.intValue() - 1]).toUpperCase();
} else {
return Character.toString(ASCII_CHARS[cosInteger.intValue() - 1]).toLowerCase();
}
// null - then page = 1
} else {
if (numberingStyle.equals(COSName.A)) {
return Character.toString(ASCII_CHARS[0]).toUpperCase();
} else {
return Character.toString(ASCII_CHARS[0]).toLowerCase();
}
}
// Roman numerals
} else if (numberingStyle.equals(COSName.R) || numberingStyle.equals(COSName.getPDFName("r"))) {
final COSBase number = rangeDict.getDictionaryObject(COSName.ST);
if (number instanceof COSInteger cosInteger) {
if (numberingStyle.equals(COSName.R)) {
return toRoman(cosInteger.intValue() - 1).toUpperCase();
} else {
return toRoman(cosInteger.intValue() - 1).toLowerCase();
}
// null - then page = 1
} else {
if (numberingStyle.equals(COSName.R)) {
return toRoman(1).toUpperCase();
} else {
return toRoman(1).toLowerCase();
}
}
// Decimal numerals
} else if (numberingStyle.equals(COSName.D)) {
final COSBase number = rangeDict.getDictionaryObject(COSName.ST);
if (number instanceof COSInteger cosInteger) {
return String.valueOf(cosInteger.intValue() - 1); | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
return String.valueOf(cosInteger.intValue() - 1);
// null - then page = 1
} else {
return String.valueOf(1);
}
// if unkown page style, then return empty string
} else {
return "";
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
Enum with some logic:
@RequiredArgsConstructor
public enum LabelStyle {
DECIMAL("Decimal"),
ROMAN_LOWER("Roman lower"),
ROMAN_UPPER("Roman upper"),
LETTER_UPPPER("Letters upper"),
LETTER_LOWER("Letters lower"),
NONE("None");
private final String style;
static LabelStyle fromPdfBoxString(final String style) {
if (style == null) {
return NONE;
}
return switch (style) {
case "D" -> DECIMAL;
case "r" -> ROMAN_LOWER;
case "R" -> ROMAN_UPPER;
case "a" -> LETTER_LOWER;
case "A" -> LETTER_UPPPER;
default -> NONE;
};
}
}
Simple record:
public record Label(
int startPage,
String label,
LabelStyle style) {
}
Two external libraries are needed: PDFBox and Lombok. Please find below Maven dependency for the first library:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.29</version>
</dependency>
Answer: @RequiredArgsConstructor
...
@SneakyThrows
There is some review context missing here.
The import statements are part of the source,
they really matter to the Gentle Reader.
You should explicitly mention the
lombok
dependency.
(FWIW, I routinely re-throw wrapped RuntimeException,
just to clean up my Public API's signature.)
public List<Label> print() {
Consider renaming this.
The "print" verb suggests we evaluate this
for side effects on System.out.
for (int i = 0; i < document.getNumberOfPages(); i++) {
final PDPageLabelRange range = pageLabels.getPageLabelRange(i); | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
I'm not familiar with what Apache PDFBox exports,
but I'll just throw this out there.
Perhaps there is some way to iterate through document pages directly?
One concern is that maybe .getPageLabelRange(i)
does not run in O(1) constant time.
If it is O(N) linear in i, then we have a quadratic loop here.
As part of the review context you should reveal
whether you're using v3 of that library.
(EDIT
Oh, I see,
"Please find below Maven dep" 2.0.29, thank you.)
Given the poor quality of the library's
architecture
documentation, it would be very helpful if a comment
explains to the Gentle Reader what the secret COS
abbreviation stands for.
Maybe Compressed Object Stream?
Or Content Object Stream?
As it stands, I don't even know how to mentally pronounce
those identifiers.
// get page label
String pageLabel = ...
Please elide that // comment,
as it's not shedding any light on the situation.
The identifier is brilliant and tells us all that we need.
OTOH I thank you for the subsequent pair of comments,
which helpfully explain how the suffix is optional.
I confess I don't understand what's going on
when we cast the returned String to a COSString
and then convert it back to a String.
Now that would be worth a // comment.
As it stands, I imagine it works fine
and I don't need to know,
as clearly we get a String in the end.
If we're handling a corner case here,
a unit test might illuminate the details.
final Label label = new Label(i + 1, ... | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
I don't understand the + 1. There's an opportunity
for the method's /** javadoc */ to spell out that
one-origin
is for some reason an important part of this method's
contract.
That is, caller should understand that the Public API we're defining
chooses to differ from PDFBox's Public API in this regard.
(Also, "missing review context", from the OP it's unclear
which library defined the meaning of Label.
My tacit assumption is that the Apache library supplies it.
EDIT
Oh, wait, here we go,
the code appears below the "Simple record" remark, got it.)
private String getSuffix(
...
if (numberingStyle.equals(COSName.A) || numberingStyle.equals(COSName.getPDFName("a"))) {
Yikes!
That's frightening.
I'm sure it's necessary.
Sounds like an issue in the underlying library,
which deserves a bug report or PR.
If this is an upper / lower thing,
consider working around the library's shortcoming
by defining your own LOWER_A,
in the interest of clarity.
Or define a Set which includes both cases.
if (numberingStyle.equals(COSName.A)) {
return Character.toString(ASCII_CHARS[cosInteger.intValue() - 1]).toUpperCase();
} else {
return Character.toString(ASCII_CHARS[cosInteger.intValue() - 1]).toLowerCase();
}
// null - then page = 1
} else {
if (numberingStyle.equals(COSName.A)) {
return Character.toString(ASCII_CHARS[0]).toUpperCase();
} else {
return Character.toString(ASCII_CHARS[0]).toLowerCase();
}
} | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
This is not a lot of
repetition,
but there's room to improve.
I'm accustomed to seeing a .toUpperCase or .toLowerCase
reference being passed into a helper,
which will indirect through that.
Also, it seems like the first thing you want to do
is settle on an index of 0 vs cosInteger.intValue() - 1.
With that in hand you can then worry about upper vs lower.
Oh, goodness, there's just more of it for Roman numerals.
Yes, definitely break out the occasional helper method.
Identifiers of {A, R, D} and comments of {alpha, roman, decimal}
were helpful -- thank you.
I'm still unclear whether ST denotes style. A hint would be welcome.
You several times commented "null - then page = 1",
which I found unclear.
Upon reading this:
// null - then page = 1
} else {
if (numberingStyle.equals(COSName.R)) {
return toRoman(1).toUpperCase();
I realized that you habitually put the comment
a little farther from the target code than I would have expected.
That is, you associate the comment with the if clause
but intend it for the else clause.
Adding a short reference document
that's read by a few unit tests wouldn't hurt.
This codebase appears to achieve its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 44916,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
python, design-patterns, console, gui, mvp
Title: Model-View-Presenter (MVP) pattern implementation
Question: To learn more about design patterns, particularly the Model-View-Presenter (MVP) pattern, I am currently creating a CLI weight tracker application in Python. I would like you to review the code to determine if it adheres to the MVP pattern.
The code or business logic itself is not finished yet. The application can currently only display the version and initialize a database. However, for the purpose of reviewing the MVP implementation I believe the code is easier to follow without a ton of fucntions.
Additionally, the model.py module currently holds all the business logic. In a real-world application I would separate that into distinct modules. But in this self-made MVP tutorial, I have chosen to focus primarily on the three conceptual aspects of the pattern.
Thanks in advance!
Module __init__.py
__app_name__ = "Weight tracker"
__version__ = "0.1.0"
DEFAULT_DATABASE_PATH = "./data/storage.json"
DEFAULT_CONFIG_PATH = "./data/.config.ini"
Module __main__.py
from weight_tracker import view, presenter
def main() -> None:
presenter.run()
if __name__ == "__main__":
main()
Module view.py
import typer
from typing import Optional
from weight_tracker import presenter, DEFAULT_DATABASE_PATH
app = typer.Typer()
class TextColor:
DEFAULT = typer.colors.BLUE
ERROR = typer.colors.RED
SUCCESS = typer.colors.GREEN
def mainloop() -> None:
app()
def exit_console() -> None:
raise typer.Exit()
def write_to_console(text: str, color=TextColor.DEFAULT) -> None:
typer.secho(
text,
fg=color,
)
@app.command(name="init")
def initialize_database(
db_path: Optional[str] = typer.Option(
DEFAULT_DATABASE_PATH,
"--db_path",
"-db",
help="Create a new database.",
callback=presenter.init_app,
)
) -> None:
return | {
"domain": "codereview.stackexchange",
"id": 44917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, design-patterns, console, gui, mvp",
"url": null
} |
python, design-patterns, console, gui, mvp
@app.callback()
def global_options(
version: Optional[bool] = typer.Option(
None,
"--version",
"-v",
help="Show installed application version.",
callback=presenter.version_callback,
is_eager=True,
)
) -> None:
return
Module presenter.py
from weight_tracker import view
from weight_tracker import model
def init_app(db_path: str) -> None:
if db_path:
initialize_database(db_path)
initialize_configuration_file(db_path)
def initialize_database(db_path: str) -> None:
try:
model.create_empty_database(db_path)
view.write_to_console(f"Created empty storage at {db_path}", view.TextColor.SUCCESS)
except OSError:
view.write_to_console("Failed to create storage.json. file", view.TextColor.ERROR)
def initialize_configuration_file(db_path: str) -> None:
try:
model.write_db_path_to_config(db_path)
view.write_to_console(f"Updated database path to {db_path}", view.TextColor.SUCCESS)
except OSError:
view.write_to_console("Failed to create config.ini file.", view.TextColor.ERROR)
def version_callback(called: bool) -> None:
if called:
view.write_to_console(model.get_version())
view.exit_console()
def run() -> None:
view.mainloop()
Module model.py
from weight_tracker import __app_name__, __version__
from pathlib import Path
EMPTY_LIST = "[]"
# Application model
def get_version() -> str:
return f"{__app_name__} v{__version__}"
# Database model
def create_empty_database(db_path: str) -> None:
Path(db_path).write_text(EMPTY_LIST)
# Configuration model
def write_db_path_to_config(db_path: str) -> None:
... # todo
Answer: It passes mypy, yay!
Nice annotations.
A small quibble, a tiny nit.
Say what you mean and mean what you say.
DEFAULT_DATABASE_PATH = "./data/storage.json" | {
"domain": "codereview.stackexchange",
"id": 44917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, design-patterns, console, gui, mvp",
"url": null
} |
python, design-patterns, console, gui, mvp
That's a lovely identifier, very informative.
Except that we're storing a str
rather than a more expressive Path.
It is helpful to the Gentle Reader to see
functions accepting a Path argument
rather than a more ambiguous str,
and helpful to the Author since
.exists() and many other convenience
methods are available.
The / slash catenation operator
is especially useful: folder / "ReadMe.txt"
I am skeptical that def mainloop() is pulling its
weight, here, but OK whatever.
The issue seems to be one of scope for app.
It is needed for the decorator usages which look very nice,
and for kicking things off.
Consider shuffling things around a bit to avoid the awkward scope detail.
Maybe def exit_console() is good?
But it, too, might be deleted.
OTOH if there's some documented scheme you're adhering to
which requires these two, great, just cite its URL so we know.
@app.command(name="init")
def initialize_database(
Consider renaming, so there's no need for the optional name parameter.
Consider deleting, as this doesn't appear to do anything.
As a command line user
I would find -d (or --db) less confusing than -db which suggests it's equivalent to -d -b.
Perhaps there's no need for a short form?
callback=presenter.init_app,
I didn't notice a corresponding import for that reference.
is_eager=True,
I'm trying to imagine what would happen if this were set to False.
Yup, not seeing it, though the typer tutorial obliquely mentions it.
This is a slightly subtle aspect.
It would be worth a # comment,
or a unit test which highlights what goes wrong if this parameter is absent.
except OSError:
view.write_to_console("Failed to create storage.json. file", view.TextColor.ERROR) | {
"domain": "codereview.stackexchange",
"id": 44917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, design-patterns, console, gui, mvp",
"url": null
} |
python, design-patterns, console, gui, mvp
Imagine that this triggers.
The first thing a customer or maintenance engineer is going
to want to know is "which error?".
The happy path is super informative: at {db_path}.
Make the sad path at least that informative.
Volunteer the details, so we don't have to repeatedly reproduce the issue.
Similarly when writing config.ini.
def initialize_configuration_file(db_path: str) -> None:
No.
This is just wrong.
Clearly it's a cfg_path, not a database.
It's bad when # comments lie,
but worse when identifiers do that.
I doubt you meant to print "Updated database path".
Just chalk it up to copy-pasta -- happens to everyone.
That's why we solicit reviews.
def get_version() -> str:
return f"{__app_name__} v{__version__}"
Woooo, this is kind of interesting.
Almost an existential question.
Is the version 1.0, or is it v1.0 ?
I literally dealt with that issue
in a CI/CD toolchain for more than a year
across a dozen related products.
Some tools would unconditionally add the letter (vv1.0!),
some conditionally, some passed along the input unchanged.
Finally they settled on one answer.
I recommend that you not "helpfully" insert a v there.
Put a stake in the ground. Either we have (roughly) three
SemVer
numbers, or we define and document our own scheme
which is free to insist on initial v if desired.
But don't try to support a pair of related versioning schemes.
Life is too short.
These modules appear to achieve the project's design goals.
I would be willing to delegate or accept maintenance tasks on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44917,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, design-patterns, console, gui, mvp",
"url": null
} |
javascript, html, css
Title: Minesweeper game with HTML & CSS & JavaScript
Question: I made a Minesweeper game using HTML, CSS and JavaScript and would like to ask for advice and feedback specifically on the code.
Here are some questions to review:
Is the use of HTML semantics correct? I would like to know if I am using HTML tags properly and if there is any way to improve the semantic structure of the code.
Is there any way to improve the organization and reusability of the CSS code, any tips to make it more modular and easy to maintain?
Is there any way to optimize JavaScript code to make it more efficient and elegant? Any advice on best practices in terms of architecture or code writing?
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Minesweeper</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/normalize.css">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="icon" href="assets/img/favicon.png">
<script src="assets/js/index.js" defer></script>
</head>
<body>
<section class="minesweeper">
<h1>Minesweeper</h1>
<div class="level">
<button class="btn active" id="beginner">Beginner</button>
<button class="btn" id="intermediate">Intermediate</button>
<button class="btn" id="advanced">Advanced</button>
<button class="btn" id="new-game">New game</button>
</div>
<p class="info"> <span id="remaining-flags">10</span></p>
<table id="board"></table>
</section>
</body>
</html>
body {
background-color: #55ddff;
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
color: #263be8;
margin-bottom: 0;
}
.minesweeper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 10px;
} | {
"domain": "codereview.stackexchange",
"id": 44918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
.btn {
background-color: #0000ff;
border: 0;
color: #fff;
cursor: pointer;
font-weight: bold;
line-height: normal;
border-radius: 5px;
padding: 5px;
margin-left: 8px;
}
.active {
background-color: red;
}
.info {
color: red;
font-weight: bold;
font-size: 20px;
}
table {
border-spacing: 0px;
}
td {
padding: 0;
width: 25px;
height: 25px;
background-color: #fff;
border: 1px solid #a1a1a1;
text-align: center;
line-height: 20px;
font-weight: bold;
font-size: 18px;
}
.mine {
background: #eeeeee url(../img/mine.png) no-repeat center;
background-size: cover;
}
.flag {
background: #eeeeee url(../img/flag.png) no-repeat center;
background-size: cover;
}
.zero {
background-color: #eeeeee;
}
.one {
background-color: #eeeeee;
color: #0332fe;
}
.two {
background-color: #eeeeee;
color: #019f02;
}
.three {
background-color: #eeeeee;
color: #ff2600;
}
.four {
background-color: #eeeeee;
color: #93208f;
}
.five {
background-color: #eeeeee;
color: #ff7f29;
}
.six {
background-color: #eeeeee;
color: #ff3fff;
}
.seven {
background-color: #eeeeee;
color: #53b8b4;
}
.eight {
background-color: #eeeeee;
color: #22ee0f;
}
const BOARD = document.getElementById("board");
const REMAINING_FLAGS_ELEMENT = document.getElementById("remaining-flags");
const NEW_GAME_BUTTON = document.getElementById("new-game");
const LEVEL_BUTTONS = {
beginner: document.getElementById("beginner"),
intermediate: document.getElementById("intermediate"),
advanced: document.getElementById("advanced"),
};
const LEVEL_SETTINGS = {
beginner: { rows: 9, cols: 9, mines: 10 },
intermediate: { rows: 16, cols: 16, mines: 40 },
advanced: { rows: 16, cols: 30, mines: 99 },
}; | {
"domain": "codereview.stackexchange",
"id": 44918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
let currentLevel = "beginner";
let currentLevelConfig = LEVEL_SETTINGS[currentLevel];
let rows = currentLevelConfig.rows;
let columns = currentLevelConfig.cols;
let remainingMines = LEVEL_SETTINGS[currentLevel].mines;
let remainingFlags = remainingMines;
let totalCellsRevealed = 0;
let correctFlagsCount = 0;
let boardArray = [];
let gameFinish;
/**
* Creates the game board by generating the HTML table structure.
* Initializes the game board array.
* Updates the remaining flags count displayed on the webpage.
* Places the mines randomly on the board.
* Counts the number of adjacent mines for each cell.
*/
function createBoard() {
const BOARD_FRAGMENT = document.createDocumentFragment();
BOARD.textContent = "";
for (let i = 0; i < rows; i++) {
const ROW = document.createElement("tr");
boardArray[i] = [];
for (let j = 0; j < columns; j++) {
const CELL = document.createElement("td");
boardArray[i][j] = 0;
ROW.appendChild(CELL);
}
BOARD_FRAGMENT.appendChild(ROW);
}
BOARD.appendChild(BOARD_FRAGMENT);
REMAINING_FLAGS_ELEMENT.textContent = remainingFlags;
placeMines();
countAdjacentMines();
}
/**
* Randomly places the mines on the game board.
* Updates the "boardArray" with the "mine" value for each mine location.
*/
function placeMines() {
let minesToPlace = remainingMines;
while (minesToPlace > 0) {
const RANDOM_ROW = Math.floor(Math.random() * rows);
const RANDOM_COL = Math.floor(Math.random() * columns);
if (boardArray[RANDOM_ROW][RANDOM_COL] !== "mine") {
boardArray[RANDOM_ROW][RANDOM_COL] = "mine";
minesToPlace--;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
/**
* Counts the number of adjacent mines for each non-mine cell on the game board.
* Updates the "boardArray" with the corresponding mine count for each cell.
*/
function countAdjacentMines() {
for (let row = 0; row < rows; row++) {
for (let col = 0; col < columns; col++) {
if (boardArray[row][col] !== "mine") {
let minesCount = 0;
for (let i = row - 1; i <= row + 1; i++) {
for (let j = col - 1; j <= col + 1; j++) {
const VALID_ROW = i >= 0 && i < rows;
const VALID_COL = j >= 0 && j < columns;
if (VALID_ROW && VALID_COL && boardArray[i][j] === "mine") {
minesCount++;
}
}
}
boardArray[row][col] = minesCount;
}
}
}
}
/**
* Reveals the content of a cell and handles game logic.
*
* @param {number} row - The row index of the cell.
* @param {number} col - The column index of the cell.
*/
function revealCell(row, col) {
const CELL = BOARD.rows[row].cells[col];
if (CELL.classList.contains("flag") || CELL.textContent || gameFinish) return;
if (boardArray[row][col] === "mine") {
gameFinish = true;
revealMines();
alert("Game over! You hit a mine.");
} else if (boardArray[row][col] === 0) {
revealAdjacentsCells(row, col);
} else {
const NUMBER_CLASS = getNumberClass(boardArray[row][col]);
CELL.textContent = boardArray[row][col];
CELL.classList.add(NUMBER_CLASS);
}
totalCellsRevealed++;
if (checkWin()) {
gameFinish = true;
alert("You win!");
return;
}
}
/**
* Reveals adjacents cells surrounding the specified cell.
*
* @param {number} row - The row index of the cell.
* @param {number} col - The column index of the cell.
*/
function revealAdjacentsCells(row, col) {
const CELL = BOARD.rows[row].cells[col];
if (CELL.textContent) return;
CELL.classList.add("zero"); | {
"domain": "codereview.stackexchange",
"id": 44918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
if (CELL.textContent) return;
CELL.classList.add("zero");
for (let i = row - 1; i <= row + 1; i++) {
for (let j = col - 1; j <= col + 1; j++) {
const VALID_ROW = i >= 0 && i < rows;
const VALID_COL = j >= 0 && j < columns;
if (VALID_ROW && VALID_COL && !(i === row && j === col)) {
const CELL = BOARD.rows[i].cells[j];
if (!CELL.classList.value) revealCell(i, j);
}
}
}
}
/**
* Reveals all the mines on the game board.
* Adds the "mine" class to the HTML elements representing mine cells.
*/
function revealMines() {
for (let i = 0; i < rows; i++) {
for (let j = 0; j < columns; j++) {
if (boardArray[i][j] === "mine") {
const MINE_CELL = BOARD.rows[i].cells[j];
MINE_CELL.classList.add("mine");
}
}
}
}
/**
* Returns the CSS class name for a given number.
*
* @param {number} number - The number of adjacent mines.
* @returns {string} The CSS class name for the number.
*/
function getNumberClass(number) {
switch (number) {
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
default:
return "";
}
}
/**
* Changes the game level to the specified level.
*
* @param {string} level - The level to change to.
*/
function changeLevel(level) {
if (currentLevel === level) return;
gameFinish = false;
LEVEL_BUTTONS[currentLevel].classList.remove("active");
currentLevel = level;
LEVEL_BUTTONS[currentLevel].classList.add("active");
currentLevelConfig = LEVEL_SETTINGS[currentLevel];
rows = currentLevelConfig.rows;
columns = currentLevelConfig.cols;
remainingMines = currentLevelConfig.mines;
remainingFlags = remainingMines;
REMAINING_FLAGS_ELEMENT.textContent = remainingFlags;
createBoard();
} | {
"domain": "codereview.stackexchange",
"id": 44918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
createBoard();
}
/**
* Toggles the flag on a cell when the player right-clicks on it.
*
* @param {HTMLElement} cell - The HTML element representing the cell.
*/
function addFlagToCell(cell) {
if (cell.classList.contains("zero") || cell.textContent || gameFinish) return;
const HAS_FLAG = cell.classList.contains("flag");
const ROW = cell.parentNode.rowIndex;
const COL = cell.cellIndex;
cell.classList.toggle("flag", !HAS_FLAG);
remainingFlags += HAS_FLAG ? 1 : -1;
REMAINING_FLAGS_ELEMENT.textContent = remainingFlags;
if (!HAS_FLAG && boardArray[ROW][COL] === "mine") correctFlagsCount++;
if (checkWin()) {
gameFinish = true;
alert("You win!");
return;
}
}
/**
* Checks if the player has won the game.
* Returns true if all non-mine cells have been revealed and all flags are correctly placed on mine cells.
*
* @returns {boolean} True if the player has won, false otherwise.
*/
function checkWin() {
return (
totalCellsRevealed === rows * columns - remainingMines &&
correctFlagsCount === remainingMines
);
}
/**
* Resets the game by resetting the game variables and creating a new board.
*/
function newGame() {
gameFinish = false;
correctFlagsCount = 0;
totalCellsRevealed = 0;
remainingMines = currentLevelConfig.mines;
remainingFlags = remainingMines;
REMAINING_FLAGS_ELEMENT.textContent = remainingFlags;
createBoard();
}
document.addEventListener("click", (event) => {
const TARGET = event.target;
if (TARGET.tagName === "TD") {
const ROW = TARGET.parentNode.rowIndex;
const COL = TARGET.cellIndex;
revealCell(ROW, COL);
} else if (TARGET === LEVEL_BUTTONS["beginner"]) {
changeLevel("beginner");
} else if (TARGET === LEVEL_BUTTONS["intermediate"]) {
changeLevel("intermediate");
} else if (TARGET === LEVEL_BUTTONS["advanced"]) {
changeLevel("advanced");
} else if (TARGET === NEW_GAME_BUTTON) {
newGame();
}
}); | {
"domain": "codereview.stackexchange",
"id": 44918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
document.addEventListener("contextmenu", (event) => {
const TARGET = event.target;
if (TARGET.tagName === "TD") {
event.preventDefault();
addFlagToCell(TARGET);
}
});
createBoard();
Github link
Live host
Answer: bugs
Clicking on revealed zero cells would increase totalCellsRevealed unexpected.
semantics
It is a good idea to add type="button" to your buttons.
Each clickable cell should be a <button type="button"> not <td>. I would expect a <button> is inserted into the <td>.
You can add role="grid" to the table and role="row" to tr, role="gridcell" to td.
You can add aria-pressed to buttons for selecting levels.
css
Your css works. just personal preference, I would avoid using zero to eight as class names like this.
javascript
Getting classname for number could be simplified into ["", "one", /* ... */, "eight"][number] || "".
You could add data- attribute to the three level buttons, so JavaScript can only read the dataset to get the difficulty level. | {
"domain": "codereview.stackexchange",
"id": 44918,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
python, file
Title: Find out all the different files from two different paths efficiently in Windows (with Python)
Question: Well, recently I'm working on a program which is able to sync files between different folders.
However, as a fresh man, the algorithm I worte seems feasible, but looks really disgusting, and inefficient as well (bruh~)
The following lines are the related things I wrote,
I really hope there would be experts who can help me improve my code
def scan_items(folder_path): # 扫描路径下所有文件夹
def scan_folders_in(f_path): # 扫描目录下所有的文件夹,并返回路径列表
surf_items = os.scandir(f_path)
folders = [f_path]
for item_data in surf_items:
if item_data.is_dir():
folders.extend(scan_folders_in(item_data.path)) # 继续遍历文件夹内文件夹,直到记下全部文件夹路径
folders = sorted(set(folders)) # 排序 + 排除重复项
surf_items.close()
return folders
file_store = []
folder_store = scan_folders_in(folder_path)
for folder in folder_store: # 遍历所有文件夹
files = [folder + '\\' + dI for dI in os.listdir(folder) if os.path.isfile(os.path.join(folder, dI))]
# 如上只生成本文件夹内 文件的路径
file_store.extend(files) # 存储上面文件路径
for i in range(len(file_store)):
file_store[i] = file_store[i][len(folder_path)::] # 返回相对位置
result = [folder_store, file_store]
return result
And here is the main part,
and the 'get_task()' part is the most important one
def sf_sync_dir(path1, path2, single_sync, language_number, area_name=None, pass_item_rpath='', pass_folder_paths=''):
from LT_Dic import sf_label_text_dic # Label information from another file
def sf_show_notice(path_1, path_2, sf_errorname): # Win10toast used | {
"domain": "codereview.stackexchange",
"id": 44919,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, file",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.