SAPUI5 – 11 Advance – Enjoyment with Super Mario in SAPUI5

It takes me back to my early years, when I used to go to my friends’ houses merely to play the video game Enjoyment with Super Mario in SAPUI5 under the pretense of group study. To what extent has anyone done it? However, my report cards started to appear unsatisfactory, so my parents soon discovered me and issued a warning. I’m grateful to Super Mario. Consequently, creating my own Mario became another goal on my bucket list. This served as the motivation. In any case, I’ve come to the realization that “while playing video games is very enjoyable, there’s nothing quite like the euphoria and fulfillment that comes from creating your own game.”

Let us get started.

The next goal is to construct barriers and a few more opponents, like cacti, professor Frankly, and blah blah (you name it). I won’t go into that today. Our Mario is currently immortal as well. Haha. Even if Mario touches the enemy, nothing occurs to him (since I haven’t developed any logic for that). I’ll gradually work toward completing each one as I have free time.

  1. Blue Sky: The blue background that has a sky-like quality.
  2. The Road: Mario goes down a path or road composed primarily of bricks.
  3. Clouds: Three different-sized, white clouds (3a and 3b).
  4. Mario: The protagonist and hero of our story, Mario, is able to leap and travel ahead or backward by pressing the arrow keys.
  5. Enemies: Several enemies move and blink their eyes.

Let us discuss about the above mentioned characters/objects one by one (easy to difficult in order).

1. The Blue Sky:-

It’s probably the simplest task. All you need to do is apply a custom CSS class to the tag in the XML view, giving it a blue background color.

<Page title=”” showHeader=”false” class=’w3-marioSky’
enableScrolling=”false”>

showHeader=”false” will make sure that the header is invisible as we don’t need one. Also we have disabled the scrolling effect by writing enableScrolling=”false”.

The custom CSS looks like below

.w3-marioSky{
color:#fff!important;
background-color:#4966de!important
}

You recently learnt how to use CSS to apply background color to SAPUI5.

The blue sky appears lovely right now. Is it not? We will then construct a road for our Mario to perform on.

The Road: Pay close attention to the brick-built road below.

The bricks are two distinct sizes. One is tiny, while the other is large. Take note of the arrangement of the bricks.The first, third, and fifth brick lines in our five-line set have comparable patterns with the second and fourth lines.

The first, third, and fifth brick lines in our five-line set all show comparable patterns, as do the second and fourth lines.

However, how would the UI display the blocked-off road/wall? For a technical person, using a static image doesn’t seem very promising. Why? Since pictures take up a lot of memory.

It’s not complicated science. You should be able to draw nearly anything in this environment, including lines, rectangles, triangles, circles, and curves, after you understand the HTML Canvas element. Believe me.

Actual application of SAPUI5’s Custom Control.

Now let’s develop a unique Canvas Control. Since my fellow author Sagar has previously written the step-by-step instructions for creating a custom control, I won’t repeat them here.

I have made a JavaScript file called CanvasCloud.js and a subdirectory called “control” (see the image below).

I’ve used an HTML5 Canvas tag with some default width and height in the CanvasCloud.js code. I have the option to use several techniques that allow me to create curves or lines directly in the JS file. However, I would have preferred to do it in the controller file to keep things simple. This is the CanvasCloud.js code content.

sap.ui.core.Control.extend(“control.CanvasCloud”, {
metadata: {
properties: {
“width”: {
type: “string”,
defaultValue: “578”
},
“height”: {
type: “string”,
defaultValue: “200”
}
},
aggregations: {},
events: {}
},
init: function () {},
renderer: {
render: function (oRm, oControl) {
oRm.write(“<canvas height=” + oControl.getHeight() + ” width=” + oControl.getWidth() + “>”);
oRm.write(“</canvas>”);
}
}
});

We have completed our bespoke SAPUI5 canvas control. We’ll utilize this to draw any item that our game requires, such as clouds, enemies, bricked roads and walls.

First, let’s utilize the custom control found in the XML view. Let’s examine the crucial code below.

