I am in the process of developing a web game that will showcase 3 images on the screen, and the player must select the image that corresponds to the displayed word. I have successfully created a JavaScript array containing the images and words retrieved from a database, and I have successfully displayed 3 random images from the array in separate divs on the screen.
However, I am currently facing difficulties in displaying the word simultaneously with the 3 images, which corresponds to one of the randomly displayed images. Below is my current code:
<script>
var items = [
<?php
$con = mysql_connect("localhost","*****","******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("learning_game", $con);
$result = mysql_query("SELECT * FROM data");
$first = true;
while ($row = mysql_fetch_array($result)) {
if (!$first) {
echo ",";
}
$first = false;
echo "{name:'" . $row['word'] . "',image:'" . $row['image'] ."'}";
}
mysql_close($con);
?>
];
for (var i = 0; i < items.length; i++) {
}
document.write("<br /> <br /> <br />");
console.log(items);
top.items = items;
var images = new Array();
var list = document.getElementsByTagName('div')[0];
for(i = 0; i < 3; i++) {
// Choose a random item and remove it from the array
var item = items.splice(Math.floor(Math.random() * items.length), 1)[0];
// Create the image element and set its src attribute
images[i] = document.createElement('img');
images[i].src = item.image;
// Add it to your container element
}
document.getElementById("one").appendChild(images[0]);
document.getElementById("two").appendChild(images[1]);
document.getElementById("three").appendChild(images[2]);
</script>
I aim to have a total of 4 divs - one div per image and the last div for the word corresponding to one of the images. The JavaScript Array content is as follows:
var items = [
{name:'Coch',image:'upload/coch.png'},
{name:'Glas',image:'upload/glas.png'},
{name:'Melyn',image:'upload/melyn.png'},{name:'Ci',image:'upload/dog.jpg'},
{name:'Cath',image:'upload/cath.jpg'},{name:'Gwyrdd',image:'upload/gwyrdd.png'},
{name:'Un',image:'upload/un.jpg'},{name:'Dau',image:'upload/dau.jpg'},
{name:'Tri',image:'upload/tri.jpg'},{name:'Bochdew',image:'upload/bochdew.jpg'},
{name:'Piws',image:'upload/piws.png'}];
'Name' signifies the word, and 'image' provides the link to the image in the filesystem.
I would greatly appreciate any assistance. Thank you in anticipation.