Колесо фортуны скрипт php

Колесо фортуны скрипт php

Most of the current turntable lottery program application site is based on a lot of flash, but this paper will use the example of jQuery and PHP to implement turntable sweepstakes program, for ease of understanding, the authors explain in two parts, the first part of this article explains, focuses on using jQuery to achieve effect rotation of the turntable. The second part focuses on the use of PHP code behind the control dial lottery draw the chances and ultimately, will have to explain in the next article.

Ready to work

First of all to prepare material, draw two pictures to use interface, disk images and pictures pointer, practical applications can be made of different disc images according to different needs.

He went on to create html page, we add the following code examples in the body:

 
class="demo">
id="disk">
id="start">src="start.png" id="startbtn">

We #disk to place the disc background image in css control, with #start to place the pointer pictures start.png.

We then use CSS to control the position of the pointer and the disk, the code is as follows:

 
.demowidth:417px; height:417px; position:relative; margin:50px auto>
#diskwidth:417px; height:417px; background:url(disk.jpg) no-repeat>
#startwidth:163px; height:320px; position:absolute; top:46px; left:130px;>
#start imgcursor:pointer>

jQuery

To get a pointer turn up, without the aid of flash if so, we can useHtml5 canvas rotate the realization of picturesBut need to consider browser compatibility, and can achieve a jQuery plug-picture (any html element) rotates and is compatible with all major browsers, it is jQueryRotate.js.

Читайте также:  Hashmap in android java

Use jQueryRotate.js pictures can be rotated to any angle, can bind mouse events, you can set the rotation animation and callback callback function.

Use of course, is first loaded into the jquery library in the head andjQueryRotate.js, Then we use the following code can be achieved a rotation pointer.

 
$(function() <
$("#startbtn").rotate( <
bind: <
click:function()// bind the click click event
var a = Math.floor(Math.random() * 360); // generate random numbers
$(this).rotate( <
duration:3000,// rotation time interval (rotational speed)
angle: 0, // start angle
animateTo:3600+a, // rotation angle, circle + 10
easing: $.easing.easeOutSine, // Extended animations
callback: function()< //Callback
alert('Hit the jackpot! ');
>
>);
>
>
>);
>);

The above code implements: click stops rotating when the pointer «Start Draw» button, the pointer starts to rotate, the rotation angle is 3600 + a, i.e. ring 10 and then a rotation angle of randomly generated, when the rotation angle reaches 3600 + a degrees .

Note that, easing: Animation expansion we need to combine animation extensions can be achieved

PHP jQuery to complete the combination dial entry process, we only need to set the dial corresponding to the angle and awards, each award and the corresponding probability of winning in the php file, use probabilistic algorithms, so that the chance of winning the lottery results are in line with set in the background.

PHP

First, we corresponding angle and the chance of winning prizes according to the settings on the lottery disks, we constructed a multi-dimensional array in data.php in:

 
$prize_arr = array(
'0' => array('id'=>1,'min'=>1,'max'=>29,'prize'=>'First Prize''v'=>1),
'1' => array('id'=>2,'min'=>302,'max'=>328,'prize'=>'second prize','v'=>2),
'2' => array('id'=>3,'min'=>242,'max'=>268,'prize'=>'Third place''v'=>5),
'3' => array('id'=>4,'min'=>182,'max'=>208,'prize'=>'Fourth Prize''v'=>7),
'4' => array('id'=>5,'min'=>122,'max'=>148,'prize'=>'Fifth prize''v'=>10),
'5' => array('id'=>6,'min'=>62,'max'=>88,'prize'=>'Liu Dengjiang''v'=>25),
'6' => array('id'=>7,'min'=>array(32,92,152,212,272,332),
'max'=>array(58,118,178,238,298,358),'prize'=>'Seven prize''v'=>50)
);

Array $ prize_arr, id used to identify the different prizes, min denotes the minimum angle of each disc segment corresponding to the award, max denotes a maximum angle, a minimum angle as the corresponding prize: 0, the maximum angle of 30, where we set the value max 1, max value of 29, in order to avoid a pointer to the lottery awards two adjacent line. Since a plurality of disks are provided seven prize, so we set the angular range corresponding to each of the seven other awards in the array. prize awards represent the content, v represents the chance of winning, we will find that the sum of seven awards in the array v is 100, if v is 1, represents 1% chance of winning, and so on.

About probability of winning algorithm, Site articles:PHP + jQuery achieve flap lotteryHas introduced classical probabilistic algorithms, this code is used to directly.

 
function getRand($proArr) <
$result = '';

The total probability of the probability of accuracy // array
$proSum = array_sum($proArr);

// probability array cycle
foreach ($proArr as $key => $proCur) <
$randNum = mt_rand(1, $proSum);
if ($randNum $proCur) <
$result = $key;
break;
> else <
$proSum -= $proCur;
>
>
unset ($proArr);

return $result;
>

Function getRand () will be calculated based on the chance of qualifying id set in the array, we can then call getRand ().

 
foreach ($prize_arr as $key => $val) <
$arr[$val['id']] = $val['v'];
>

$rid = getRand($arr); // Get the id awards based on probability

$res = $prize_arr[$rid-1]; // in awards
$min = $res['min'];
$max = $res['max'];
if($res['id']==7)< // seven prize
$i = mt_rand(0,5);
$result['angle'] = mt_rand($min[$i],$max[$i]);
>else <
$result['angle'] = mt_rand($min,$max); // generates a random angle
>
$result['prize'] = $res['prize'];

echo json_encode($result);

Code, we call the getRand (), awards by the probability calculation obtained, and then according to the angle range awards configured to generate between the minimum angle and a maximum angle of an angle value and construct an array, comprising the angle angle and awards Prize, The final output in json format.