<core:View xmlns:core=”sap.ui.core” xmlns:mvc=”sap.ui.core.mvc”
xmlns=”sap.m” controllerName=”supermario.firstView” xmlns:html=”http://www.w3.org/1999/xhtml”
xmlns:demo=”control”>
<Page title=”Title” showHeader=”false” class=’w3-marioSky’
enableScrolling=”false”>
<content>
<demo:CanvasCloud id=”cl1″></demo:CanvasCloud>
<demo:CanvasCloud id=”canvas” class=”enemy”></demo:CanvasCloud>
<VBox id=”character” class=”character” />
<FlexBox class=”w3-display-container”>
<demo:CanvasCloud id=”brick1″ width=”1366″ class=”w3-display-bottommiddle w3-container”></demo:CanvasCloud>
<demo:CanvasCloud id=”brick2″ width=”1366″></demo:CanvasCloud>
<demo:CanvasCloud id=”brick3″ width=”1366″></demo:CanvasCloud>
<demo:CanvasCloud id=”brick4″ width=”1366″></demo:CanvasCloud>
<demo:CanvasCloud id=”brick5″ width=”1366″></demo:CanvasCloud>
</FlexBox>
</content>
</Page>
</core:View>

Custom namespace “demo” has been assigned in lieu of “control.”You are free to use whatever name you choose.

I have to draw five bricked-rows, hence I have written the tag five times. In case you need to create more rows than one, my recommendation would be to utilize a JavaScript for-loop that can handle the operation of constructing numerous rows.

Let’s sketch the first brick, a rectangle, with dimensions of 20 by 10 and placed at coordinates (2, 130).

// Begin of drawing the bricks
onAfterRendering:function(){
      var brick1 = $(‘canvas’);
      var context_brick = brick1[2].getContext(‘2d’);
     context_brick.beginPath();
     context_brick.rect(2,130, 20, 10);
}

Drawn using the code above is a single rectangle. Let’s make a few more bricks in a for-loop that are 40 wide and 10 high.

var startPoint1=22; /*Because you have already created a rectangle which started at x-pos 2 and have occupied 20 width*/
var width=40;

//1st row other bricks
for(var i=0;startPoint1<screen.availWidth;i++,startPoint1=startPoint1+40){
context_brick.rect(startPoint1,130, width, 10);
}

JavaScript’s for loop was just taught to us.

You have depicted a single row of bricked roads using this.

All you need to do now is repeat the process five times to obtain a road. However, hold on… Your road will turn completely black if you test this code.These bricks are white on black with a narrow border. Our desired brick color was orange, and we wanted the borders to be substantial. Let’s give them some beauty.

context_brick.fillStyle = ‘orange’;
context_brick.fill();
context_brick.lineWidth = 2;
context_brick.strokeStyle = ‘black’;
context_brick.stroke();

You’re done there. The sky is blue now, and the brickwork has a lovely orange hue.

The Sky:

The sky appears beautiful, yet it lacks charm. The sky will appear more natural with the white clouds.

If you look closely at any of the clouds in the above image, you will realize that they are made up of a few various sized and shaped curves that, when combined, resemble clouds.

// Begin of Draw clouds
var canvas = $(‘canvas’);
var context = canvas[0].getContext(‘2d’);
// begin custom shape
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 280, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20,170,80);
// complete custom shape
context.closePath();
context.lineWidth = 5;
context.fillStyle = ‘white’;
context.fill();
// end of Draw clouds

To draw two clouds, you can repeat the same steps twice. Simply try to use smaller numbers in the bezierCurveTo method argument if you require a smaller cloud.

Suppose you wish to sketch a curve that is three times smaller.

We have created two clouds, a five-row brick road, and a blue sky thus far. This is the current appearance.

It’s now time to present Mario, the protagonist of our game.

  1. Mario

Up till now, we have drawn rectangles and curves using the canvas custom control. Similar to this, we can draw Mario using straight lines, circles, rectangles, curves, and other shapes. However, drawing Mario beautifully calls for artistic imagination. Additionally, we must attend to Mario’s live actions, such as his eye movements and limb motions during jumps and sprints. It’s going to take a long time.Let’s not sketch Mario for the time being as a result. A vector image of Mario with a transparent background will be used.

We will keep two different versions of the Mario image. One with the Mario Face facing towards right and the other image basically the mirror image i.e Mario facing left. This will be helpful when we have to switch direction of Mario when we press Right arrow and Left arrow key in the keyboard.

All we need to is to switch the image based on user action.

Pseudocode :-

Find the keyboard shortcut =>

