Limiter un nombre de gain.

Fermé
ugo.scannapieco - Modifié le 28 oct. 2019 à 15:36
 ugo.scannapieco - 29 oct. 2019 à 08:47
Bonjour à tous,

Pour un projet de digital je dois réaliser le développement d'une roue de la fortune.
Jusqu'à la, j'ai trouvé de l'aide, ma roue fonctionne convenablement.. Cependant, j'aimerais donner un nombre limite à chaque gain.

Exemple : 10€ x 2 / 100€ x 3 / 1500€ x1 / ect...

Je n'ai aucune idée de quoi faire : créer une instruction "for" / utiliser "Math.max" / Travailler simplement par condition avec "if" et "else".

Je découvre le JS et même en étant plein de bonne volonté j'en ch**

Voici le code, HELP s'il vous plait :).
<html>
    <head>
        <title>HTML5 Canvas Winning Wheel</title>
        <link rel="stylesheet" href="main.css" type="text/css" />
        <script type="text/javascript" src="../../Winwheel.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
    </head>
    <body>
        <div align="center">
            <h1>Winwheel.js example wheel - one image per segment</h1>
            <br />
            <p>Here is an example of a wheel created using one image per segment, also includes code drawn text.</p>
            <br />
            <p>Choose a power setting then press the Spin button.</p>
            <br />
            <table cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td>
                        <div class="power_controls">
                            <br />
                            <br />
                            <table class="power" cellpadding="10" cellspacing="0">
                                <tr>
                                    <th align="center">Power</th>
                                </tr>
                                <tr>
                                    <td width="78" align="center" id="pw3" onClick="powerSelected(3);">High</td>
                                </tr>
                                <tr>
                                    <td align="center" id="pw2" onClick="powerSelected(2);">Med</td>
                                </tr>
                                <tr>
                                    <td align="center" id="pw1" onClick="powerSelected(1);">Low</td>
                                </tr>
                            </table>
                            <br />
                            <img id="spin_button" src="spin_off.png" alt="Spin" onClick="startSpin();" />
                            <br /><br />
                              <a href="#" onClick="resetWheel(); return false;">Play Again</a><br />     (reset)
                        </div>
                    </td>
                    <td width="1000" height="1000" class="the_wheel" align="center" valign="center">
                        <canvas id="canvas" width="1000" height="1000">
                            <p style="{color: white}" align="center">Sorry, your browser doesn't support canvas. Please try another.</p>
                        </canvas>
                    </td>
                </tr>
            </table>
        </div>
        <script>
            // Create new wheel object specifying the parameters at creation time.
            let theWheel = new Winwheel({
                'numSegments'       : 8,                 // Specify number of segments.
                'outerRadius'       : 200,               // Set outer radius so wheel fits inside the background.
                'drawText'          : true,              // Code drawn text can be used with segment images.
                'textFontSize'      : 16,
                'textOrientation'   : 'curved',
                'textAlignment'     : 'inner',
                'textMargin'        : 90,
                'textFontFamily'    : 'monospace',
                'textStrokeStyle'   : 'black',
                'textLineWidth'     : 3,
                'textFillStyle'     : 'white',
                'drawMode'          : 'segmentImage',    // Must be segmentImage to draw wheel using one image per segemnt.
                'segments'          :                    // Define segments including image and text.
                [
                   {'image' : 'CAM2.png', 'id' : '1a',  'text' : 'Jane'},
                   {'image' : 'CAM3.png', 'id' : '2a',  'text' : 'Tom'},
                   {'image' : 'CAM4.png', 'id' : '3a', 'text' : 'Mary'},
                   {'image' : 'CAM5.png', 'id' : '4a', 'text' : 'Alex'},
                   {'image' : 'CAM6.png', 'id' : '5a', 'text' : 'Sarah'},
                   {'image' : 'CAM7.png', 'id' : '6a', 'text' : 'Bruce'},
                   {'image' : 'CAM8.png', 'id' : '7a', 'text' : 'Rose'},
                   {'image' : 'CAM1.png', 'id' : '8a', 'text' : 'Steve'}
                ],
                'animation' :           // Specify the animation to use.
                {
                    'type'     : 'spinToStop',
                    'duration' : 5,     // Duration in seconds.
                    'spins'    : 8,     // Number of complete spins.
                    'callbackFinished' : alertPrize
                }
            });
   
   

            // Vars used by the code in this page to do power controls.
            let wheelPower    = 0;
            let wheelSpinning = false;

            // -------------------------------------------------------
            // Function to handle the onClick on the power buttons.
            // -------------------------------------------------------
            function powerSelected(powerLevel)
            {
                // Ensure that power can't be changed while wheel is spinning.
                if (wheelSpinning == false) {
                    // Reset all to grey incase this is not the first time the user has selected the power.
                    document.getElementById('pw1').className = "";
                    document.getElementById('pw2').className = "";
                    document.getElementById('pw3').className = "";

                    // Now light up all cells below-and-including the one selected by changing the class.
                    if (powerLevel >= 1) {
                        document.getElementById('pw1').className = "pw1";
                    }

                    if (powerLevel >= 2) {
                        document.getElementById('pw2').className = "pw2";
                    }

                    if (powerLevel >= 3) {
                        document.getElementById('pw3').className = "pw3";
                    }

                    // Set wheelPower var used when spin button is clicked.
                    wheelPower = powerLevel;

                    // Light up the spin button by changing it's source image and adding a clickable class to it.
                    document.getElementById('spin_button').src = "spin_on.png";
                    document.getElementById('spin_button').className = "clickable";
                }
            }

            // -------------------------------------------------------
            // Click handler for spin button.
            // -------------------------------------------------------
            function startSpin()
            {
                // Ensure that spinning can't be clicked again while already running.
                if (wheelSpinning == false) {
                    // Based on the power level selected adjust the number of spins for the wheel, the more times is has
                    // to rotate with the duration of the animation the quicker the wheel spins.
                    if (wheelPower == 1) {
                        theWheel.animation.spins = 3;
                    } else if (wheelPower == 2) {
                        theWheel.animation.spins = 8;
                    } else if (wheelPower == 3) {
                        theWheel.animation.spins = 15;
                    }

                    // Disable the spin button so can't click again while wheel is spinning.
                    document.getElementById('spin_button').src       = "spin_off.png";
                    document.getElementById('spin_button').className = "";

                    // Begin the spin animation by calling startAnimation on the wheel object.
                    theWheel.startAnimation();

                    // Set to true so that power can't be changed and spin button re-enabled during
                    // the current animation. The user will have to reset before spinning again.
                    wheelSpinning = true;
                }
            }

            // -------------------------------------------------------
            // Function for reset button.
            // -------------------------------------------------------
            function resetWheel()
            {
                theWheel.stopAnimation(false);  // Stop the animation, false as param so does not call callback function.
                theWheel.rotationAngle = 0;     // Re-set the wheel angle to 0 degrees.
                theWheel.draw();                // Call draw to render changes to the wheel.

                document.getElementById('pw1').className = "";  // Remove all colours from the power level indicators.
                document.getElementById('pw2').className = "";
                document.getElementById('pw3').className = "";

                wheelSpinning = false;          // Reset to false to power buttons and spin can be clicked again.
            }

            // -------------------------------------------------------
            // Called when the spin animation has finished by the callback feature of the wheel because I specified callback in the parameters.
            // note the indicated segment is passed in as a parmeter as 99% of the time you will want to know this to inform the user of their prize.
            // -------------------------------------------------------
            function alertPrize(indicatedSegment)
            {
                // Do basic alert of the segment text. You would probably want to do something more interesting with this information.
                alert(indicatedSegment.text + ' says Hi');
            }
        </script>
    </body>
