# View Single Post

1. ## Re: D&D Battle simulator

Good work!

And here I was patting myself on the back for writing amateur (literally halfway through my first course in the R language), unfinished code to simulate how many attack rolls it takes to kill a single combination of hit points and AC. The saddest part of this is that I already did the "hard" work, and now I'm stuck trying to get averages and plots from my probability table (i.e. Number of Attacks Needed vs. Probability. That's the "atkprobtable" near the bottom). I think the table might be interpreting its contents as a string rather than integers/floats. Or something like that. Once I can get this table working, it won't take long to start simulating 1v1 slugfests, adding more features (pretty graphs, more than 2 combatants, vulnerability/resistance, chance to win a slugfest, etc), and applying data analytics to it.

EDIT: Whoops. Turned out I just needed to mapply() the as.double function to the table. I feel really dumb right now.

Spoiler: R Code
#Skill Roll
#d20roll
p.d6 <- rep(1/6,6)
d6 <- 1:6

dieroll<-function(x,n){

sample(d6, size=1, prob=p.d6, replace=T)
}
mean(result)
sd(result)
###
#Try to make a die-roll function

dieroll<-function(x,n){
p.die <- rep(1/x,x)
die <- 1:x
return(sample(die, size=n, prob=p.die, replace=T))
}
###Modified d20
d20<-function(x=0){
return(dieroll(20,1)+x)
}
###d12, d10, d8, d6, d4, d2
d12<-function(x=0){
return(dieroll(12,1)+x)
}
d10<-function(x=0){
return(dieroll(10,1)+x)
}
d8<-function(x=0){
return(dieroll(8,1)+x)
}
d6<-function(x=0){
return(dieroll(6,1)+x)
}
d4<-function(x=0){
return(dieroll(4,1)+x)
}
###

simatks<-function(Atk_bonus, AC, Max_HP){

hitdmg<-function(X){
return(d8(0))
}
critdmg<-function(x){
return(d8(0)+d8(0))

}

crit_counter=0
hit_counter=0
miss_counter=0
atk_counter=0
dmgcnt=0

HP = Max_HP
while(HP>0){
Atk_roll= d20(Atk_bonus)
hitdmg1=hitdmg(0)
critdmg1=critdmg(0)
Hitstring="Error"

if (Atk_roll-Atk_bonus==20){
HP = HP - critdmg1
dmgcnt = dmgcnt + critdmg1
crit_counter=crit_counter+1
atk_counter=atk_counter+1
Hitstring="Crit"
}
else if (Atk_roll >= AC){

HP = HP - hitdmg1
hit_counter=hit_counter+1
atk_counter=atk_counter+1
dmgcnt = dmgcnt + hitdmg1
Hitstring="Hit"
}
else if (Atk_roll < AC){
miss_counter=miss_counter+1
atk_counter=atk_counter+1
Hitstring="Missed"
}
#print(cat("attack #",atk_counter, Hitstring, "and", HP, " hit points remain||"))
}
return(atk_counter)
}

countatks=mapply(simatks, rep(0,1000), MoreArgs=list(AC=10, Max_HP=20))

counttable<-table(countatks)
atkprobtable=data.frame(counttable/sum(counttable))
names(atkprobtable)=c("Atks", "Prob")
atkprobtable=mapply(as.double,atkprobtable)

plot(atkprobtable, type="b")

It's inspiring to see someone like OP actually managing to get work done. Keep it up.  Reply With Quote