Matlab2048游戏代码
时间: 2023-12-05 18:06:30 浏览: 59
以下是一个简单的 Matlab 2048 游戏代码:
```matlab
clear
clc
% 初始化游戏板
board = zeros(4,4);
% 在两个随机位置添加初始数字2
emptyCells = find(board == 0);
randIdx = emptyCells(randperm(length(emptyCells),2));
board(randIdx) = 2;
while true
% 打印游戏板
disp(board)
% 判断游戏是否结束
if max(board(:)) == 2048
disp('You win!')
break
elseif all(board(:) ~= 0) && ~canMerge(board)
disp('Game over!')
break
end
% 获取用户输入
direction = input('Enter direction (w/a/s/d): ','s');
% 根据用户输入移动游戏板
switch direction
case 'w'
board = moveUp(board);
case 'a'
board = moveLeft(board);
case 's'
board = moveDown(board);
case 'd'
board = moveRight(board);
otherwise
disp('Invalid input')
end
% 在随机位置添加新数字2
emptyCells = find(board == 0);
if ~isempty(emptyCells)
randIdx = emptyCells(randi(length(emptyCells)));
board(randIdx) = 2;
end
end
function board = moveUp(board)
for j = 1:4
col = board(:,j);
[col, merged] = merge(col);
board(:,j) = col;
end
end
function board = moveDown(board)
for j = 1:4
col = board(end:-1:1,j);
[col, merged] = merge(col);
board(end:-1:1,j) = col;
end
end
function board = moveLeft(board)
for i = 1:4
row = board(i,:);
[row, merged] = merge(row);
board(i,:) = row;
end
end
function board = moveRight(board)
for i = 1:4
row = board(i,end:-1:1);
[row, merged] = merge(row);
board(i,end:-1:1) = row;
end
end
function [arr, merged] = merge(arr)
% 移动非零数字到数组开头
nonZeroIdx = arr ~= 0;
arr = [arr(nonZeroIdx) zeros(1,sum(~nonZeroIdx))];
% 合并相同数字
merged = false(size(arr));
for i = 2:length(arr)
if arr(i) == arr(i-1) && ~merged(i-1) && ~merged(i)
arr(i-1) = 2*arr(i-1);
arr(i) = 0;
merged(i-1) = true;
end
end
% 再次移动非零数字到数组开头
nonZeroIdx = arr ~= 0;
arr = [arr(nonZeroIdx) zeros(1,sum(~nonZeroIdx)))];
end
function canMergeFlag = canMerge(board)
canMergeFlag = false;
for i = 1:3
for j = 1:3
if board(i,j) == board(i+1,j) || board(i,j) == board(i,j+1)
canMergeFlag = true;
return
end
end
end
end
```
这个代码使用了一个简单的合并算法来移动游戏板,如果您需要更复杂的合并算法或更高级的游戏功能,可以自行修改该代码。
阅读全文