Developing Program Motion1

Introduction

Steven Binns, when teaching younger students, gradually changed the code of program Motion1 until it became program Motion2 with the code below. The ellipse now bounces round the GameView with different speeds depending on the direction of movement. Note the use of the operators += and -= for increasing and decreasing the value of a numeric variable.

See also an adapted version where the user can select a value for the delay and for the height, width and colour of the mobile.

Code of Motion2

unit Unit1;

interface

uses
  System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application,
  SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics;

type
  TCanvasProject = class(TW3CustomGameApplication)
  protected
    procedure ApplicationStarting; override;
    procedure ApplicationClosing; override;
    procedure PaintView(Canvas: TW3Canvas); override;
  end;

const
  MOB_WIDTH = 20;
  MOB_HEIGHT = 25;
var
  MobX: integer;
  GoingRight: Boolean;
  GoingUp: Boolean;
  MobY: integer = 100;

implementation

procedure TCanvasProject.ApplicationStarting;
begin
  inherited;
  GoingRight := True;
  MobX := 5;
  GameView.Delay := 1;           // 1 millisecond
  GameView.StartSession(True);
end;

procedure TCanvasProject.ApplicationClosing;
begin
  GameView.EndSession;
  inherited;
end;

procedure TCanvasProject.PaintView(Canvas: TW3Canvas);
begin
  // Clear background to teal
  Canvas.FillStyle := 'Green';
  Canvas.FillRectF(0, 0, GameView.Width, GameView.Height);
  Canvas.FillStyle := 'Silver';
  Canvas.BeginPath;
  Canvas.Ellipse(MobX, MobY, MobX + MOB_WIDTH, MobY + MOB_HEIGHT); // leftX, topY, rightX, bottomY
  Canvas.Fill;

  // Change position of mobile before next paint.
  if GoingRight = True then // If ball is going right then
    begin                   // do whatever is below
      MobX += 5;  //increase MobX by 5
    end
  else               // Otherwise
    begin            
      MobX -= 2;     // decrease MobX by 2
    end;
  // Change direction when right of ellipse is at right of GameView or beyond.

  if MobX + MOB_WIDTH >= GameView.Width  then //If the ball is on the right of the screen
    begin
      GoingRight := False;   // Going right is no longer true i.e it will go left
    end
  // Change direction when left of ellipse is at left of GameView or beyond.
  else if MobX <= 0 then
    begin
      GoingRight := True;
    end;

  if GoingUp = true then
    begin
      MobY -= 3;
    end
  else
    begin
      MobY += 6;
    end;

  if MobY <= 0 then
    begin
      GoingUp := False;
    end
  else if MobY + MOB_HEIGHT >= GameView.Height then
    begin
      GoingUp := True;
    end;
end;

end.

Programming - a skill for life!

How to write programs in Smart Pascal