C# Which int is Closer to 21

153 views Asked by At

I'm working on a simple blackjack game in c#

For example I have int playerTotal and int dealerTotal I want to compare them for which is closest to 21 and which one is greater than 21.

How can I do that?

2

There are 2 answers

0
Selman Genç On BEST ANSWER

You can use Math.Abs method to find the absolute difference between those numbers and 21 then compare them:

int closest = Math.Abs(playerTotal - 21) <Math.Abs(dealerTotal - 21) 
             ? playerTotal
             : dealerTotal;

To find the greatest:

int greatest = playerTotal > 21 ? playerTotal : dealerTotal;
0
Lee Daniel Crocker On

Under proper blackjack rules, it is not sufficient to simply compare the hands. You have to do things in the proper order, which is:

  • If the dealer has an ace or ten showing, he peeks, and if he has a natural, he exposes it and the hand is over. All hands lose unless they too are naturals. If the dealer did not have a natural, play continues.
  • Each player, in turn, hits/splits/doubles until done. If any hand busts, it loses immediately. Any naturals are paid immediately and removed.
  • After this, the dealer hits according to casino rules. If the dealer busts, he pays all remaining non-busted player hands.
  • Only after this are hands compared. Since we already know that both are non-busts, it's a simple matter of greater number wins, ties push.

You have to do it in this order or you get the wrong result. The major source of house edge in blackjack is the fact that if both you and the dealer bust, you lose, because you busted first.

"Atlantic City" rules are a bit different, in that the dealer does not have a hole card and doesn't peek. If the dealer ends up having a natural, payouts are adjusted to be as if it had been done in the way outlined above.