</html>


EDIT : Ajout des balises de code.
Merci d'y penser à l'avenir...


Configuration: Windows / Chrome 77.0.3865.120

1 réponse

jordane45 Messages postés 38138 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 17 avril 2024 4 649
28 oct. 2019 à 15:52
Bonjour,

Que signifie, pour toi, la phrase
Cependant, j'aimerais donner un nombre limite à chaque gain.


Limiter.. à l'affichage ? où ça ?
Ou alors.. limiter le nombre de personnes pouvant toucher ces gains ?
Mais dans ce cas, où sauvegardes tu ces informations ?

Pour l'instant tu as juste copier/coller l'un des exemples fournis pour le script wheel.js ... mais je ne vois pas ce que tu y a modifié ou non...
Ni à quel endroit tu définis des gains ...

Merci d'être plus précis dans la rédaction de tes questions.

Et à l'avenir, merci d'utiliser les balises de code pour poster ton code sur le forum.


0
ugo.scannapieco
28 oct. 2019 à 16:06
Bonjour Jordane45,

Merci pour ta réponse.
Effectivement tu as raison j'ai sélectionné un code déjà pré fabriqué sur un site de dév. Je ne suis pas du tout callé en JS ce pour quoi je demande de l'aide.
Ce que j'ai modifié ne fonctionnait pas du tout aussi je m'en remet à vous pour trouver comment faire.

Si on parle en terme mathématique, on parlerait de pondération.
Je souhaite qu'il y ait qu'un seul gagnant pour le lot A / 4 gagnants pour le lot B / 30 gagnants pour le lot C / etc...
Ici la partie concernant les gains est celle ci :

[
                   {'image' : 'CAM2.png', 'id' : '1a',  'text' : '10€'},
                   {'image' : 'CAM3.png', 'id' : '2a',  'text' : '20€'},
                   {'image' : 'CAM4.png', 'id' : '3a', 'text' : '30€'},
                   {'image' : 'CAM5.png', 'id' : '4a', 'text' : '40€'},
                   {'image' : 'CAM6.png', 'id' : '5a', 'text' : '50€'},
                   {'image' : 'CAM7.png', 'id' : '6a', 'text' : '60€'},
                   {'image' : 'CAM8.png', 'id' : '7a', 'text' : '70€'},
                   {'image' : 'CAM1.png', 'id' : '8a', 'text' : '80€'}
                ],
                


J'espère avoir été assez clair !

Merci beaucoup pour votre aide.
0
jordane45 Messages postés 38138 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 17 avril 2024 4 649 > ugo.scannapieco
28 oct. 2019 à 16:11
Tu parles d'un seul gagnant....
Mais... comment gères tu le "multi joueurs" ?
As tu un lien avec un serveur ? une base de données ? quelque chose pour que tes données (qui ne sont actuellement que dans TON navigateur internet ) puisse êtres partagées sur le réseau (ou sur internet ) ?
0
ugo.scannapieco
28 oct. 2019 à 16:45
Concrétement Jordane45,

Lors d'une animation pour mon école je souhaite réaliser une roue de la fortune digitale.

La roue sera composée de 8 quartiers :

- 1 quartier mention gain repas
- 1 quartier mention panier garnis
- 1 quartier mention box bouteille de vin
- 1 coffret mention bouteille de vin
- 1 quartier mention coffret cadeau
- 1 quartier mention bon 20%
- 1 quartier mention ballon
- 1 quartier mention perdu

(tous les gains évoqués seront distribués en physique et ne sont en aucun cas lié à une Base de donnée).

Pour chacun de ces lots j'ai une quantité pré-définie à faire gagner :
- 1 quartier mention gain repas (x1)
- 1 quartier mention panier garnis (x3)
- 1 quartier mention box bouteille de vin (26)
- 1 coffret mention bouteille de vin (x30)
- 1 quartier mention coffret cadeau (x70)
- 1 quartier mention bon 20% (x170)
- 1 quartier mention ballon (x200)
- 1 quartier mention perdu (infini)

Chaque lancé est provoqué par le clic "d'un organisateur". On est sur de l'événement physique avec retranscription sur un vidéo projecteur de la roue qui tourne.

Je pensais rester sur du local pour éviter tout problème de réseau pendant l'événement cependant je crois bien savoir que mon école dispose d'un serveur privé sur lequel je peux héberger la page de la roue.

