—-Pong

clear; clc; close all;

%
fprintf(‘\n*****************************************\n’)
fprintf(‘Hello! Welcome to the Pong! \n’);
fprintf(‘In this game,you need to use your paddle to hit back the pong. \n ‘);
fprintf(‘Once you fail to hit back the pong, you loss \n’);
fprintf(‘The score will be added up for every successful hitting \n’);
fprintf(‘Good Luck! \n’);
fprintf(‘\n*****************************************\n’)

%———Board———–%
PongFigure = figure(‘color’, ‘white’,’KeyPressFcn’, @keyboardFunction);
PongAxes = axes(‘color’, ‘black’,’XLim’, [0 100],’YLim’,[-5 100], ‘XTickLabels’, [ ], ‘YTickLabels’, [ ], ‘position’,[0.05 0.05 0.9 0.9]);

%—————-Ball Commands———%
%%Create Pong Ball, the (50,25) is the starting position, and the marker
BallVelocity = [1,1];
BallPosition = [50, 25];
Ball = line(BallPosition(1),BallPosition(2), ‘marker’,’.’, ‘markersize’, 30, ‘color’, ‘white’);

%————Paddle Setup————%
%Global Variable keeps track of Paddle Center
global BlockCenter;
BlockCenter = 15;
%%15 = height/2
Paddle = line([0 0],[BlockCenter – 15, BlockCenter + 15],’linewidth’, 7, ‘color’, ‘white’);

%————-Loop—————–%
tic; %sets timer
n=1
Score = 0
while toc > 0 && n == 1 %keeps track of time

if BallPosition(1) < 0 || BallPosition(1) > 100
BallVelocity(1) = – BallVelocity(1);
end
if BallPosition(2) < 0 || BallPosition(2) > 100
BallVelocity(2) = – BallVelocity(2);
end
if BallPosition(1) <= 0
if abs(BallPosition(2) – BlockCenter) < 15
BallVelocity= – BallVelocity;
Score = Score + 1
else
msgbox(sprintf(‘Restart the Program to Try Again, You Lost, your score was %0f’, Score))
n=n+1 %this ends the program when you lose
end
end

BallPosition = BallPosition + BallVelocity;
set(Ball,’XData’,BallPosition(1),’YData’,BallPosition(2));

set(Paddle, ‘YData’, [BlockCenter – 15, BlockCenter + 15]);

pause(0.02);
end

%difficulty
difficulty = Score*0.1 + 1
if 20 > Score && Score > 10
BallVelocity(1)= BallVelocity(1)*difficulty
end
if 30 > Score && Score >= 20
BallVelocity(1)= BallVelocity(1)*difficulty
BallVelocity(2)= BallVelocity(1)*difficulty
end

%————-Controls———-%
function keyboardFunction(figure, event)
global BlockCenter;
switch event.Key
case ‘uparrow’
BlockCenter = BlockCenter + 5;
case ‘downarrow’
BlockCenter = BlockCenter – 5;
end
if BlockCenter >= 85 %makes it so that the paddle can’t escape borders
BlockCenter = 85;
end
if BlockCenter <= 10
BlockCenter = 10;
end

end

 

Pong Game File