0

I am trying to make a hangman game where a 'for' loop scrolls through different images but I can't get the previous image to be replaced by the next one, this was originally meant to be drawn through vectors but I went another way, any suggestions, below is the code:

<?php
    $dude = [
        '<img id="hung"src="images/hangman00.png"/>',
        '<img id="hung"src="images/hangman01.png"/>',
        '<img id="hung"src="images/hangman02.png"/>',
        '<img id="hung"src="images/hangman03.png"/>',
        '<img id="hung"src="images/hangman04.png"/>',
        '<img id="hung"src="images/hangman05.png"/>',
    ];
    
    function drawdude(){
        global $dude;
    
    
    for ($i=0; $i <= $_SESSION['numwrong']; $i++) {
        echo $dude[$i];
    }
        echo '</img>';
    }
?>
Yash
  • 3
  • 3
  • You are just printing one image after the other. If you want to replace it, you need to do some client side DOM manipulation with JavaScript. With PHP it is not possible to change data that already has been sent. If you are willing to use CSS instead os JS this: [Hide Element after 5s](https://stackoverflow.com/questions/21993661/css-auto-hide-elements-after-5-seconds) could be an option. – DreiDe Aug 03 '20 at 23:46

1 Answers1

0

The function should not use for loop. It will print all the conditions that match the criteria. You need a condition to show one image. Here is the code

<?php
    // Just for the sake of calling
    $_SESSION['numwrong'] = 2;

    $dude = [
        '<img id="hung"src="images/hangman00.png"/>',
        '<img id="hung"src="images/hangman01.png"/>',
        '<img id="hung"src="images/hangman02.png"/>',
        '<img id="hung"src="images/hangman03.png"/>',
        '<img id="hung"src="images/hangman04.png"/>',
        '<img id="hung"src="images/hangman05.png"/>',
    ];
    
    function drawdude(){
        global $dude;

        if(isset($_SESSION['numwrong']) && $_SESSION['numwrong'] <= 5){
            echo $dude[$_SESSION['numwrong']];
        } else{
            echo '</img>';
        }  
    }

    // Call the function
    drawdude();
?>
Chilarai
  • 1,842
  • 2
  • 15
  • 33