DndDice/R/disadvantage_advantage.R
2019-03-18 20:56:07 -07:00

102 lines
2.4 KiB
R

#'
#' Disadvantage
#'
#' Disadvantage a die roll, which means that when both die are rolled, the result
#' is the lower number.
#'
#' @param x A die to roll.
#' @param y A die to roll. If not specified, then x is disadvantaged against itself.
#' @return A die representing the minimum of both die
#' @examples
#' disadvantage(d20,d20)
#'
#' @export
disadvantage <- function(x, y=NULL){
if(is.null(y)){
y = x
}
minX = min(x$numbers)
minY = min(y$numbers)
maxX = max(x$numbers)
maxY = max(y$numbers)
range_z_min = pmin(minX, minY)
range_z_max = pmin(maxX, maxY)
z_numbers = c()
probabilities = c()
for(num in range_z_min:range_z_max){
prob_x_eq_num = getProbabilitiy(x, num)
prob_y_eq_num = getProbabilitiy(y, num)
y_geq_nums = y$numbers[y$numbers >= num] # >= not a mistake
x_ge_nums = x$numbers[x$numbers > num]
prob_y_geq_nums = sum(getProbabilitiy(y, y_geq_nums))
prob_x_ge_nums = sum(getProbabilitiy(x, x_ge_nums))
prob_num = prob_x_eq_num*prob_y_geq_nums + prob_x_ge_nums*prob_y_eq_num
if(prob_num > 0){
z_numbers = c(z_numbers, num)
probabilities = c(probabilities, prob_num)
}
}
z = makeDie(z_numbers, probabilities)
return(z)
}
#'
#' Advantage
#'
#' Advantage a die roll, which means that when both die are rolled, the result
#' is the higher number.
#'
#' @param x A die to roll.
#' @param y A die to roll. If not specified, then x is advantaged against itself.
#' @return A die representing the maximum of both die
#' @examples
#' advantage(d20,d20)
#'
#' @export
advantage <- function(x, y=NULL){
if(is.null(y)){
y = x
}
minX = min(x$numbers)
minY = min(y$numbers)
maxX = max(x$numbers)
maxY = max(y$numbers)
range_z_min = pmax(minX, minY)
range_z_max = pmax(maxX, maxY)
z_numbers = c()
probabilities = c()
for(num in range_z_min:range_z_max){
prob_x_eq_num = getProbabilitiy(x, num)
prob_y_eq_num = getProbabilitiy(y, num)
y_leq_nums = y$numbers[y$numbers <= num] # <= not a mistake
x_le_nums = x$numbers[x$numbers < num]
prob_y_leq_nums = sum(getProbabilitiy(y, y_leq_nums))
prob_x_le_nums = sum(getProbabilitiy(x, x_le_nums))
prob_num = prob_x_eq_num*prob_y_leq_nums + prob_x_le_nums*prob_y_eq_num
if(prob_num > 0){
z_numbers = c(z_numbers, num)
probabilities = c(probabilities, prob_num)
}
}
z = makeDie(z_numbers, probabilities)
return(z)
}