The Mario image with Mario facing left will appear if the detected key is the left arrow key; else, the Mario image with Mario facing right will appear.

Now let’s really write the code.

First, open the xml view and build a VBox. Using CSS, we will insert the background picture.

<VBox id=”character” class=”character” />
Look at the CSS code below
.character {
background-image: url(“<yourimge_url>”),
position: absolute;
width: 70px;
height:97px;
}

Let us initialize the Characters initial position.

// / store reference to character’s position and element
var character = {
x:10,
y: Math.ceil(screen.availHeight*0.68),
speedMultiplier: 2,
element: document.getElementById(this.byId(“character”).sId)
};

Code for key detection:-

//  key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var kc = e.keyCode || e.which;
keys[kc] = e.type == ‘keydown’;
};

Now we have to move the position of Mario on arrow key press. Below code will take care of that. 

Technically we need to change the CSS positioning of the image.

//  character movement update
var moveCharacter = function(dx, dy){
character.x += (dx||0) * character.speedMultiplier;
character.y += (dy||0) * character.speedMultiplier;
character.element.style.left = character.x + ‘px’;
character.element.style.top = character.y + ‘px’;
};

Simultaneously, we must program logic to cause Mario to change course in response to the left or right arrow keys being tapped. Additionally, we must ensure that when the user pushes the up arrow key, Mario jumps up to 50 locations.

//  character control
var detectCharacterMovement = function(){
if ( keys[keys.LEFT] ) {
document.getElementById(“idfirstView1–character”).style.backgroundImage= “url(‘<left Mario Image here>);
moveCharacter(-3, 0);
}
if ( keys[keys.RIGHT] ) {
document.getElementById(“idfirstView1–character”).style.backgroundImage= “url(‘<Right Mario Image here>);
moveCharacter(3, 0);
}
if ( keys[keys.UP] ) {
moveCharacter(0, -50);
setTimeout(function(){
moveCharacter(0, 50);
}, 100);
};
//  update current position on screen
moveCharacter();
// / game loop
setInterval(function(){
detectCharacterMovement();
}, 1000/24);
}

Mario is now reacting to important press events sent by users. The only thing left to do is bring our enemy character to life. A hero would not be a hero without a villain, after all.

  1. The Opponent Character:

We will use the custom canvas control to draw the enemy character shown below.

If you carefully examine the image above from bottom to top, you will notice that there are a lot of straight lines, a curved head, some black and white circles (around the eyes), and a red face hue. That will be resolved by the code below.

//Begin of drawing the enemy character
var canvas= $(‘canvas’);
var flag=”left”;
/* if (canvas) {*/
var ctx = canvas[1].getContext(‘2d’);
ctx.beginPath();
ctx.moveTo(83, 116);
ctx.lineTo(83, 102);
ctx.bezierCurveTo(83, 94, 89, 88, 97, 88);
ctx.bezierCurveTo(105, 88, 111, 94, 111, 102);
ctx.lineTo(111, 116);
ctx.lineTo(106.333, 111.333);
ctx.lineTo(101.666, 116);
ctx.lineTo(97, 111.333);
ctx.lineTo(92.333, 116);
ctx.lineTo(87.666, 111.333);
ctx.lineTo(83, 116);
ctx.fillStyle = ‘red’;
ctx.fill();

Let’s add some life to our adversary’s eyes as a final task. We intend to frighten Mario by haphazardly moving his eyes. The code that follows will see to it.

