1

我正在制作纸牌游戏,当它结束时,我希望人们能够玩更多的回合,但是当它重播时,它必须再次通过变量..重置分数。我正在寻找一种方法来修复它,而无需使用全新的复杂代码块,我希望我只是错过了一个非常简单的修复。

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Imports

import time


def play_game():

    # Variables

    acard = int()
    bcard = int()
    apoints = int()
    bpoints = int()

    # Repeat

    repeat = True

    # Hand out cards

    print 'Cards have been served'
    input('\nPress Enter to Reveal')

    # Cards Turn

    time.sleep(0.5)
    t = time.time()
    acard = int(str(t - int(t))[2:]) % 13
    print '\nYour card value is ' + str(acard)

    time.sleep(0.1)

    t = time.time()
    bcard = int(str(t - int(t))[2:]) % 13

    # Number Check & Point Assign

    time.sleep(2)
    if acard > 5:
        apoints += 1
        print '\nYour points have increased by one, your total is now ' \
            + str(apoints)
    if acard < 5:
        apoints -= 1
        print '\nYour points have decreased by one, your total is now ' \
            + str(apoints)
    if bcard > 5:
        bpoints += 1
        print '\nYour opponent got ' + str(bcard) \
            + ', their points have increased by one,\ntheir total is now ' \
            + str(bpoints)
    if bcard < 5:
        bpoints -= 1
        print '\nYour opponent got ' + str(bcard) \
            + ', their points have decreased by one,\ntheir total is now ' \
            + str(bpoints)

    # Card Reset

    bcard = 0
    acard = 0

    # Shuffle

    input('\nPress enter to shuffle deck')
    print '\nCards being shuffled'
    time.sleep(1)
    print '.'
    time.sleep(1)
    print '.'
    time.sleep(1)
    print '.'
    print 'Cards have been shuffled'
    global enda
    global endb
    enda = apoints
    endb = bpoints


# Loop

time.sleep(1)
answer = 'y'
while answer.lower() == 'y':
    play_game()
    answer = input('\nDo you wish to play again? (Y/N)')

# Scores

if enda > endb:
    print '\nYou Win!'
    print '\nScores'
    print 'You: ' + str(enda) + ' Opponent: ' + str(endb)

if endb > enda:
    print '\nYou Lost!'
    print '\nScores'
    print 'You: ' + str(enda) + ' Opponent: ' + str(endb)
4

6 回答 6

4

我可能会使用面向对象的方式使用类级变量来编写它,但是如果你想让代码尽可能接近你现在拥有的,你可以将你的分数变量移到方法之外:

apoints = 0
bpoints = 0

def play_game():
    global apoints
    global bpoints
    ...
于 2013-09-18T20:29:54.600 回答
1

解决此问题的最佳方法可能是创建一个类并存储您希望在每一轮中保持一致的所有变量。我也不相信这会是一个太复杂的代码块。

class GameVariables(object):

      def __init__(self):
           self.acard = 0
           self.bcard = 0
           self.apoints = 0
           self.bpoints = 0

      def reset(self):
           self.acard = 0
           self.bcard = 0
           self.apoints = 0
           self.bpoints = 0

    #need to initialize class.
    gamevar = GameVariables()

然而,正如其他人所说,在 python 中不需要将变量 = 设置为 int() 。更好的方法是将其设置为等于某个数字:

self.acard = 0

这将在类初始化后保持变量不变,直到您调用类中包含的重置方法。

为此,请像调用任何其他函数一样调用它,但要在前面加上类名。

gamevar.reset() #this will reset variables.

如果您的游戏变得更大更复杂,这将变得特别有用。希望这可以帮助。

于 2013-09-18T20:36:23.217 回答
1

函数的本质是在每次调用时初始化它们的变量。关键是它们每次都以相同的方式工作。

如果您希望变量持续存在并与函数相关联,则使用对象。这也允许您将巨大的代码块分解为更小的函数。

于 2013-09-18T20:36:35.160 回答
1

您可以进行的最简单的更改是使这些变量成为“全局变量”。

因此,例如:

a = 5

def myfunc():
    print a
    a = 7

myfunc()

将不起作用,因为对ain的赋值myfunc()使 Python 认为您a在函数中声明了第二个局部变量。您可以通过执行以下操作来使用全局变量:

a = 5

def myfunc():
    global a
    print a
    a = 7

myfunc()

这明确说明您希望a函数内部的所有引用都引用全局定义的a.

