python 左右两只手交换扑克牌

示例:小明手里有两张牌,左手红桃♥K、黑桃♠A,小明交换两手的牌后,手里分别是什么?

- 思路:
  - 先找到对象:小明,左手、右手、红桃♥K、黑桃♠A
  - 根据对象找出对应的类:人、手、牌
  - 根据需要写出相应的逻辑,很可能反过来完善类的设计
  - 按照题目要求创建相关对象,调用相关方法,实现相关功能
  """
#扑克类
class Poker:
    def __init__(self,color,num):
        self.color=color
        self.num=num
    def __str__(self):
        return '{}{}'.format(self.color,self.num)
#创建两张牌对象
p1 = Poker('♥','K')
p2 = Poker('♠','A')
print(p1)
print(p2)
#手的类
class Hand:
    def __init__(self,poker):
        self.poker=poker
    def hold_poker(self,poker):
        self.poker = poker
#创建左右两只手对象
left_hand = Hand(p1)
right_hand = Hand(p2)
#人的类
class Person:
    def __init__(self,name,left_hand,right_hand):
        self.name=name
        self.left_hand=left_hand
        self.right_hand=right_hand
        #展示手里面的扑克牌
    def show(self):
        print('{}张开手'.format(self.name), end=':')
        print('左手:{}'.format(self.left_hand.poker), end=',')
        print('右手:{}'.format(self.right_hand.poker))
    # 交换两手的牌
    def swap(self):
        self.left_hand.poker, self.right_hand.poker = self.right_hand.poker, self.left_hand.poker
        print('{}交换两手的牌'.format(self.name))
#创建小明对象
xiaoming=Person('小明',left_hand,right_hand)
#展示手里的牌
xiaoming.show()
#交换两手的牌
xiaoming.swap()
#再次展示
xiaoming.show()

猜你喜欢

转载自blog.csdn.net/qq_42467563/article/details/82974675