随机播放一副牌并将其分配给四名玩家。当有人有4颗心并说出谁是胜利者时,你需要停止游戏

时间:2018-03-18 14:13:29

标签: python probability

我需要为Shuffle编写一个python代码,然后将它分发给四个玩家。当有人有4颗心并且说谁是胜利者时,你需要停止游戏。作为我在python中的初学者并直接完成它。任何人都可以给我优化的代码编码方式??这是我的尝试..

import random
colour=["Heart","Spade","Club","Diamond"] 
a=[2,3,4,5,6,7,8,9,10,"J","Q","K","A"] 
player1,player2,player3,player4=[],[],[],[]
shuffle=[{x:y} for x in colour for y in a ]
cnt=0
while len(shuffle)!=0:
    p1,p2,p3,p4=random.sample(population=shuffle,k=4) 

    i1=shuffle.index(p1)
    del shuffle[i1]
    i2=shuffle.index(p2)
    del shuffle[i2]
    i3=shuffle.index(p3)
    del shuffle[i3]
    i4=shuffle.index(p4)
    del shuffle[i4]

    if "Heart" in p1:
        player1.append(p1)
        if len(player1)>=4:
            print("player 1 is win ,heart cards are:",player1)
            break
    if "Heart" in p2:
        player2.append(p2)
        if len(player2)>=4:
            print("player 2 is win,heart cards are:",player2)
            break
    if "Heart" in p3:
        player3.append(p3)
        if len(player3)>=4:
            print("player 3 is win,heart cards are:",player3)
            break
    if "Heart" in p4:
        player4.append(p4)
        if len(player4)>=4:
            print("player 4 is win,heart cards are:",player4)
            break

2 个答案:

答案 0 :(得分:1)

牌组有52张牌。把他们洗了一次。向每位玩家发放一张牌,直到牌组为空或其中一个玩家有4个心。一颗心是一张卡,那个数字是0 mod 4.其他套房是1 mod 4,2 mod 4和3 mod 4.

from random import shuffle

deck = range(52)
shuffle(deck)

from itertools import cycle

players = [[] for _ in range(4)]

for i, p in cycle(enumerate(players)):
    if not deck: break
    p.append(deck.pop())
    if sum(1 for c in p if c % 4 == 0) == 4:
        print i
        break

print players

答案 1 :(得分:1)

假设卡1-12是心脏。我使用shuffle函数来分发卡,然后将它们分成4个阵列。我只计算每个数组中卡号小于13的最小索引,然后返回palyer索引

from random import shuffle
import numpy as np
x = range(52)
shuffle(x)
x = [(i<13)*1 for i in x]
y = [np.cumsum([x[i*4+n] for i in range(13)]) for n in range(4)]
def findmin(x, v):
    try:
        return x.index(v)
    except:
        return 9999

y = [findmin(list(y[i]), 4)for i in range(4)]
y.index(min(y))