//moveEyes();
window.setInterval(function(){ moveEyes() }, 1000);
function moveEyes(){
if(flag==”right”){
ctx.fillStyle = ‘white’;
ctx.beginPath();
ctx.moveTo(91, 96);
ctx.bezierCurveTo(88, 96, 87, 99, 87, 101);
ctx.bezierCurveTo(87, 103, 88, 106, 91, 106);
ctx.bezierCurveTo(94, 106, 95, 103, 95, 101);
ctx.bezierCurveTo(95, 99, 94, 96, 91, 96);
ctx.moveTo(103, 96);
ctx.bezierCurveTo(100, 96, 99, 99, 99, 101);
ctx.bezierCurveTo(99, 103, 100, 106, 103, 106);
ctx.bezierCurveTo(106, 106, 107, 103, 107, 101);
ctx.bezierCurveTo(107, 99, 106, 96, 103, 96);
ctx.fill();
ctx.fillStyle = ‘black’;
ctx.beginPath();
ctx.arc(101, 102, 2, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.arc(89, 102, 2, 0, Math.PI * 2, true);
//ctx.arc(93, 102, 2, 0, Math.PI * 2, true);
ctx.fill();
flag=”left”;
}else if(flag==”left”){
ctx.fillStyle = ‘white’;
ctx.beginPath();
ctx.moveTo(91, 96);
ctx.bezierCurveTo(88, 96, 87, 99, 87, 101);
ctx.bezierCurveTo(87, 103, 88, 106, 91, 106);
ctx.bezierCurveTo(94, 106, 95, 103, 95, 101);
ctx.bezierCurveTo(95, 99, 94, 96, 91, 96);
ctx.moveTo(103, 96);
ctx.bezierCurveTo(100, 96, 99, 99, 99, 101);
ctx.bezierCurveTo(99, 103, 100, 106, 103, 106);
ctx.bezierCurveTo(106, 106, 107, 103, 107, 101);
ctx.bezierCurveTo(107, 99, 106, 96, 103, 96);
ctx.fill();
ctx.fillStyle = ‘black’;
ctx.beginPath();
ctx.arc(105, 102, 2, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
//ctx.arc(89, 102, 2, 0, Math.PI * 2, true);
ctx.arc(93, 102, 2, 0, Math.PI * 2, true);
ctx.fill();
flag=”right”;
}
}

That’s it for now, guys. We can save the game even though it isn’t finished for use in future projects. You can expand on these suggestions. I will advise against trying this just yet if you are not experienced with SAPUI5. Understand the fundamentals of SAPUI5 and JS. Learn the fundamentals of creating apps. then return to this tutorial for the game. Then, you’ll be able to appreciate it more. Experienced or expert SAPUI5 developers who are proficient in canvas, css, js, custom control, functions, and events are the target audience for this tutorial.

I hope this essay is enjoyable for you. You may definitely find solutions to your challenging requirements by consulting this article when working on projects.

Remarks?


you may be interested in this blog here:-

Just a key and two clicks for ALV consistency check

Making Your First Salesforce App exchange: A Complete Strategy

  • Related Posts

    Advanced SAPUI5-16: Google Maps JavaScript API Integration with SAPUI5 Application

    In any field of technology, newcomers frequently want examples of actual projects. To those who are interested, I would advise them to choose whatever scenario they can imagine, and it…

    SAPUI5 – Advanced – 15 – Stylish and Flexible Login Page Design in SAPUI5

    The majority of our SAP clients deploy their customized SAPUI5 apps onto Fiori Launchpad; nevertheless, Fiori does not support the creation of an app’s own login page. However, just as…

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    You Missed

    SAPUI5 – 11 Advance – Enjoyment with Super Mario in SAPUI5

    • By Varad
    • February 4, 2025
    • 14 views
    SAPUI5 – 11 Advance – Enjoyment with Super Mario in SAPUI5

    Advanced SAPUI5-16: Google Maps JavaScript API Integration with SAPUI5 Application

    • By Varad
    • February 3, 2025
    • 32 views
    Advanced SAPUI5-16: Google Maps JavaScript API Integration with SAPUI5 Application

    SAPUI5 – Advanced – 15 – Stylish and Flexible Login Page Design in SAPUI5

    • By Varad
    • February 2, 2025
    • 32 views
    SAPUI5 – Advanced – 15 – Stylish and Flexible Login Page Design in SAPUI5

    How to Open Fiori App Directly with Pre-Filled Data from Backend in Advance SAPUI5 – 17?

    • By Varad
    • February 1, 2025
    • 38 views
    How to Open Fiori App Directly with Pre-Filled Data from Backend in Advance SAPUI5 – 17?

    SAPUI5 Responsive Table Data Export to CSV File (Advance SAPUI5 Part-27)

    • By Varad
    • January 31, 2025
    • 49 views
    SAPUI5 Responsive Table Data Export to CSV File (Advance SAPUI5 Part-27)

    Advanced SAPUI5 – 21: Custom Button Control with Drag and Drop

    • By Varad
    • January 30, 2025
    • 50 views
    Advanced SAPUI5 – 21: Custom Button Control with Drag and Drop