I'm trying to write a blackjack-code in R. Since I'm new to this language I'm facing some difficulties. I already wrote two different functions to distribute the first 2 cards to each player and count the total points for each one. Now I want to write a function that's based on the results of the second function to decide if a player has to take another card or not with some conditions. Here's the code:
bj_add_card <- function(hand) {
hand <- bj_simplified(hand)
m_hand <- matrix(unlist(hand), ncol = 3, byrow = TRUE)
sums <- m_hand[,3]
sum_players <- as.vector(as.numeric(sums[-1]))
sum_dealer <- as.numeric(tail(sums), 1)
add_card <- vector("list")
for (i in seq_along(sum_players)) {
if(sum_players[i] <= 11) {
add_card[i] <- sample(Spielkarten, 1)
}
else if(sum_players[i] >= 17) {
add_card[i] <- "stay"
}
else if(11 > sum_players[i] && sum_players[i] < 17) {
if(sum_players[i] == 12 && sum_dealer == 4 || 5 || 6) {
add_card[i] <- "stay"
}
else if(sum_players[i] == 12 && sum_dealer != 4 || 5 || 6) {
add_card[i] <- sample(Spielkarten, 1)
}
else if(sum_players[i] == 13 || 14 || 15 || 16 && sum_dealer ==
2||3||4||5||6||7||8||9||10) {
add_card[i] <- "stay"
}
else if(sum_players[i] == 13 || 14 || 15 || 16 && sum_dealer !=
2||3||4||5||6||7||8||9||10) {
add_card[i] <- sample(Spielkarten, 1)
}
}
}
return(add_card)
}
bj_add_card(6)
I really don't see the problem. Everytime I call this function the output is a list (as it should be) with different amount of arguments, but it does not always match the input number, although it should. Sometimes it gives me "NULL" as output without any reason. I think it's an overwriting problem but I cannot figure out where the problem is. Any ideas?