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

标签 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 帖子,如果这是一个愚蠢的问题,我很抱歉。

最佳答案

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

单例方式:

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 阅读我关于它的古老文章。 .

关于python - 如何在python中使用只有一个类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27976598/

相关文章:

javascript - 将 python 函数转换为 Javascript/node.js

c# - UML 类图 - 我们在这里包含像用户控件和 MainWindow 这样的部分类吗?

c# - 在asp.net中创建一个基本类

C++ 创建一个类的实例?

c# - 无法使用实例引用访问成员 '<method>'

python - 我的执行文件。从 pyinstaller 创建的文件不像 .py 时那样工作(Pyexcel 问题)

python - 如何在 python 中合并重叠的字符串?

swift - 枚举在自定义初始化程序中不起作用

Cocoa: 'amountOfReservations' 的本地声明隐藏了实例变量。怎么了?

python : printing lines of factorial "*" through recursion