I have a problem with the movement of a pawn by two fields in its first move does anyone have a suggestion for a solution
28 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
function chess_game()
% Funkcja główna inicjalizująca grę w szachy
% Inicjalizacja stanu gry
gameState = struct();
gameState.board = initialize_board();
gameState.currentPlayer = 'white';
gameState.selectedPiece = [];
% Utworzenie GUI
fig = figure('Name', 'Gra w Szachy', 'NumberTitle', 'off', 'MenuBar', 'none', 'UserData', gameState);
ax = axes('Parent', fig, 'Position', [0 0 1 1], 'XTick', [], 'YTick', []);
axis(ax, [0 8 0 8]);
hold on;
% Wyświetlenie planszy
draw_board(ax, gameState.board);
% Obsługa kliknięcia myszy
set(fig, 'WindowButtonDownFcn', @(src, event)on_click(ax, src));
end
function board = initialize_board()
% Inicjalizuje planszę z ustawieniem początkowym figur
board = {
'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R';
'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p';
'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r';
};
end
function draw_board(~, board)
% Rysuje szachownicę i figury
colors = [1 1 1; 0.8 0.8 0.8];
for row = 1:8
for col = 1:8
% Rysowanie pól
rectColor = colors(mod(row + col, 2) + 1, :);
rectangle('Position', [col-1, 8-row, 1, 1], 'FaceColor', rectColor, 'EdgeColor', 'k');
% Rysowanie figur
piece = board{row, col};
if ~isempty(piece)
text(col-0.5, 8-row+0.5, piece, 'HorizontalAlignment', 'center', ...
'FontSize', 20, 'FontWeight', 'bold');
end
end
end
end
function on_click(ax, fig)
% Funkcja obsługująca kliknięcia myszy
pos = get(ax, 'CurrentPoint');
x = floor(pos(1,1)) + 1; % Zaokrąglij współrzędne w poziomie i dopasuj do indeksów
y = 8 - floor(pos(1,2)); % Dopasuj współrzędne w pionie (odwrócenie osi Y)
% Pobranie stanu gry z figury
gameState = get(fig, 'UserData');
if x >= 1 && x <= 8 && y >= 1 && y <= 8
disp(['Kliknięto na pole: (', num2str(x), ', ', num2str(y), ')']);
if isempty(gameState.selectedPiece)
% Wybór figury
piece = gameState.board{y, x};
if ~isempty(piece)
if (strcmp(gameState.currentPlayer, 'white') && any(ismember(piece, 'RNBQKP'))) || ...
(strcmp(gameState.currentPlayer, 'black') && any(ismember(piece, 'rnbqkp')))
gameState.selectedPiece = [y, x];
disp(['Wybrano figurę: ', piece, ' na pozycji (', num2str(x), ', ', num2str(y), ')']);
else
disp('Nie możesz wybrać tej figury.');
end
else
disp('Nie wybrano figury.');
end
else
% Sprawdzenie, czy kliknięto ponownie na wybraną figurę
if isequal(gameState.selectedPiece, [y, x])
disp('Anulowano wybór figury.');
gameState.selectedPiece = [];
else
% Ruch figury
[sy, sx] = deal(gameState.selectedPiece(1), gameState.selectedPiece(2));
piece = gameState.board{sy, sx};
if is_valid_move(gameState.board, piece, [sy, sx], [y, x], gameState.currentPlayer)
% Wykonanie ruchu
gameState.board{sy, sx} = ''; % Usuwamy figurę z poprzedniego pola
gameState.board{y, x} = piece; % Umieszczamy figurę na nowym polu
gameState.selectedPiece = [];
% Przełącz gracza
gameState.currentPlayer = switch_player(gameState.currentPlayer);
% Odśwież planszę
cla(ax);
draw_board(ax, gameState.board);
else
disp('Ruch niezgodny z zasadami.');
end
end
end
% Zaktualizowanie stanu gry w figurze
set(fig, 'UserData', gameState);
end
end
function valid = is_valid_move(board, piece, from, to, currentPlayer)
% Funkcja sprawdzająca, czy ruch jest poprawny
[sy, sx] = deal(from(1), from(2));
[dy, dx] = deal(to(1), to(2));
dy_diff = dy - sy;
dx_diff = abs(dx - sx);
targetPiece = board{dy, dx};
% Sprawdzenie, czy ruch jest w granicach planszy
if dx < 1 || dx > 8 || dy < 1 || dy > 8
valid = false;
return;
end
% Nie można zbijać swoich figur
if ~isempty(targetPiece) && ...
((strcmp(currentPlayer, 'white') && ismember(targetPiece, 'RNBQKP')) || ...
(strcmp(currentPlayer, 'black') && ismember(targetPiece, 'rnbqkp')))
valid = false;
return;
end
% Zasady ruchu dla każdej figury
switch lower(piece)
case 'p' % Pion
direction = strcmp(currentPlayer, 'white') * 2 - 1; % 1 dla białych, -1 dla czarnych
startRow = strcmp(currentPlayer, 'white') * 2 + 1; % Rząd startowy dla białych i czarnych
if isempty(targetPiece)
% Ruch o jedno pole do przodu
if dy_diff == direction && dx_diff == 0
valid = true;
% Ruch o dwa pola do przodu z pozycji startowej
elseif dy_diff == 2 * direction && dx_diff == 0 && sy == startRow
if isempty(board{sy + direction, sx}) && isempty(board{dy, dx})
valid = true;
else
valid = false;
end
else
valid = false;
end
else
% Zbijanie na ukos
valid = (dx_diff == 1) && (dy_diff == direction);
end
case 'r' % Wieża
valid = (dx_diff == 0 || dy_diff == 0) && path_is_clear(board, from, to);
case 'n' % Skoczek
valid = (dx_diff == 2 && abs(dy_diff) == 1) || (dx_diff == 1 && abs(dy_diff) == 2);
case 'b' % Goniec
valid = (dx_diff == abs(dy_diff)) && path_is_clear(board, from, to);
case 'q' % Hetman
valid = ((dx_diff == 0 || dy_diff == 0) || (dx_diff == abs(dy_diff))) && path_is_clear(board, from, to);
case 'k' % Król
valid = max(abs(dx_diff), abs(dy_diff)) == 1;
otherwise
valid = false;
end
end
function clear = path_is_clear(board, from, to)
% Sprawdza, czy ścieżka między polami jest wolna od innych figur
[sy, sx] = deal(from(1), from(2));
[dy, dx] = deal(to(1), to(2));
stepY = sign(dy - sy);
stepX = sign(dx - sx);
y = sy + stepY;
x = sx + stepX;
while y ~= dy || x ~= dx
if ~isempty(board{y, x})
clear = false;
return;
end
y = y + stepY;
x = x + stepX;
end
clear = true;
end
function nextPlayer = switch_player(currentPlayer)
% Przełącza aktywnego gracza
if strcmp(currentPlayer, 'white')
nextPlayer = 'black';
else
nextPlayer = 'white';
end
end
0 comentarios
Respuestas (1)
dpb
el 14 de Dic. de 2024 a las 16:14
Editada: dpb
el 14 de Dic. de 2024 a las 23:23
You'll need to keep a state variable for each that indicates when it has yet to be moved...or, alternatively, you can always check to see if is in its original location before every move since a pawn cannot return home (other than after promotion in which case you would know by it having its new moniker).
Never attempted writing one; otomh the state would seem better as it also could hold the promotion info...that, of course, presumes the game you're modeling is that complete.
ADDENDUM:
It would seem there would have to be a state variable for each piece already keeping track of its position, etc., ...if so, making this an additional field would seem natural (or reconsidering the data structure in use to add such).
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!