jQuery

On the basis of the above, we were on the front-end jQuery code transformation, after clicking «Start Draw» button, a ajax request to send back data.php, if the request was successful and award information return, turn the pointer, the pointer points to the final data.php position to return the value of the angle.

 
$(function() <
$("#startbtn").click(function() <
lottery();
>);
>);
function lottery() <
$.ajax( <
type: 'POST',
url: 'data.php',
dataType: 'json',
cache: false,
error: function() <
alert('error! ');
return false;
>,
success:function(json) <
$("#startbtn").unbind('click').css("cursor","default");
var a = json.angle; // angle
var p = json.prize; // Awards
$("#startbtn").rotate( <
duration:3000, // rotation time
angle: 0,
animateTo:1800+a, // rotation angle
easing: $.easing.easeOutSine,
callback: function() <
var con = confirm('Congratulations, you have the' + p +'\ N would come back again? ');
if(con) <
lottery();
>else <
return false;
>
>
>);
>
>);
>

We build custom function lottery (), we send a POST request to data.php in the lottery (), if successful return after winning information, call rotate the plug begins to rotate, the rotation angle is determined by the angle of the back-end return, here we use 1800 + a represents the angle of rotation, i.e., rotation pointer 6 turns + a degrees after the stop, then we call when you click lottery «lottery start» button (), then draw the dial is complete.

Источник

СКРИПТ КОЛЕСО ФОРТУНЫ PHP

Скрипт колесо фортуны на PHP может быть написан с использованием функций PHP, что существенно упрощает процесс разработки. При создании скрипта необходимо учитывать следующие особенности:

1. Генерация случайного значения для определения выигрышной комбинации. Для этого можно использовать функцию rand() в PHP, которая генерирует случайное число в заданном диапазоне.

2. Определение выигрышной комбинации и вывод соответствующего сообщения. Для этого можно использовать конструкцию if-else в PHP:

if($user_input == $winning_number)echo «Вы выиграли!»;
> else echo «Попробуйте ещё раз!»;
>

3. Взаимодействие со страницей HTML для вывода колеса фортуны и получения введенного пользователем числа. Для этого можно использовать форму HTML и метод POST:

4. Обработка данных, полученных из HTML-формы. Для этого необходимо использовать массив $_POST в PHP:

5. Дополнительные функции и возможности для улучшения скрипта. Например, можно добавить возможность задавать количество попыток, после которого игра заканчивается, или выводить сообщения на русском языке.

Делаем колесо фортуны на HTML, CSS, JS // Колесо фортуны на JavaScript

Колесо Фортуны — попробуйте бесплатно на WordPress

Создаем Вращающееся Колесо используя HTML CSS и JavaScript

✅МАЙНИЛ НА ТЕЛЕФОНЕ 2 МЕСЯЦА. 💸ВЫВОЖУ ДЕНЬГИ НА QIWI КОШЕЛЁК. Verus coin

Колесо Фортуны — плагин для WordPress и виджет для любых других сайтов

Виджет для повышения конверсии «Колесо Фортуны» — Промо Видео 2022

TUTORIAL Как применить рандом в JS / РУЛЕТКА

Делаю персов с помощью рулетки:∆

создаю пару с помощью колеса фортуны/гача тренд/ by Alisa Milk

Источник

Инструкция

Установка скрипта возможна на все самописные сайты и на сайты с CMS (а также конструкторы), у которых есть доступ к исходному коду сайта. Потребуется поддержка PHP, функции отправки писем с сервера и JQuery выше 3.0.0. В некоторых случаях может потребоваться исправление Z-index и других стилевых ошибок. Не настаиваем, но рекомендуем заказывать пакеты с установкой виджета для сайтов на: Битрикс, Tilda, Joomla и OpenCart.

2. Установка

Распаковываем файлы скрипта в корень сайта:

В wheel.js меняем development на false, и меняем production на прямую ссылку к файлу скрипта (*.php):

В индекс файле сайта добавляем jquery (если нет), и в body добавляем скрипт:

3. Настройки

Настройки стилей производятся в файле index.php. В нем же находятся настройки секторов, их вероятностей, текстов и другие настройки.

4. Интеграции и отправка лидов

Отправка лидов возможна: на почту, в Битрикс, в Telegram, на WhatsApp. Для того чтобы настроить отправку на почту или в Битрикс, нужно активировать соответствующие настройки в скрипте (true и false), для Битрикса все настройки закомментированы в отдельном файле.

Чтобы настроить отправку лидов в Whatsapp, вам нужно добавить в контакты этот номер: +34 621 34 22 27. Далее отправьте ему следующее сообщение: «I allow callmebot to send me messages» (без кавычек). Дождитесь такого сообщения от бота: «API Activated for your phone number. Your APIKEY is ВАШ КЛЮЧ». На 125 строке в index.php (или по поиску слова «Whatsapp» в скрипте) находим часть скрипта, где меняется token и меняем его на полученный от бота. Готово.

Для того чтобы настроить отправку лидов в Telegram, нужно сначала написать боту @getMyID_tgbot и узнать свой ID, а затем вписать его в скрипт. Затем нужно написать боту @wheelnotifybot команду «start». Теперь заявки из виджета будут приходить в ваш Telegram.

Для того чтобы получать отчеты в Яндекс.Метрика о действиях с виджетом, не требуется взаимодействия со скриптом. Достаточно зарегистрировать аккаунт и перейти в инструкцию сервиса и настроить необходимые отчеты: инструкция по настройке Яндекс.Метрика.

ИП Лукин, ОГРН 322508100540525

Источник

Оцените статью