randomly mapping divs

后端 未结 4 1161
闹比i
闹比i 2021-02-19 21:11

I am creating a new \"whack-a-mole\" style game where the children have to hit the correct numbers in accordance to the question. So far it is going really well, I have a timer,

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 21:45

    Just use a random number which is based on the width of your board and then modulo with the height...

    You get a cell which is where you can put the mole.

    For the positions the x and y should never change as you have 9 spots lets say where the mole could pop up.

    x x x
    x x x 
    x x x
    

    Each cell would be sized based on % rather then pixels and would allow re sizing the screen

    1%3 = 1 (x) 3%3 = 0 (y)

    Then no overlap is possible.

    Once the mole is positioned it can be show or hidden or moved etc based on some extended logic if required.

    If want to keep things your way and you just need a quick re-position algorithm... just set the NE to the SW if the X + width >= x of the character you want to check by setting the x = y+height of the item which overlaps. You could also enforce that logic in the drawing routine by caching the last x and ensuring the random number was not < last + width of the item.

    newY = randomFromTo(minY, maxY); newX = randomFromTo(minX, maxX); if(newX > lastX + characterWidth){ /*needful*/}

    There could still however be overlap...

    If you wanted to totally eliminate it you would need to keep track of state such as where each x was and then iterate that list to find a new position or position them first and then all them to move about randomly without intersecting which would would be able to control with just padding from that point.

    Overall I think it would be easier to just keep X starting at 0 and then and then increment until you are at a X + character width > greater then the width of the board. Then just increase Y by character height and Set X = 0 or character width or some other offset.

    newX = 0; newX += characterWidth; if(newX + chracterWidth > boardWidth) newX=0; newY+= characterHeight;

    That results in no overlap and having nothing to iterate or keep track of additional to what you do now, the only downside is the pattern of the displayed characters being 'checker board style' or right next to each other (with possible random spacing in between horizontal and vertical placement e.g. you could adjust the padding randomly if you wanted too)

    It's the whole random thing in the first place that adds the complexity.

    AND I updated your fiddle to prove I eliminated the random and stopped the overlap :)

    http://jsfiddle.net/pUwKb/51/

提交回复
热议问题