令人困惑的是,如果您没有a在函数中赋值,它会将函数外部定义的变量视为函数范围内的变量:

a = 5

def myfunc():
    print a

myfunc()

(这将打印数字 5。)

编辑:建议使用类的另一个答案是提供许多好处的解决方案。在复杂程序中使用许多全局变量会降低可维护性,因为它们会强制这些变量共享一个命名空间,并且使一个函数可能对另一个函数可能产生的副作用不那么明确,因为使用许多全局变量您可能无法分辨很容易在更改特定变量的地方。

然而,如果你打算采用基于类的方法来解决你的问题,你最好花一些时间来熟悉面向对象编程和设计的语言,因为你的代码的一些行为'在您了解这些概念之前,您可能不清楚要写的内容。

在您的代码中,使这些变量成为全局变量会改变这部分:

def play_game():

    # Variables

    acard = int()
    bcard = int()
    apoints = int()
    bpoints = int()

对此:

acard = int()
bcard = int()
apoints = int()
bpoints = int()

def play_game():

    # Variables

    global acard
    global bcard
    global apoints
    global bpoints

# etc.

还有一个想法:使用类似的东西

apoints = int()

因为您希望将变量“声明”为整数可能不会产生您认为的效果。在 Python 中这样做是完全有效的:

apoints = int()
print(apoints)

apoints = 5.0
print(apoints)

apoints = "My string"
print(apoints)

因此,创建apoints一个 int 并不会使变量永远成为整数。您最好为变量分配一个显式值:

apoints = 0

Python 变量类型的这个属性称为“鸭子类型”。

http://en.wikipedia.org/wiki/Duck_typing

于 2013-09-18T20:36:42.573 回答
1

这是转换为基于类的编程的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Imports

import time

class Play_Game:

    def __init__(self):
        self.apoints = 0
        self.bpoints = 0

    def play_game(self):

        repeat = True
        print 'Cards have been served'
        raw_input('\nPress Enter to Reveal')

        # Cards Turn

        time.sleep(0.5)
        t = time.time()
        acard = int(str(t - int(t))[2:]) % 13
        print '\nYour card value is ' + str(acard)

        time.sleep(0.1)

        t = time.time()
        bcard = int(str(t - int(t))[2:]) % 13

        # Number Check & Point Assign

        time.sleep(2)
        if acard > 5:
            self.apoints += 1
            print '\nYour points have increased by one, your total is now ' \
                + str(self.apoints)
        elif acard < 5:
            self.apoints -= 1
            print '\nYour points have decreased by one, your total is now ' \
                + str(self.apoints)
        elif bcard > 5:
            self.bpoints += 1
            print '\nYour opponent got ' + str(bcard) \
                + ', their points have increased by one,\ntheir total is now ' \
                + str(self.bpoints)
        elif bcard < 5:
            self.bpoints -= 1
            print '\nYour opponent got ' + str(bcard) \
                + ', their points have decreased by one,\ntheir total is now ' \
                + str(self.bpoints)
        else:
            pass

        # Shuffle

        raw_input('\nPress enter to shuffle deck')
        print '\nCards being shuffled'
        time.sleep(1)
        print '.'
        time.sleep(1)
        print '.'
        time.sleep(1)
        print '.'
        print 'Cards have been shuffled'
        return

    def check_winner(self):
        if self.apoints > self.bpoints:
            print '\nYou Win!'
            print '\nScores'
            print 'You: ' + str(self.apoints) + ' Opponent: ' + str(self.bpoints)

        else:
            print '\nYou Lost!'
            print '\nScores'
            print 'You: ' + str(self.apoints) + ' Opponent: ' + str(self.bpoints)
        return


if __name__ == '__main__':

    time.sleep(1)
    answer = 'y'
    current_game = Play_Game()
    while answer.lower() == 'y':
        current_game.play_game()
        current_game.check_winner()
        answer = raw_input('\nDo you wish to play again? (Y/N)')
于 2013-09-18T21:04:28.483 回答
0

将您的变量移到函数之外并将您正在使用的变量设置为 += on 为 0 并且由于您在函数中设置 acard 和 bcard 的值,因此您不需要为它设置全局变量,因为它不断改变:

def play_game(apoints: int, bpoints: int):
    ...


if __name__ == __main__:
    apoints = 0
    bpoints = 0
    play_game(apoints, bpoints)
于 2013-09-18T20:34:41.500 回答