繁体   English   中英

为游戏中的功能插入计数器。 (在整个运行过程中调用了多少次 function)

[英]Insert counter for functions in game. (How many times has a function been called throughout the whole run)

import random


def first_player_chance():
    p1 = random.randint(1, 10)
    p2 = random.randint(1, 10)
    if p1 != p2:
        print(p1, p2)
        second_player_chance()

    else:
        print(p1, p2)
        return print("First player won!")


def second_player_chance():
    p1 = random.randint(1, 10)
    p2 = random.randint(1, 10)
    if p1 != p2:
        print(p1, p2)
        first_player_chance()

    else:
        print(p1, p2)
        return print("Second player won!")


first_player_chance()

这个游戏是一种 1 到 10 的机会游戏。 如果第一次尝试都得到相同的数字,则玩家一获胜。 如果他没有获胜,玩家 2 就有机会。 该程序工作并打印所有尝试的游戏。 但我希望 output 类似于:“第一个玩家在 X 次尝试后获胜!”

我如何在这个游戏中实现计数器? 一个简单的计数器 += 1 不起作用。

您可以使用一个简单的 function 属性来实现它:

import random


def first_player_chance():
    first_player_chance.called += 1  # increment called count
    p1 = random.randint(1, 10)
    p2 = random.randint(1, 10)
    if p1 != p2:
        print(p1, p2)
        second_player_chance()
    else:
        print(p1, p2)
        return print(f"First player won after {first_player_chance.called} rounds!")


def second_player_chance():
    second_player_chance.called += 1
    p1 = random.randint(1, 10)
    p2 = random.randint(1, 10)
    if p1 != p2:
        print(p1, p2)
        first_player_chance()

    else:
        print(p1, p2)
        return print(f"Second player won after {second_player_chance.called} rounds!")

first_player_chance.called = 0  # initialize count for the functions
second_player_chance.called = 0

first_player_chance()

哪个输出:

4 5
5 8
3 1
9 7
10 7
2 1
5 7
5 6
6 2
7 8
4 8
5 6
10 9
3 3
Second player won after 7 rounds!

这可能是您正在寻找的。

请记住,可以通过使用装饰器添加计数器来大量清理代码。

import random

count = 0


def first_player_chance():
    global count
    count += 1
    p1 = random.randint(1, 10)
    p2 = random.randint(1, 10)
    if p1 != p2:
        print(p1, p2)
        second_player_chance()

    else:
        print(p1, p2)
        return print("First player won!")


def second_player_chance():
    global count
    count += 1
    p1 = random.randint(1, 10)
    p2 = random.randint(1, 10)
    if p1 != p2:
        print(p1, p2)
        first_player_chance()

    else:
        print(p1, p2)
        return print("Second player won!")


first_player_chance()
print('count: ', count)

output:

9 8
3 2
1 1
First player won!
count: 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM