-
Notifications
You must be signed in to change notification settings - Fork 3
/
500.R
587 lines (483 loc) · 20.1 KB
/
500.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# coding up the game of 500 in R, just for fun!
# AF june 3, 2013
# updated again june 11, 2013
# set up an S4 class for the cards
setClass("card",
representation(
suit = "character", # the card's suit
number = "character", # the card's value (2-10, J, Q, K, A)
trump = "logical" # whether it falls into the called trump suit
)
)
# card constructor:
card = function(suit, number, trump=FALSE) {
return(new("card", suit=suit, number=number, trump=trump))
}
# define a slot setter for trump (need to change based on bid results):
setGeneric("trump<-", function(x, value) standardGeneric("trump<-"))
setReplaceMethod("trump", "card", function(x, value) {x@trump <- value; x})
# define the slot getters:
setGeneric("suit", function(x) standardGeneric("suit"))
setMethod("suit", "card", function(x) x@suit)
setGeneric("number", function(x) standardGeneric("number"))
setMethod("number", "card", function(x) x@number)
setGeneric("trump", function(x) standardGeneric("trump"))
setMethod("trump", "card", function(x) x@trump)
# define the show method:
setMethod("show", "card",
function(object){
if(number(object)=="joker") {cat("joker [trump]\n")}
else if(trump(object)) {cat(paste(number(object), suit(object), "[trump]", "\n"))}
else {cat(paste(number(object), suit(object), "\n"))}
}
)
# define a < or > method
# function to create a deck (of cards):
makeDeck = function(trump = NULL){
deck = list() #list to hold the cards
deck.df = expand.grid(c(4:10, "J", "Q", "K", "A"), c("spades", "clubs", "diamonds", "hearts"), stringsAsFactors = FALSE)
names(deck.df) = c("number", "suit")
deck.df = rbind(deck.df, c("joker", "none"))
for(i in 1:nrow(deck.df)){
deck[[i]] = card(suit = deck.df$suit[i], number=deck.df$number[i])
}
if(!is.null(trump)){
if(trump=="hearts") trumpCardInds = c(34:40, 42:44, 30, 41, 45)
if(trump=="diamonds") trumpCardInds = c(23:29, 31:33, 41, 30, 45)
if(trump=="spades") trumpCardInds = c(1:7, 9:11, 19, 8, 45)
if(trump=="clubs") trumpCardInds = c(12:18, 20:22, 8, 19, 45)
nonTrumpInds = c(1:45)[-trumpCardInds]
for(i in trumpCardInds) trump(deck[[i]]) = TRUE
deck = deck[c(nonTrumpInds, trumpCardInds)]
}
return(deck)
}
# function to sort a list of cards:
# [HELPER] function to compare two cards and see if they are the same:
compare = function(c1, c2){
# this function recurses, WOAH
if(class(c1)=="list"){
return(lapply(c1, function(x) compare(x, c2)))
}
return(suit(c1)==suit(c2) & number(c1)==number(c2))
}
# now the sorting:
sortHand = function(hand, trump=NULL){
deck = makeDeck(trump=trump)
inds = sapply(hand, function(x) which(compare(deck, x)==TRUE))
return(deck[sort(inds)])
}
# function to show a hand:
showHand = function(hand){
for(i in 1:length(hand)){
print(hand[[i]])
}
}
# function to divide cards into hands (or, as they say, "deal"):
deal = function(deck){
# first: shuffle
deck.shuffled = sample(deck)
# deal the cards (threes, fours (2 to the kitty), threes) and sort the hands
hand1 = sortHand(deck.shuffled[c(1:3, 16:19, 34:36)])
hand2 = sortHand(deck.shuffled[c(4:6, 20:23, 37:39)])
hand3 = sortHand(deck.shuffled[c(7:9, 24:27, 40:42)])
dealerhand = sortHand(deck.shuffled[c(10:12, 28:31, 43:45)])
kitty = sortHand(deck.shuffled[c(13:15, 32:33)])
# return the dealt hand
return(list(hand1=hand1, hand2=hand2, hand3=hand3, dealerhand=dealerhand, kitty=kitty))
}
#deck = makeDeck()
#deal(deck)
# function to compare bids:
compareBids = function(bid1, bid2){
# bid1/bid2 are length-2 vectors of strings (num + suit), except for that you can put in NULL for bid1 and "pass" for bid2
# want to know if bid2 is higher than bid1
# relies on alphabetical order of "aspades", "clubs", "diamonds", "hearts", "notrump"
if(is.null(bid1)) return(TRUE)
if(length(bid2)==1){
if(bid2=="pass"){
return(TRUE)
}
}
if(as.numeric(bid2[1]) > as.numeric(bid1[1])) return(TRUE)
if(as.numeric(bid2[1]) < as.numeric(bid1[1])) return(FALSE)
if(bid2[2] == bid1[2]) return(FALSE)
if(bid2[2] < bid1[2]) return(FALSE)
return(TRUE)
}
# function to check the bid for rule-breaking:
checkBid = function(bid, highBid){
# if you bid something weird:
##[too long or too short]
if(length(bid)!=2){
if(bid[1] == "pass") return(bid)
if(length(bid)>2 | (length(bid)==1 & bid[1]!="pass")){
theBid = strsplit(readline("invalid bid - try again: "), split=" ")[[1]]
if(length(theBid)>1){
if(theBid[2]=="spades") theBid[2] = "aspades"
}
return(checkBid(theBid, highBid))
}
}
##[not bidding a number]
if(suppressWarnings(is.na(as.numeric(bid[1])))){
theBid = strsplit(readline("invalid bid (bid <NUMBER><space><SUIT>) - try again: "), split=" ")[[1]]
if(length(theBid)>1){
if(theBid[2]=="spades") theBid[2] = "aspades"
}
return(checkBid(theBid, highBid))
}
##[bidding an invalid suit]
if(bid[2]!="hearts" & bid[2]!="spades" & bid[2]!="diamonds" & bid[2]!="clubs" & bid[2]!="notrump" & bid[2]!="aspades"){
theBid = strsplit(readline("invalid bid (suits are hearts, spades, diamonds, clubs, and notrump) - try again: "), split=" ")[[1]]
if(length(theBid)>1){
if(theBid[2]=="spades") theBid[2] = "aspades"
}
return(checkBid(theBid, highBid))
}
# if you bid less than 6:
if(bid[1] < 6){
theBid = strsplit(readline("please bid at least 6: "), split=" ")[[1]]
if(length(theBid)>1){
if(theBid[2]=="spades") theBid[2] = "aspades"
}
return(checkBid(theBid, highBid))
}
# if you bid lower than the current highest bid:
if(!compareBids(highBid, bid)){
if(highBid[2]=="aspades") highBid[2] = "spades"
message(paste0("You must bid higher than the current high bid (",paste(highBid, collapse=" "),")"))
theBid = strsplit(readline("new bid: "), split=" ")[[1]]
if(length(theBid)>1){
if(theBid[2]=="spades") theBid[2] = "aspades"
}
return(checkBid(theBid, highBid))
}
return(bid)
}
# function to find a given card in a hand
findCard = function(hand, cardname){
# cardname = string, such as "joker", "A hearts", etc.
# hand is a list of cards.
splitCard = strsplit(cardname, split=" ")[[1]]
if(length(splitCard) == 0) return(NULL)
if(length(splitCard) == 1){
if(splitCard != "joker") return(NULL)
myCard = card(suit="none", number="joker")
}else{
myCard = card(suit=splitCard[2], number=splitCard[1])
}
tf = compare(hand, myCard)
cardInd = which(tf==TRUE)
return(cardInd)
}
### bidding action:
makeBids = function(dealer, hands){
## "dealer" = id of player who is now the dealer
## "hands" = dealt deck object
highBid = NULL #(nobody has bid yet)
firstTwo = list() # so that second-partner-bidders can be reminded
firstBidders = c(1:3)+dealer
firstBidders = sapply(firstBidders, function(x){
if(x > 4){return(x %% 4)}; return(x)
})
biddingOrder = c(firstBidders, dealer)
leadPlayer = NULL #(nobody is winning yet)
for(i in 1:4){
if(i==4) message("[dealer]")
message(paste0("player ", biddingOrder[i],": here is your hand." ))
showHand(hands[[i]])
if(i==4 | i==3) message(paste0("your partner has bid ", paste(firstTwo[[i-2]], collapse=" ")))
theBid = strsplit(readline("Please make your bid: "), split=" ")[[1]]
if(length(theBid)>1){
if(theBid[2]=="spades") theBid[2] = "aspades"
}
theBid = checkBid(theBid, highBid) # this will ALWAYS result in either a "pass" or a new high bid.
if(length(theBid)>1){
highBid = theBid
leadPlayer = biddingOrder[i]
}
# for printing only:
if(i==2 | i==1){
if(theBid[1]!="pass"){
if(theBid[2]=="aspades") theBid[2] <- "spades"
}
firstTwo[[i]] <- theBid
}
} #end loop: finished bidding.
if(!is.null(highBid)){
if(highBid[1]=="6") leadPlayer = NULL #we don't play 6 bids
}
return(list(leadPlayer=leadPlayer, dealer=dealer, highBid=highBid, biddingOrder=biddingOrder))
} # end bidding function
#############################
######## PLAY BALL!! ########
#############################
play500 = function(){
score13 = 0
score24 = 0
dealer = 4 # player 4 starts as the dealer.
# create the score table (just once, before the loop)
scoreTable = matrix(seq(140, 520, by=20), ncol=5, byrow=TRUE)
colnames(scoreTable) = c("spades", "clubs", "diamonds", "hearts", "notrump")
rownames(scoreTable) = c("7", "8", "9", "10")
while(score13<500 & score13>(-500) & score24<500 & score24>(-500)){
deck = makeDeck()
###################################
# deal the cards:
dealer = ifelse(dealer <= 4, dealer, dealer %% 4)
message(paste("Player",dealer,"is dealing."))
hands = deal(deck)
###################################
# have players bid:
bidObject = makeBids(dealer, hands)
leadPlayer = bidObject$leadPlayer
# check that a valid bid was actually made
while(is.null(leadPlayer)){
newDealer = bidObject$dealer+1
newDealer = ifelse(newDealer == 5, 1, newDealer)
if(!is.null(bidObject$highBid)){
message(paste("House rules: play only continues if the highest bid is at least 7. Deal moves to player", newDealer))
}
if(is.null(bidObject$highBid)){
message(paste("Everyone has passed. Deal moves to player",newDealer))
}
message(paste("Player",newDealer,"is dealing."))
hands = deal(deck)
bidObject = makeBids(newDealer, hands)
dealer = newDealer # to use at end of the hand
leadPlayer = bidObject$leadPlayer
}
###################################
# determine the winning bid, and in which order everyone bid:
bidWinner = leadPlayer #(leadPlayer will change in later tricks, but bidWinner needs to be stored)
highBid = bidObject$highBid
biddingOrder = bidObject$biddingOrder
if(highBid[2]=="aspades") highBid[2] = "spades"
message(paste0("Player ",leadPlayer," wins the bid with ",paste(highBid, collapse=" ")))
###################################
# winning player gets the kitty
message(paste0("Player ", leadPlayer,": the kitty is here:"))
showHand(hands$kitty)
message("and again, here is your hand:")
leadHandIndex = which(biddingOrder==leadPlayer)
showHand(hands[[leadHandIndex]])
message("of these 15 cards, enter the 10 you would like to keep.")
# (pick 10 cards)
j = 1
newHand = list() #create empty list, for his new hand
while(j <= 10){
cardname = strsplit(readline(paste0("card ",j,": ")),split=" ")[[1]]
# if the card is the joker:
if(length(cardname)==1){
if(cardname != "joker"){
message("Invalid card - try again.")
next
}
tryJoker = findCard(hands[[leadHandIndex]], "joker")
if(length(tryJoker)==0){
tryJokerKitty = findCard(hands$kitty, "joker")
if(length(tryJokerKitty)==0){
message("the joker is not in your hand or the kitty - try again.")
next
}
}
alreadyJokered = findCard(newHand, "joker")
if(length(alreadyJokered)!=0){
message("you already have the joker in your hand - try again.")
next
}
newHand[[j]] = card(suit = "none", number="joker", trump=TRUE )
}
# if the card is not the joker:
if(length(cardname)>1){
# make sure it's in this player's hand:
tryCard = findCard(hands[[leadHandIndex]], paste(cardname, collapse=" "))
if(length(tryCard)==0){
tryCardKitty = findCard(hands$kitty, paste(cardname, collapse=" "))
if(length(tryCardKitty)==0){
message("this card is not in your hand or the kitty - try again.")
next
}
}
# make sure he didn't already pick it:
cardAlready = findCard(newHand, paste(cardname, collapse=" "))
if(length(cardAlready)!=0){
message("you already have this card in your hand - try again.")
next
}
# assuming they've picked a valid card, assign trump (deal w/ low bower)
if(cardname[2] == highBid[2]){
isTrump = TRUE
}else if(cardname[1]=="J" & highBid[2]=="spades" & cardname[2]=="clubs"){
isTrump = TRUE
}else if(cardname[1]=="J" & highBid[2]=="clubs" & cardname[2]=="spades"){
isTrump = TRUE
}else if(cardname[1]=="J" & highBid[2]=="hearts" & cardname[2]=="diamonds"){
isTrump = TRUE
}else if(cardname[1]=="J" & highBid[2]=="diamonds" & cardname[2]=="hearts"){
isTrump = TRUE
}else{isTrump = FALSE}
newHand[[j]] = card(suit = cardname[2], number=cardname[1], trump=isTrump )
}
j = j+1
} # finish choosing hand
hands[[leadHandIndex]] = newHand
###################################
# sort and assign trump to each player's hand
for(phand in 1:4) hands[[phand]] = sortHand(hands[[phand]], trump=highBid[2])
###################################
# keep track of who takes which tricks
numTricks13 = 0
numTricks24 = 0
###################################
# play the game :)
# we already have a lead player (leadPlayer = 1, 2, 3, or 4 depending on who won the bid)
# OR lead player was set at the end of the previous trick.
for(trick in 1:10){
leadHandIndex = which(biddingOrder==leadPlayer)
cardsPlayed = list()
message(paste0("Player ", leadPlayer,": here is your hand. It's your lead!"))
showHand(sortHand(hands[[leadHandIndex]], trump = highBid[2]))
ledCard = readline("what card would you like to play? ")
ledCardInd = findCard(hands[[leadHandIndex]], ledCard)
while(length(ledCardInd)==0){
ledCard = readline("this card is not in your hand - choose another: ")
ledCardInd = findCard(hands[[leadHandIndex]], ledCard)
}
# add card to the middle:
cardsPlayed = append(cardsPlayed, hands[[leadHandIndex]][[ledCardInd]])
# remove card from your hand:
hands[[leadHandIndex]] = hands[[leadHandIndex]][-ledCardInd]
# figure out which suit was led:
ledSuit = ifelse(trump(cardsPlayed[[1]]), highBid[2], suit(cardsPlayed[[1]]))
# have the other players play, following suit.
nextPlayers = c(1:3)+leadPlayer
nextPlayers = sapply(nextPlayers, function(x){
if(x > 4){return(x %% 4)}; return(x)
})
for(player in nextPlayers){
handIndex = which(biddingOrder == player)
message(paste0("Player ", player,": here is your hand. It's your turn!"))
showHand(sortHand(hands[[handIndex]], trump = highBid[2]))
message(paste("led:", ledCard))
if(length(cardsPlayed)>1){
for(cnum in 2:length(cardsPlayed)){
if(number(cardsPlayed[[cnum]])=="joker"){
message("joker")
}else{
message(paste(number(cardsPlayed[[cnum]]), suit(cardsPlayed[[cnum]])))
}# end if/else
}# end for loop
}# end if(length(cardsPlayed)>1)
chosenCard = readline("what card would you like to play? ")
chosenCardInd = findCard(hands[[handIndex]], chosenCard)
while(length(chosenCardInd)==0){
chosenCard = readline("this card is not in your hand - choose another: ")
chosenCardInd = findCard(hands[[handIndex]], chosenCard)
}
chosenCard.obj = hands[[handIndex]][[chosenCardInd]]
# did the player have any of the suit that was led?
if(trump(cardsPlayed[[1]])){
# if trump was led:
howManyTrump = sum(sapply(hands[[handIndex]], function(x) trump(x)))
while(!trump(chosenCard.obj) & howManyTrump!=0){
message(paste0("you must follow suit (suit led: ", ledSuit,")"))
chosenCard = readline(paste0("please play a ", substr(ledSuit,1,nchar(ledSuit)-1),": "))
chosenCardInd = findCard(hands[[handIndex]], chosenCard)
chosenCard.obj = hands[[handIndex]][[chosenCardInd]]
}
}
if(!trump(cardsPlayed[[1]])){
# if off-suit was led:
howManyOfSuit = sum(sapply(hands[[handIndex]], function(x) (suit(x)==ledSuit & !trump(x))))
while(suit(chosenCard.obj)!=ledSuit & howManyOfSuit!=0){
message(paste0("you must follow suit (suit led: ", ledSuit,")"))
chosenCard = readline(paste0("please play a ", substr(ledSuit,1,nchar(ledSuit)-1),": "))
chosenCardInd = findCard(hands[[handIndex]], chosenCard)
chosenCard.obj = hands[[handIndex]][[chosenCardInd]]
}
}
# add card to the middle:
cardsPlayed = append(cardsPlayed, chosenCard.obj)
# remove card from your hand:
hands[[handIndex]] = hands[[handIndex]][-chosenCardInd]
} # all players are done playing
showHand(cardsPlayed)
# figure out which card wins:
playerList = c(leadPlayer, nextPlayers)
trumpDeck = makeDeck(trump = highBid[2])
trumpBool = sapply(cardsPlayed, function(x) trump(x))
anyTrump = sum(trumpBool)
if(anyTrump > 0){
trumpInds = which(trumpBool)
deckRank = sapply(trumpInds, function(x) findCard(trumpDeck, paste(number(cardsPlayed[[x]]), suit(cardsPlayed[[x]]))))
winInd = trumpInds[which.max(deckRank)]
}
if(anyTrump == 0){
followSuitInds = which(sapply(cardsPlayed, function(x) suit(x)==ledSuit))
deckRank = sapply(followSuitInds, function(x) findCard(trumpDeck, paste(number(cardsPlayed[[x]]), suit(cardsPlayed[[x]]))))
winInd = followSuitInds[which.max(deckRank)]
}
winningPlayer = playerList[winInd]
winningCard = paste(number(cardsPlayed[[winInd]]), suit(cardsPlayed[[winInd]]))
if(number(cardsPlayed[[winInd]]) == "joker") winningCard = "joker"
message(paste0("Player ",winningPlayer," wins, with ", winningCard))
if(winningPlayer==1 | winningPlayer == 3){
numTricks13 = numTricks13 + 1
}
if(winningPlayer==2 | winningPlayer == 4){
numTricks24 = numTricks24 + 1
}
leadPlayer = winningPlayer
message("Players 1/3 have this many tricks:")
print(numTricks13)
message("Players 2/4 have this many tricks:")
print(numTricks24)
} # finish playing tricks.
###################################
# determine winner and return the score
rowInd = which(rownames(scoreTable)==highBid[1])
colInd = which(colnames(scoreTable)==highBid[2])
if((bidWinner==1 | bidWinner==3) & numTricks13>=as.numeric(highBid[1])){
message("players 1 and 3 have made their bid!")
score13 = score13 + scoreTable[rowInd, colInd]
score24 = score24 + 10*numTricks24
}
if((bidWinner==2 | bidWinner==4) & numTricks24>=as.numeric(highBid[1])){
message("players 2 and 4 have made their bid!")
score24 = score24 + scoreTable[rowInd, colInd]
score13 = score13 + 10*numTricks13
}
if((bidWinner==1 | bidWinner==3) & numTricks13<as.numeric(highBid[1])){
message("bummer - players 1 and 3 have been set.")
score13 = score13 - scoreTable[rowInd, colInd]
score24 = score24 + 10*numTricks24
}
if((bidWinner==2 | bidWinner==4) & numTricks24<as.numeric(highBid[1])){
message("bummer - players 2 and 4 have been set.")
score24 = score24 - scoreTable[rowInd, colInd]
score13 = score13 + 10*numTricks13
}
message("score update:")
message(paste0("players 1 and 3 have ", score13," points."))
message(paste0("players 2 and 4 have ", score24," points."))
dealer = dealer + 1
dealer = ifelse(dealer<=4, dealer, dealer %% 4)
} ### END GIANT WHILE LOOP (nobody is above 500 or below -500)
if(score13 >= 500){
message("Players 1 and 3 WIN!")
}
if(score13 <= (-500)){
message("Players 2 and 4 win, by virtue of players 1 and 3 LOSING!")
}
if(score24 >= 500){
message("Players 2 and 4 WIN!")
}
if(score24 <= (-500)){
message("Players 1 and 3 win, by virtue of players 2 and 4 LOSING!")
}
message("thank you for playing!")
}
### And, now you can play the game:
play500()