如何使用python中只有一个类的实例

时间:2015-01-16 02:56:50

标签: python class instance

我已经可以说这个问题不受欢迎,而且可能很快得到回答。我想通过让你知道我对此进行研究,但不能理解该怎么做来为此作序。

所以我有一个python脚本,可以创建一个卡片游戏。卡片游戏的想法是3。只有(据我所知)我的家人知道怎么玩的游戏。

到目前为止,我的脚本是:

import math
import random
from itertools import product

def start_game():
    print ("Game started")
    deck = Deck()
    deck.current_turn = random.randint(1,2)
    print ("Player " + str(deck.current_turn) + " will go first.")
    Round_Start()
def Round_Start():
    deck = Deck()
    p1down = Player1Down()
    p2down = Player2Down()
    p1up = Player1Up()
    p2up = Player2Up()
    if p1down.hidden == True:
        print("P1: " + " - ".join(map(str,p1up.cards)))
        print("P1: #/# - #/# - #/#")
    else:
        print("P1: " + " - ".join(map(str,p1up.cards)))
        print("P1: " + " - ".join(map(str,p1down.cards)))
    if p2down.hidden == True:
        print("P2: " + " - ".join(map(str,p2up.cards)))
        print("P2: #/# - #/# - #/#")
    else:
        print("P2: " + " - ".join(map(str,p2up.cards)))
        print("P2: " + " - ".join(map(str,p2down.cards)))
    Give_Turn()
def P1Turn():
    print("It is now Player 1's turn.")
def P2Turn():
    print("It is now Player 2's turn.")
def Give_Turn():
    deck = Deck()
    print(deck.current_turn)
    if deck.current_turn == 2:
        print("It is now Player 1's turn.")
        P1Turn()
    elif deck.current_turn == 1:
        print("It is now Player 2's turn.")
        P2Turn()
class Player1Down(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
        self.hidden = True
class Player2Down(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
        self.hidden = True
class Player1Up(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
class Player2Up(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
class Deck(object):
    current_turn = 0
    def __init__(self, ranks=None, suits=None):

        if ranks is None:
            ranks = range(2,15)
        if suits is None:
            suits = ["H","D","C","S"]
        self.deck = []
        for r in ranks:
            for s in suits:
                self.deck.append(Card(r,s))
    def Deal(self, n):
        return random.sample(self.deck,n)

class Card(object):
    FACES = {11: 'J', 12: 'Q', 13: 'K', 14: 'A'}
    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        value = self.FACES.get(self.rank, self.rank)
        return "{0}/{1}".format(value, self.suit)

    def __lt__(self, other):
        return self.rank < other.rank
if __name__ == '__main__':
    start_game()

现在一些脚本是来自其他用户的直接复制粘贴工作,这是我能够在此之前完成工作的唯一方法。

我的问题是

deck.current_turn

保持重置为0.我认为这是因为我打开了Deck()类的多个实例。但我不知道如何解决这个问题。

我当前脚本的输出是:

Game started
Player 2 will go first.
P1: 7/H - 9/H - J/H
P1: #/# - #/# - #/#
P2: 5/H - 3/S - 10/H
P2: #/# - #/# - #/#
0

这是我的第一篇Stack Exchange帖子,如果这是一个愚蠢的问题,我很抱歉。

1 个答案:

答案 0 :(得分:2)

评论中提出的解决方案要好得多,但快速而肮脏的方法是SingletonBorg

Singleton方式:

class Deck(object):
    _deck = None
    def __new__(cls, *a, **k):
        if not cls._deck:
            cls._deck = object.__new__(cls, *a, **k)
        return cls._deck
    # and the rest as you have it above

博格方式:

class Deck(object):
    _dict = {}
    def __init__(self, ranks=None, suits=None):
        self.__dict__ = self._dict
        # and the rest as you have it, inc. the rest of __init__

他们都工作。作为Borg的原始发明者,当然,我对它有一个情有独钟,你仍然可以在http://www.aleax.it/Python/5ep.html阅读我关于它的古老文章。