首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在表格的单元格中选择随机img,并使用jquery或javascript打印

在表格的单元格中选择随机img,并使用jquery或javascript打印
EN

Stack Overflow用户
提问于 2018-08-21 22:33:47
回答 1查看 79关注 0票数 1

问题:我必须在一个单元格内的任意(该元素的坐标将是随机生成的)图像上打印一个图像,而不覆盖现有内容。

限制:我不得不认为,在第二个时刻,我必须像国际象棋游戏一样移动这个打印的图像,而且我只能使用Javascript或jQuery。

这是画笔的链接:-> codepen

现在,通过这个函数,我设置了随机坐标,并且我知道一个单元格是否可以遍历。

代码语言:javascript
复制
function coordinate(){

    let rowCoord= map.length;
    let cellCoord = map[1].length;

    let coord = {
        row: Math.floor(Math.random() * rowCoord),
        cell: Math.floor(Math.random() * cellCoord)
    }

    return coord;  
};


function placeCharAndItem(){
    let coord= coordinate();

    // with this if you choose a walkable table to spawn, this is random generated
    if(map[coord.row][coord.cell] === 0){
        alert(map[coord.rowCoord][coord.cellCoord]);
        place(coord);
    }
    else{
        placeCharAndItem();
    }
};

这是我生成表的函数:

代码语言:javascript
复制
function mapGenerate(){
    var map=createMap(); //the function createMap generates a 2dArray full of 1 and 0.
        //loop the 2d array map and change the number with the appropriate img    
        for(var i = 0; i < map.length; i++) {
            var innerArrayLength = map[i].length;
            for(var j = 0; j<innerArrayLength; j++){
                if(map[i][j] === 0){
                    map[i][j]="<img class=\"walkable\" src=\"https://image.ibb.co/bGanFz/floor_Resized.png\">";
                }else{
                    map[i][j]="<img class=\"nonWalkable\" src=\"https://image.ibb.co/m9s1az/volcanoresize.png\">";
                }    
                ;
            }
        $("#tableGame").append("<tr><td>"+ map[i].join('') + "<td></tr>")
    }  
}

任何形式的帮助都是非常感谢的。

这就是我需要实现的结果,可能这个图像会比我说的更好:)。

你可以忽略红色方块和红线,它们只是为了突出显示字符在这个随机的img中,在td Result

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-22 07:03:53

我不能说我真的理解你的问题,但通过看你的笔,我写了这个函数,希望它能有所帮助:

代码语言:javascript
复制
function place(coord, char){
  var charImage = $("<img>").attr("src", char.image).addClass('char');
  var row = $($("#tableGame tr")[coord.row]);
  var cell = $($("td", row)[coord.cell]);
  cell.append(charImage);
}

您的地图没有按照您预期的方式构建,因为在单个表单元格中有许多图像。下面是如何在每个单元格中放置一个图像:

代码语言:javascript
复制
function mapGenerate(){
  ...
  $("#tableGame").append("<tr><td>"+ map[i].join('</td><td>') + "</td></tr>")
  ...
}

https://codepen.io/rafaelcastrocouto/pen/qMEVZz?editors=0010

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51951049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档