gpt4 book ai didi

Python 游戏 "House of Cards"需要帮助

转载 作者:行者123 更新时间:2023-11-30 23:21:26 25 4
gpt4 key购买 nike

我目前是一个Python新手,正在使用Python创建一些游戏。我编写了一个游戏“纸牌屋”,基本上我正在尝试使用我在 OOP 中学到的知识来完成它。规则非常简单——你需要最大的牌才能获胜。玩家首先比较数字,然后比较牌的花色——拥有最大牌的人获胜。我编写了以下代码:

import itertools
import random

class Card (object):
def __init__ (self):
self.suit = ["Cubs", "Diamonds", "Hearts", "Spades"]
self.value = ["2","3","4","5","6","7","8","9","10", "J", "Q", "K", "A"]
self.deck = []
for card in itertools.product(self.value, self.suit):
self.deck.append(card)

class Player(object):
def __init__ (self, name, card = None):
self.name = name
self.carddeck = Card()
self.card_available = self.carddeck.deck
def draw_a_card(self):
self.card = random.choice(self.card_available)
print "%s has gotten a %s" %(self.name, self.card)
def __cmp__(self, other):
if self.card_available.index(self.card) > self.card_available.index(other.card):
print "%s wins!" %(self.name)
elif self.card_available.index(self.card) < self.card_available.index(other.card):
print "%s wins!" %(other.name)

player_1= Player("Player 1")
player_2 = Player("Player 2")
player_3 = Player("Player 3")
player_1.draw_a_card()
player_2.draw_a_card()
player_3.draw_a_card()
cards_deck = Card()
player_1.__cmp__(player_2)

经过一番努力,我已经成功比较了玩家 1 和玩家 2 之间的牌,但我不知道如何将玩家 3 纳入比较中。

最佳答案

cmp 函数用于覆盖比较,以便您可以执行类似的操作

如果玩家1 > 玩家2:打印“玩家1击败玩家2!”

不是这样你就可以在函数内打印一些消息...通过不返回任何东西,你本质上是说它们是相等的(我认为在python中,不从cmp返回任何东西大致相当于返回0),或者更糟糕的是可能会引发如果您尝试正常比较,则会出现错误...

class Player(object):
def __init__ (self, name, card = None):
self.name = name
self.carddeck = Card()
self.card_available = self.carddeck.deck
def draw_a_card(self):
self.card = random.choice(self.card_available)
print "%s has gotten a %s" %(self.name, self.card)
def __cmp__(self, other):
if self.card_available.index(self.card) > self.card_available.index(other.card):
return 1
elif self.card_available.index(self.card) < self.card_available.index(other.card):
return -1
return 0

print max([player1,player2,player3]), "Wins!"
print min([player1,player2,player3]), "Loses!!!"

这是最简单的方法......

你真的错过了 OOP 设计的几个方面

class Card:
def __init__(self,val,suite):
self.val = val
self.suite = suite
def __int__(self):
return self.val
def __str__(self):
card_name = ["2","3","4","5","6","7","8","9","10", "J", "Q", "K", "A"][self.val]
suite_name = ["Clubs","Spades","Diamonds","Hearts"][self.suite]
return card_name + " of " + suite_name
def __cmp__(self,other):
return cmp(int(self),int(other))

print Card(1,3)
print Card(4,2) < Card(3,2)

请注意,该牌与牌组无关......它属于牌组

deck = [Card(i,j) for i in range(13) for j in range(4)]
random.shuffle(deck.shuffle)

关于Python 游戏 "House of Cards"需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24962469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com