write a code for the game pong in matlab

Here's an example code for Pong game in MATLAB:

main.m
% Pong game
clc; clear all; close all;
% paddle size
paddle_h = 0.2;
paddle_w = 0.02;
% initial position & velocity
paddle_speed = 0.05;
ball_pos = [0.5, 0.5];
ball_velocity = [-0.03, 0.01];
paddle_pos = 0.5 - paddle_h/2;

while true
    % move paddle
    if rand < 0.5 && paddle_pos > 0
        paddle_pos = paddle_pos - paddle_speed;
    elseif paddle_pos + paddle_h < 1
        paddle_pos = paddle_pos + paddle_speed;
    end
    
    % move ball
    ball_pos = ball_pos + ball_velocity;
    
    % ball reflection
    if ball_pos(2) < 0 || ball_pos(2) > 1
        ball_velocity(2) = -ball_velocity(2);
    end
    if ball_pos(1) < 0
        ball_velocity(1) = -ball_velocity(1);
    elseif ball_pos(1) > 1
        if ball_pos(2) >= paddle_pos && ball_pos(2) <= paddle_pos + paddle_h
            ball_velocity(1) = -ball_velocity(1);
        else
            break
        end
    end
    
    % plot scene
    h = figure(1);
    set(h, 'KeyPressFcn', @movePaddle, 'Position', [600, 300, 400, 400])
    hold off
    rectangle('Position', [0, paddle_pos, paddle_w, paddle_h], 'FaceColor', 'r');
    hold on
    plot(ball_pos(1), ball_pos(2), 'o', 'MarkerSize', 10, 'MarkerFaceColor', 'g');
    xlim([0 1])
    ylim([0 1])
    pause(0.01)
end

% Move paddle
function movePaddle(~,event)
    global paddle_pos paddle_speed;
    if strcmp(event.Key,'uparrow')
        paddle_pos = paddle_pos + paddle_speed;
    elseif strcmp(event.Key,'downarrow')
        paddle_pos = paddle_pos - paddle_speed;
    end
end
1508 chars
58 lines

This script defines the size of the playing field and the initial velocity of the ball and the paddle. The script then enters an infinite loop where it moves the ball and the paddle and checks whether the ball has left the playing field or collided with the paddle.

The function movePaddle is a callback function that is called whenever the up or down arrow key is pressed. It changes the position of the paddle accordingly.

related categories

gistlibby LogSnag