Skip to content

Instantly share code, notes, and snippets.

@willtownes
Last active August 29, 2015 14:05
Show Gist options
  • Save willtownes/a91aa1c3e63e824f2682 to your computer and use it in GitHub Desktop.
Save willtownes/a91aa1c3e63e824f2682 to your computer and use it in GitHub Desktop.
Paintball Simulation
# Simulation of a Paintball Game.
# The two players start off in random positions. They move one square each turn. Then they shoot at each other.
# Probability of who shoots first is 50/50.
# Probability of a hit is proportional to the distance between the players.
# Tracks history of last 3 moves.
# Prints out graphs to show the movement of the players and the shots.
# Game over when someone is hit.
shoot<-function(a.pos,b.pos){
# returns TRUE if the shot was a hit, otherwise FALSE
distance<-sqrt(sum(a.pos * b.pos))
shot.prob<-1/distance
u<-runif(1)
if(shot.prob > u){
return(TRUE)
}
else{
return(FALSE)
}
}
move<-function(pos){
# pos is a 2-vector showing the position. Returns the new position.
direction=c(0,0)
while(direction[1] == 0 && direction[2] == 0){
direction<-sample(c(-1,0,1),2,replace=TRUE)
}
if(pos[1]==1 && direction[1]== -1){
direction[1]= 1
} else if(pos[1]==10 && direction[1]==1){
direction[1]= -1
}
if(pos[2]==1 && direction[2]== -1){
direction[2] = 1
} else if(pos[2]==10 && direction[2] == 1){
direction[2] = -1
}
return(pos+direction)
}
plot.moves<-function(a,b,t){
plot(a,type='l',xlim=c(0,11),ylim=c(0,11),main=paste("Turn",t),xlab='',ylab='',col='red',lwd=2)
points(a[3,1],a[3,2],pch='A',cex=2,col='red')
lines(b,col='blue',lwd=2)
points(b[3,1],b[3,2],pch='B',cex=2,col='blue')
}
paintball<-function(player1="A",player2="B"){
players<-c(player1,player2)
run<-TRUE
t<-0
a<-matrix(NA,3,2)
b<-matrix(NA,3,2)
a[2,]<-a[3,]<-a[1,]<-sample(10,2)
b[2,]<-b[3,]<-b[1,]<-sample(10,2)
while(run){
# keep track of history
t<-t+1
a[c(1,2),]<-a[c(2,3),]
b[c(1,2),]<-b[c(2,3),]
# move players
a[3,]<-move(a[3,])
b[3,]<-move(b[3,])
plot.moves(a,b,t)
Sys.sleep(1)
# determine which shots are hits/misses
a.fire<-shoot(a[3,],b[3,])
b.fire<-shoot(a[3,],b[3,])
#establish who shoots first
first<-sample(players,1)
if(first==players[1]){
p1<-a; col1<-'red'; p2<-b; col2<-'blue'
p1.fire<-a.fire; p2.fire<-b.fire
} else{
p1<-b; col1<-'blue'; p2<-a; col2<-'red'
p1.fire<-b.fire; p2.fire<-a.fire
}
traj<-rbind(a[3,],b[3,])
if(p1.fire){ #case where first shot was a hit
lines(traj,lty=1,col=col1,lwd=2)
winner=first
run=FALSE
} else { #first shot was a miss
lines(traj,lty=2,col=col1,lwd=2)
Sys.sleep(1)
if(p2.fire){ #second shot was a hit
lines(traj,lty=1,col=col2,lwd=2)
winner=players[players!=first]
run=FALSE
} else { # second shot was a miss
lines(traj,lty=2,col=col2,lwd=2)
}
}
Sys.sleep(2)
}
print(paste("The Winner was:",winner))
}
paintball()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment