|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
怎么样修改可以做到使用turn的function,实现让两个玩家轮流玩,我写的有点问题,我写的是让两个玩家同时进行
而且我的代码中update_hand_value方程中,无法实现我想要的结果
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):
# calculate and update the bjvalue
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):
# display their hands
print(player.name+" has card "+str(player.hand))
def bjHandValue(hand):
# display the total bjvalue
pass
def turn(deck, player):
# including whether to accept another card
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):
# accoring to their total bjvalue, declare the winner
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)
# give the players cards
for i in range(2):
dealAHand(deck, player1)
dealAHand(deck, player2)
# show the players' hands
displayHand(player1)
displayHand(player2)
# 玩家进行操作,直到不再要牌或手牌总黑杰克值超过21点
turn(deck, player1)
turn(deck, player2)
bjHandValue(player1)
bjHandValue(player2)
# declare the winner
while player1.bjvalue<21 and player2.bjvalue<21:
declare_winner(player1,player2)
main() |
|