Top HTML5 Games you can play on Mobile
Game development has evolved from what it used to be, where it could only run on dedicated gaming devices or mobile. Now, you can play on almost any phone or tablet with minimal specifications, thanks to HTML5.
These are video games built using the Hypertext Markup Language (HTML). It also combines the elements of JavaScript and CSS3, resulting in elementary yet engaging games. It is designed to be played without any additional plugins or app installations.
Overall, HTML5 games range from simple puzzle games like Solitaire, confidence builder, and picture shifters to complex, HD graphics games like Olympia Rising and PixelRace. These games are becoming more popular, playing a significant role in the growth of web-based gaming.
In the next section, we shall discuss some of the most popular HML5 games you can try on your mobile phone.
Slotomania
Slots are often the most popular games you’d find, whether online or offline. That’s because it is so easy to play and does not require any skill. Instead, it’s all about luck. Most times, accessing quality slots requires downloading the casino app or using devices with high specs to keep up with the graphics demand.
However, the HML5 version, like Slotomania, is quite the opposite. It is an all-in-one app that features virtual slot machines with different mechanics, themes, and gameplay. That way, you do not have to use multiple apps or access other casinos to find your favorite slots. It is available for iOS, Android, and Windows users, making it easily accessible.
The gameplay is the same; spin the reels to win coins and other rewards. As you win, you can unlock other slot games. New levels make the game very exciting. Another interesting part is the social feature that allows users to connect with other players, compete in tournaments, and interact.
While Slotomania focuses only on slots, other HTML5 variants cover other casino games. Roulette Royale, Blackjack 21, Big Fish Casino, and Governor of Poker are popular casino-themed HTML5 games. They support an in-game currency and real money mode. If you like this, see the best blackjack apps for real money on The Sports Geek. There is a lot of info about the latest real money casino games you can enjoy.
2048
2048 is a straightforward 4 x 4 grid puzzle game that can keep you glued to your phone for the house. The objective is simple, move the photo slides across the grid until you end up with «2048» on the screen.
The game wouldn’t be so much fun if it were this simple. In typical gameplay, you get two tiles, usually numbered between 2 and 4. You can swipe the tiles in one of four directions using the arrow keys or swipe gestures on your device. After each move, a new tile will appear on the empty spot left by the moved tile.
For every move, the tile goes to the edge. So, when you slide a number to the right, it moves to the farthest end of the grid. A tricky art to note is that two tiles of the same number will add up when collapsing. So, if you move a tile numbered 2 to collide with another number 2, it becomes a single tile with the number 4.
The game continues until there are no possible moves you can make. While the game aims to form «2048» using the tiles, you can also achieve higher numbers and win more points. You can also check out JS13kGames for some similar grid puzzle games.
Angry Bird
Arguably one of the most popular HTML5 video game franchises created by Rovio Entertainment. Since its release in December 2009, the game has reached millions of downloads across different devices.
It is a physics-based puzzle game where you can apply your knowledge of force and projectile using a fling. Using the fewest birds possible, the idea is to use the angry birds as flings to eliminate structures occupied by green pigs. The birds have different characteristics and abilities that cause different levels of damage. Similarly, as the game progresses to higher levels, the pig structures become more difficult to destroy, requiring more birds or birds with specific characteristics.
Some birds can explode while others dive. Players must devise different shooting strategies and timing to get the maximum effect per fling. As the game progresses, the layout also changes, making the game very appealing and fun to play.
Fruit Ninja
Fruit Ninja is another popular HTML5 game developed in 2010 by Halfbrick Studios. The keywords that define the gameplay are «Ninja» and «fruits.» Each player takes the place of a Ninja armed with a sharp sword with the simple objective of slicing as many fruits as possible. The player earns a point for each successful slice, and when multiple fruits are sliced in quick succession, you get combos.
However, while trying to be fast and earn the combo points, you must be careful of the bombs occasionally appearing during the game. Each time you slice a bomb, you lose a life or some points. The same goes for every fruit you miss. Therefore, the game requires a combination of speed, precision, and attention to detail.
Overall, the game has a colorful display with fantastic sounds, especially with each successful slice or combo point earned. Power-up modes are also achieved by slicing unique fruits in the game, like bananas.
Final Thoughts
One of the major selling points of HTML5 games is their simplicity. Players do not need additional plugins like Flash Player or huge system specs. Instead, you can play directly from a web browser.
HTML5 games come in different variants like puzzle, shooter, multilayer, and strategy games. Hey integrates the elements of touch controls, audio, and animation to create an interactive game that is fun and easy to play. It also supports cross-platform compatibility, is often lightweight, and loads fast, making them very popular.
Портируем html5 игру на Android
Это продолжение моей прошлой статьи «Создаем html5 мини-бродилку на CraftyJS». Я подумал, сейчас так много возможностей относительно просто портировать любое html5 приложение на мобильную платформы, почему бы не попробовать?
Ниже, то что из этого вышло. Внимательно читаем вывод!
Что нам потребуется
- PhoneGap и окружение для работы с ним (инструкция по установке)
- Проект из предидущей статьи
- Крайне желательно наличие android телефона
Задача
Нужно портировать игру бродилку на android, сделать краткий вывод статистики и управление по средствам акселерометра.
Предварительная подготовка
С начала, выслушав критику к прошлой статье, я убрал из index.html множественные вызовы js файлов, оставив только главные библиотеки. Для этого я подключил библиотеку requirejs. Так же я сразу подключил phonegap.js и немного изменил верстку, вот как теперь все это выглядит:
Level: 1 Score: 0
body, html < margin:0; padding: 0; overflow:hidden; font-family:Arial; font-size:20px; background-color: #000; >#cr-stage < color:white; float:left; >#sidebar < top: 0; left: 0; width: 150px; height: 100px; position: absolute; color:white;>#sidebar div
var Settings = < width: 480, // ширина игрового поля height: 320, // высота poligon: 16, // размер полигона 16x16 level: 1, // текущий уровень flower_count: 0 // цветков на уровне >; var AllScripts = [ // objects 'js/objects/flower', 'js/objects/bush', 'js/objects/grass', 'js/objects/unit', 'js/objects/fourway_accel', 'js/objects/player', 'js/objects/fourway_ai', 'js/objects/monster', // scenes 'js/scenes/loading', 'js/scenes/main', 'js/scenes/win', 'js/scenes/lose' ]; require(AllScripts, function() < require.ready(function() < Crafty.init(Settings.width, Settings.height); // создаем игровое поле // подгружаем спрайт Crafty.sprite(Settings.poligon, "images/sprite.png", < grass1: [0,0], grass2: [1,0], grass3: [2,0], grass4: [3,0], flower: [0,1], bush1: [0,2], bush2: [1,2], player: [0,3], monster: [0,4] >); // запускаем первую сцену Crafty.scene("loading"); >); >);
Обратите внимание, что я так же изменил width и height в соответствие с разрешением мобильного телефона.
Акселерометр
Теперь давайте займемся управлением, для это изменим /js/objects/player.js заменив компонент Fourway на FourwayAccel, а так же вызов this.fourway(1) на this.fourway_accel(1). Дальше, нам нужно создать этот самый компонент, вот он:
Crafty.c("FourwayAccel", < _speed: 3, _touch_element: null, init: function() < this._movement= < x: 0, y: 0>; this.accels = <>; this.accels['left'] = false; this.accels['right'] = false; this.accels['top'] = false; this.accels['bottom'] = false; >, fourway_accel: function(speed) < var self = this; self._speed = speed; self.bind('Acceleration', function(acceleration) < if (acceleration.y < -2) this.start_or_stop_move('left'); if (acceleration.y >2) this.start_or_stop_move('right'); if (acceleration.x < -2) this.start_or_stop_move('top'); if (acceleration.x >2) this.start_or_stop_move('bottom'); >); self.bind("EnterFrame",function() < if (self.disableControls) return; if(self._movement.x !== 0) < self.x += self._movement.x; self.trigger('Moved', ); > if(self._movement.y !== 0) < self.y += self._movement.y; self.trigger('Moved', ); > >); return self; >, start_or_stop_move: function(move_type) < var move_speed = this.get_speed(move_type); if (this.accels[move_type]) < // stop move this._movement.x = Math.round((this._movement.x - move_speed.x)*1000)/1000; this._movement.y = Math.round((this._movement.y - move_speed.y)*1000)/1000; this.accels[move_type] = false; >else < // start move this.accels[move_type] = true; this._movement.x = Math.round((this._movement.x + move_speed.x)*1000)/1000; this._movement.y = Math.round((this._movement.y + move_speed.y)*1000)/1000; >this.trigger('NewDirection', this._movement); >, get_speed: function(key_id) < switch (key_id) < case 'top': return ; case 'left': return ; case 'right': return ; case 'bottom': return ; > > >);
После вызова метода fourway_accel, мы начинаем слушать событие «Acceleration», которое мы создадим чуть позже. Данное событие передает нам данные о наклоне (x,y,z). Нас тут интересует только x и y. Для упрощения, я проверяю достаточно большой уровень наклона, меньше -2 или больше 2.
Как только наклон достиг определенного градуса, вызывается функция «start_or_stop_move», которой передается направление наклона. Данная функция, в зависимости от скорости задает направление движения игрока, которое потом отрисовывается в событие «EnterFrame».
Дальше нам нужно создать сам генератор события «Acceleration», для этого добавим следующий код в /js/game.js:
var watchID = null; function stopWatch() < if (watchID) < navigator.accelerometer.clearWatch(watchID); watchID = null; >> function startWatch() < var options = < frequency: 200 >; watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); // с помощью этого куска, можно дебажить акселерометр в хроме // window.addEventListener('deviceorientation', function(event) < // Crafty.trigger("Acceleration", ) // >, false); > function onSuccess(acceleration) < Crafty.trigger("Acceleration", acceleration) >function onError()
Более подробно, о работе с акселерометром в phonegap, можно прочесть в документации.
Теперь, нам нужно вызвать startWatch() в сцене /js/scenes/main.js, а так же stopWatch() в сценах win.js и lose.js
Непосредственный запуск на телефоне
Итак, будем считать что вы уже сделал все, что описано в документации. Нужно немного подправить AndroidManifest.xml, добавив в секцию activity строчку: android:screenOrientation=«landscape». Это необходимо для того, что бы ориентация экрана всегда была альбомной.
Приводим AndroidrpgActivity.java к такому виду:
package com.phonegap.simplerpg; import android.os.Bundle; import android.view.WindowManager; import com.phonegap.*; public class AndroidrpgActivity extends DroidGap < /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.loadUrl("file:///android_asset/www/index.html"); >>
Думаю переменная FLAG_FULLSCREEN говорит сама за себя.
Результат и вывод
Вот, что у меня в итоге получилось (извините за качество):
Работает? О да! Доволен ли я? О нет!
Дело в том, что толи я криворукий, толи лыжи не едут, но приложение получилось крайне тормазнутым. Результат больше похож на пошаговую стратегию, чем на Action. И дело тут, я думаю, все же в лыжах, ответ наверное очевиден. PhoneGap — отличная библиотека для tumblr читалок и прочих новостных ридеров, но для игрушек лучше использовать нативный для android Java.