Fundamentals 12 min read

How to Build a Python Card Game: Simulating ‘ZhaJinHua’ for Five Players

This article walks through creating a Python program that simulates the popular Chinese card game ZhaJinHua, covering deck construction, random dealing to five players, hand‑type evaluation, scoring, and ranking, with complete source code and a concise explanation of each step.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Build a Python Card Game: Simulating ‘ZhaJinHua’ for Five Players

Hello, I am a Python enthusiast.

Preface

"ZhaJinHua" (also known as Three‑Card Brag) is a widely‑played Chinese card game where each player receives three cards and the hands are compared according to a specific hierarchy. A fan in a Python group posted a challenge to implement this game in Python.

1. Idea

The solution requires constructing a standard 52‑card deck (excluding jokers), dealing three cards to each of five players, determining each hand’s type, assigning scores based on the hierarchy Leopard > Straight Flush > Straight > Pair > High Card , and finally ranking the players.

2. Solution

Below is the original implementation that follows the described steps.

# -*- coding: utf-8 -*-
import random

puke = []  # store the deck
num_list = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
hua_list = ['梅花','红桃','黑桃','方块']
sort_dic = {'2':0,'3':1,'4':2,'5':3,'6':4,'7':5,'8':6,'9':7,'10':8,'J':9,'Q':10,'K':11,'A':12,
           '对子':15,'顺子':30,'顺金':60,'豹子':100}
count_new_list = []
count_dic = {}
# build deck
for hua in hua_list:
    for num in num_list:
        puke.append(hua+num)
player_dic = {'玩家1':[],'玩家2':[],'玩家3':[],'玩家4':[],'玩家5':[]}
# deal cards
for key in player_dic:
    plate = random.sample(puke,3)
    player_dic[key] = plate
    for i in plate:
        puke.remove(i)
print(player_dic)

def paixing(list1):
    num=[]; huase=[]
    for i in list1:
        a=i[2:]; b=i[:2]
        num.append(a); huase.append(b)
    return num,huase

def sort(num):
    new_num=[sort_dic[i] for i in num]
    new_num=sorted(new_num)
    sort_list2=[]
    for new in new_num:
        sort_list2.append([k for k,v in sort_dic.items() if v==new])
    list1=[]
    for m in sort_list2:
        for n in m:
            list1.append(n)
    return list1

def count(num,huase):
    a=0
    base_count=sort_dic[num[0]]+sort_dic[num[1]]+sort_dic[num[2]]
    if num[0]==num[1]==num[2]:
        a=base_count+sort_dic['豹子']
    elif (sort_dic[num[0]]+1==sort_dic[num[1]] and sort_dic[num[2]]-1==sort_dic[num[1]]) and (huase[0]==huase[1] and huase[1]==huase[2]):
        a=base_count+sort_dic['顺金']
    elif (sort_dic[num[0]]+1==sort_dic[num[1]] and sort_dic[num[2]]-1==sort_dic[num[1]]) and (huase[0]!=huase[1] or huase[1]!=huase[2]):
        a=base_count+sort_dic['顺子']
    elif (num[0]==num[1] and num[1]!=num[2]) or (num[1]==num[2] and num[0]!=num[1]) or (num[0]==num[2] and num[1]!=num[0]):
        a=base_count+sort_dic['对子']
    else:
        a=base_count
    return a

def compare(count_dic):
    d=list(zip(count_dic.values(),count_dic.keys()))
    return sorted(d,reverse=True)

for key,value in player_dic.items():
    num,huase=paixing(value)
    num=sort(num)
    count1=count(num,huase)
    count_dic[key]=count1
    print(key+"的牌为:"+str(value))
    count_new_list=compare(count_dic)
print('最终排名:' + "\t" + count_new_list[0][1] + "第一名" + "\t" + count_new_list[1][1] + "第二名" + "\t" + count_new_list[2][1] + "第三名" + "\t" + count_new_list[3][1] + "第四名" + "\t" + count_new_list[4][1] + "第五名")

Running the program produces an output similar to the screenshot below.

Game result
Game result

An improved version removes redundant code, uses clearer variable names, and simplifies the logic.

# -*- coding: utf-8 -*-
import random

puke = []
num_list = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
hua_list = ['梅花','红桃','黑桃','方块']
sort_dic = {'2':0,'3':1,'4':2,'5':3,'6':4,'7':5,'8':6,'9':7,'10':8,'J':9,'Q':10,'K':11,'A':12,
           '对子':15,'顺子':30,'顺金':60,'豹子':100}
count_new_list = []
count_dic = {}
for hua in hua_list:
    for num in num_list:
        puke.append(hua+num)
player_dic = {'玩家1':[],'玩家2':[],'玩家3':[],'玩家4':[],'玩家5':[]}
print(len(puke))
for key in player_dic:
    for _ in range(3):
        plate = random.sample(puke,3)
        player_dic[key] = plate
        for i in plate:
            puke.remove(i)
print(player_dic)

def paixing(list1):
    num=[]; huase=[]
    for data in list1:
        huase_type=data[:2]
        pai_number=data[2:]
        num.append(pai_number)
        huase.append(huase_type)
    return num,huase

def get_score(num,huase):
    base_count=sort_dic[num[0]]+sort_dic[num[1]]+sort_dic[num[2]]
    if num[0]==num[1]==num[2]:
        score=base_count+sort_dic['豹子']
    elif (sort_dic[num[0]]+1==sort_dic[num[1]] and sort_dic[num[2]]-1==sort_dic[num[1]]) and (huase[0]==huase[1] and huase[1]==huase[2]):
        score=base_count+sort_dic['顺金']
    elif (sort_dic[num[0]]+1==sort_dic[num[1]] and sort_dic[num[2]]-1==sort_dic[num[1]]) and (huase[0]!=huase[1] or huase[1]!=huase[2]):
        score=base_count+sort_dic['顺子']
    elif (num[0]==num[1] and num[1]!=num[2]) or (num[1]==num[2] and num[0]!=num[1]) or (num[0]==num[2] and num[1]!=num[0]):
        score=base_count+sort_dic['对子']
    else:
        score=base_count
    return score

if __name__=='__main__':
    for key,value in player_dic.items():
        num,huase=paixing(value)
        num=sorted(num)
        score=get_score(num,huase)
        count_dic[key]=score
        print(key+"的牌为:"+str(value))
        count_new_list=sorted(zip(count_dic.values(),count_dic.keys()),reverse=True)
    print("最终排名:")
    for i in range(len(count_new_list)):
        print(count_new_list[i][1]+'\t',end='')

3. Conclusion

The script demonstrates how basic Python constructs—lists, dictionaries, functions, and the random module—can be combined to model a complete card‑game workflow, from deck generation to hand evaluation and final ranking.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmsimulationPythonListdictionaryrandomcard gamepoker
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.