mercredi 9 août 2017

How to Avoid or Test Randomness in Functional Programming

I started to make a dungeon-game that creates randomly new dungeons.

Currently I write the function createRoom that returns a new room object based on the arguments. This function is called in createDungeon, but it receivs random parameters there.

function createRoom (width = 1, height = 1, topLeftCoordinate = {x: 0, y: 0}) {
  return {
    width,
    height,
    topLeftCoordinate
  }
}

function createDungeon (numberOfRooms, rooms = []) {
  if (numberOfRooms <= 0) {
    return rooms
  }
  const randomWidth = getRandomNumber(5, 10)
  const randomHeight = getRandomNumber(5, 10)
  const randomTopLeftCoordinate = {x: getRandomNumber(5, 10), y: getRandomNumber(5, 10)}
  return createDungeon (
    numberOfRooms - 1, 
    rooms.concat(Room.create(randomWidth, randomHeight, randomTopLeftCoordinate))
  )
}

I don't know if this is the right why, because I don't how to test createDungeon. I can only test if this function retuns an array and the length of the array.. Is this enough or is there a design pattern for the randomness?

Aucun commentaire:

Enregistrer un commentaire