|
楼主 |
发表于 2023-12-10 06:00:17
|
显示全部楼层
import random
class Player:
def __init__(self, name):
self.name = name
self.hand = []
self.bjvalue = 0
def __str__(self):
return (self.name+ " has the bjvalue "+self.bjvalue)
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
if rank == 'A':
self.bjValue = 11
elif rank in ['J', 'Q', 'K']:
self.bjValue = 10
else:
self.bjValue = int(rank)
def __str__(self):
return (self.rank+self.suit)
def instructions():
print("You two will play this Black Jack game in turn.")
print("Each of you can get two cards randomly and you can choose request or hold a card.")
print("The winner will be the person whose bjvalue is the closet to 21 and less than 21.")
def makeADeckOf52():
cardSuits = ["♣","♦","♥","♠"]
cardRanks = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
deck = []
for s in cardSuits:
for r in cardRanks:
deck.append(s+r)
random.shuffle(deck)
return(deck)
def update_hand_value(player):
# 计算并更新玩家的手牌的黑杰克值
values={'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,\
'9':9,'10':10,'J':10,'Q':10,'K':10,"A":10}
numA=0
for card in player.hand:
player.bjvalue=values[card[0]]
if card=="A":
numA=numA+1
while player.bjvalue>=21 and numA>0:
player.bjvalue=player.bjvalue-10
numA=numA-1
def dealAHand(deck, player):
# 从牌组中发出两张牌给玩家,并将这两张牌存入玩家的手牌列表
card=deck.pop()
player.hand.append(card)
def displayHand(player):
# 显示玩家的手牌
print(player.name+" has card "+str(player.hand))
def bjHandValue(hand):
# display the total玩家手牌的总黑杰克值
pass
def turn(deck, player):
# 玩家的一轮操作,包括是否要牌的选择
update_hand_value(player)
while player.bjvalue<21:
answer=input("Do you want more card?[y/n] ")
while answer.lower=="y":
card=dealAHand(deck, player)
print(player.name+" has a new card: "+card)
if player.bjvalue>=21:
print(player.name+", you lose! Game over!")
def declare_winner(player1,player2):
# 根据所有玩家的手牌总黑杰克值,声明胜利者
if (21-player1.bjvalue)<(21-player2.bjvalue):
print(player1.name+", you win!")
else:
print(player2.name+", you win!")
def main():
instructions()
deck = makeADeckOf52()
name1 = input("Enter the name of the first player: ")
player1 = Player(name1)
name2 = input("Enter the name of the second player: ")
player2 = Player(name2)
# 发牌
for i in range(2):
dealAHand(deck, player1)
dealAHand(deck, player2)
# 显示玩家的手牌
displayHand(player1)
displayHand(player2)
# 玩家进行操作,直到不再要牌或手牌总黑杰克值超过21点
turn(deck, player1)
turn(deck, player2)
bjHandValue(player1)
bjHandValue(player2)
# 声明胜利者
while player1.bjvalue<21 and player2.bjvalue<21:
declare_winner(player1,player2)
main()
这是我目前的代码,
我可以怎么修改做到减少代码的重复,让两个玩家是有先后顺序的玩,也就是说让游戏可以进行两次,而不是同时玩? |
|