clc;
clear;
close all;
% J 向右移动
% F 向左移动
% 设置游戏参数
playerWidth = 30; % 玩家宽度
playerHeight = 30; % 玩家高度
playerSpeed = 5; % 玩家速度
obstacleWidth = 60; % 障碍物宽度
obstacleHeight = 50; % 障碍物高度z
obstacleSpeed = 10; % 障碍物下落速度
obstacleGap = 20; % 障碍物间距

% 游戏界面
global pPos;
pPos = [250, 50, playerWidth, playerHeight];
figure('KeyPressFcn', @onKeyPress); % 键盘监听
% figure
axis([0 600 0 400]);
hold on;
player = rectangle('Position', pPos, 'FaceColor', 'b');
obstacles = []; % 存储障碍物
score = 0; % 计分
gameOver = false; % 游戏结束标志
% 游戏主循环
while ~gameOver
% 生成障碍物
if mod(score, obstacleGap) == 0
x = randi([1, 550]);
obstacles = [obstacles; rectangle('Position', [x, 400, obstacleWidth, obstacleHeight], 'FaceColor', 'g')];
end
% 倒序遍历障碍物并移除
for i = length(obstacles):-1:1
pos = get(obstacles(i), 'Position');
pos(2) = pos(2) - obstacleSpeed; % 障碍物下移
set(obstacles(i), 'Position', pos);
% 判断碰撞
if pos(2) < playerHeight && pos(1) < pPos(1) + playerWidth && ...
pos(1) + obstacleWidth > pPos(1) && pos(2) + obstacleHeight > pPos(2)
gameOver = true; % 游戏结束
text(250, 200, 'Game Over', 'FontSize', 30, 'Color', 'r');
break;
end
% 删除画面外的障碍物
if pos(2) + obstacleHeight < 0
delete(obstacles(i));
obstacles(i) = []; % 从列表中移除该障碍物
end
end
% 更新分数
score = score + 1;
pause(0.01)
drawnow;
delete(player);
player = rectangle('Position', pPos, 'FaceColor', 'b');
end
function onKeyPress(~, event)
% 键盘监听函数
global pPos
switch event.Key
case 'f'
% Left movement
if pPos(1) > 0
pPos(1) = pPos(1) - 5;
end
case 'j'
% Right movement
if pPos(1) < 570 % 保证玩家不会超出右边界
pPos(1) = pPos(1) + 5;
end
end
end
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删