Concernant le code que je vous ai fournis, il faut effectivement y rapprocher le fichier winwheel.js, j'ai trouvé tout le package ici : https://github.com/zarocknz/javascript-winwheel

Merci encore,

A vous lire,

Ugo.
0
jordane45 Messages postés 38138 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 17 avril 2024 4 649
28 oct. 2019 à 20:53
Si ta "roue" n'est lancée que depuis un seul ordi, tu peux rester sur du "local".
Eventuellement, tu peux mémoriser les données dans des COOKIES ou via le LOCAL STORAGE ( ça fera toujours une petite protection au cas où le navigateur internet était fermé par inadvertance.. )
=> pour cette partie, je te laisserai regarder sur le net.... toutes les docs sont disponibles sans souci..

Revenons maintenant à ton code à proprement parlé...
Sur quel point bloques tu exactement ?
Le "click" sur un tronçon de la roue ?
L'algorithme à mettre en place ?
Décrémenter une variable ?
Autre chose ??

Et que se passe t'il lorsqu'un lot n'est plus disponible ? Son tronçon disparait ? ou alors il est remplacé par un perdu ?


En attendant.. tu peux t'inspirer de ça
<!Doctype html>
<html>
    <head>
      <meta charset="utf-8">
        <title>Wheel of fortune Wheel</title>
      <link rel="stylesheet" href="main.css" type="text/css" />
        <script type="text/javascript" src="Winwheel.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
  
    </head>
    <body>
     <div class="power_controls">
                            <img id="spin_button" src="spin_off.png" alt="Spin" onClick="startSpin();" />
                            <br /><br />
                              <a href="#" onClick="resetWheel(); return false;">Play Again</a><br />     (reset)
                        </div>
                        <div class="the_wheel">
        <canvas id='canvas' width='880' height='700'>
        
            Canvas not supported, use another browser.
        </canvas>
        <div id="resultats"></div>
        </div>
        <script>
        /**
        - 1 quartier mention gain repas (x1)
        - 1 quartier mention panier garnis (x3)
        - 1 quartier mention box bouteille de vin (26)
        - 1 coffret mention bouteille de vin (x30)
        - 1 quartier mention coffret cadeau (x70)
        - 1 quartier mention bon 20% (x170)
        - 1 quartier mention ballon (x200)
        - 1 quartier mention perdu (infini) 
        */
        var prices=[1,3,26,30,70,170,200,99999999999999];
        
        
        console.log(prices);
        
         // Vars used by the code in this page to do power controls.
            let wheelPower    = 0;
            let wheelSpinning = false;
            // Create new wheel object specifying the parameters at creation time.
            let theWheel = new Winwheel({
                'numSegments'       : 8,                 // Specify number of segments.
                'outerRadius'       : 200,               // Set outer radius so wheel fits inside the background.
                'drawText'          : true,              // Code drawn text can be used with segment images.
                'textFontSize'    : 24,         // Set default font size for the segments.
                'textOrientation' : 'vertical', // Make text vertial so goes down from the outside of wheel.
                'textAlignment'   : 'outer',
                'segments':                    // Define segments including image and text.
                [
                   {'fillStyle' : '#ee1c24', 'text' : '1'},
                   {'fillStyle' : '#3cb878', 'text' : '2'},
                   {'fillStyle' : '#f6989d', 'text' : '3'},
                   {'fillStyle' : '#00aef0', 'text' : '4'},
                   {'fillStyle' : '#f26522', 'text' : '5'},
                   {'fillStyle' : '#f26522', 'text' : '6'},
                   {'fillStyle' : '#f26522', 'text' : '7'},
                   {'fillStyle' : '#000000', 'text' : 'Perdu', 'textFontSize' : 16, 'textFillStyle' : '#ffffff'},
                ],
                'animation' :           // Specify the animation to use.
                {
                    'type'     : 'spinToStop',
                    'duration' : 5,     // Duration in seconds.
                    'spins'    : 8,     // Number of complete spins.
                    'callbackFinished' : alertPrize
                }
            });
   
   

            

            // -------------------------------------------------------
            // Function to handle the onClick on the power buttons.
            // -------------------------------------------------------
            function powerSelected(powerLevel)
            {
                // Ensure that power can't be changed while wheel is spinning.
                if (wheelSpinning == false) {
                    // Reset all to grey incase this is not the first time the user has selected the power.
                    document.getElementById('pw1').className = "";
                    document.getElementById('pw2').className = "";
                    document.getElementById('pw3').className = "";

                    // Now light up all cells below-and-including the one selected by changing the class.
                    if (powerLevel >= 1) {
                        document.getElementById('pw1').className = "pw1";
                    }

                    if (powerLevel >= 2) {
                        document.getElementById('pw2').className = "pw2";
                    }

                    if (powerLevel >= 3) {
                        document.getElementById('pw3').className = "pw3";
                    }

                    // Set wheelPower var used when spin button is clicked.
                    wheelPower = powerLevel;

                    // Light up the spin button by changing it's source image and adding a clickable class to it.
                    document.getElementById('spin_button').src = "spin_on.png";
                    document.getElementById('spin_button').className = "clickable";
                }
            }

            // -------------------------------------------------------
            // Click handler for spin button.
            // -------------------------------------------------------
            function startSpin()
            {
              wheelPower = 1;
                // Ensure that spinning can't be clicked again while already running.
                if (wheelSpinning == false) {
                     // Disable the spin button so can't click again while wheel is spinning.
                    document.getElementById('spin_button').src       = "spin_off.png";
                    document.getElementById('spin_button').className = "";

                    // Begin the spin animation by calling startAnimation on the wheel object.
                    theWheel.startAnimation();
                    // Set to true so that power can't be changed and spin button re-enabled during
                    // the current animation. The user will have to reset before spinning again.
                    wheelSpinning = true;
                }
            }

            // -------------------------------------------------------
            // Function for reset button.
            // -------------------------------------------------------
            function resetWheel()
            {
                theWheel.stopAnimation(false);  // Stop the animation, false as param so does not call callback function.
                theWheel.rotationAngle = 0;     // Re-set the wheel angle to 0 degrees.
                theWheel.draw();                // Call draw to render changes to the wheel.
                wheelSpinning = false;          // Reset to false to power buttons and spin can be clicked again.
            }

            // -------------------------------------------------------
            // Called when the spin animation has finished by the callback feature of the wheel because I specified callback in the parameters.
            // note the indicated segment is passed in as a parmeter as 99% of the time you will want to know this to inform the user of their prize.
            // -------------------------------------------------------
            function alertPrize(indicatedSegment)
            {
                // Do basic alert of the segment text. You would probably want to do something more interesting with this information.
                var resTirage = indicatedSegment.text;
                if(resTirage=="Perdu"){
                  resTirage=8;
                }
                let numPrice = parseInt(resTirage);
                let reste = prices[numPrice-1];
                var p = document.createElement("p");
                p.innerHTML = "Case  :" + numPrice + " - reste avant tirage: " + reste + " - reste après tirage: " + (reste -1);
                document.getElementById('resultats').appendChild(p);
                if(numPrice == 8){
                    alert("Désolé... vous avez perdu !");
                    resetWheel();
                }else{
                  if(reste > 0 ){
                    //on décrémente :
                    prices[numPrice-1] = reste -1;
                    alert('Vous avez gagné le lot N°'+numPrice );
                    console.log('prices',prices);
                    resetWheel();
                  }else{
                    alert('quantité dépassée...');
                    resetWheel();
                  }
                }
            }
        </script>
    </body>
</html>
0
ugo.scannapieco
29 oct. 2019 à 08:47
Merci 1000 fois Jordane !
La réponse est très claire, et surtout comme tu me l'indiquais, je souhaites comprendre le fonctionnement du code.

Je te souhaite une excellente journée,

Au top pour cette aide !

Bien à toi,

Ugo.
0