当前位置:网站首页>[pyGame practice] playing poker? Win or lose? This card game makes me forget to eat and sleep.
[pyGame practice] playing poker? Win or lose? This card game makes me forget to eat and sleep.
2022-07-23 15:22:00 【Gu Muzi acridine】
Introduction
Things I could play with when I was a child , It is far less abundant than now , Playing poker is one of them .
what “ Three dozen ha ”、“ Have bumper harvest ”、“ Two hundred and four ” ah ! I don't know what all your dialect playing methods are called , I'm from my hometown in Hunan .

My words don't often play cards , When I was in college, I had a cell phone, and then I went to a dormitory to play online occasionally .
Years of work , The times of playing cards with friends can be counted with one hand .
BUT Every year, I go back to my hometown in Hunan for the Spring Festival , I can't help playing mahjong and cards with my relatives and having a Play Naughty together , This is an unavoidable method
Then ~( Of course, if you play cards, don't indulge , You all know .....)
Today, Xiaobian will write a Poker games, Ba ! I hope you like it , You can practice with the code first ~
Complete material for all articles + The source code is in

Text
One 、 Project introduction
1) Player module specifications
Use a length of 2 The string of represents a card :(D,C,H,S) + (A,2,3,4,5,6,7,8,9,0,J,Q,K) use "jk"、"JK" , respectively,
It means Xiao Wang 、 King The sequence of the game is counterclockwise The role is represented by a string .
("banker","banker_opposite","banker_left","banker_right") Respectively means the dealer 、 The opposite of the banker 、 zhuang
On the left side of home 、 The right side of the dealer Don't consider throwing cards , Use python Design .
player Module design :
1.1 Design function :
de add_card_and_is_snatch(current_card): It means that the player touches a card curernt_card, And choose whether
Rob the village . current_card Represents a card ( The length is 2 String ) If you rob the village , Returns the string of the corresponding card , otherwise
return '' Design function : def add_left_cards(left_cards): Only the dealer can use it , Indicates that the card is
left_cards,left_cards Is a length of 2 Of string list You need to return the card that the player is ready to bury in the bottom card , Return value
It is also a length of 2 Of string list .1.2 Design function :
def finish_one_round(current_turn_out_cards): It means that this round of cards is over , Players are told about this round
Licensing information , current_turn_out_cards Represents a triple (order,role,card) Of list, Every triple table
Show the card information of someone before you play this round , order It's an integer , Indicates the order of cards (1,2,3,4)
role Is a string , Said role ("banker","banker_opposite","banker_left","banker_right")
card It's a card .1.3 Design function :
def set_main_value(main_value): Players are told what the main face value is ,main_value Is a character
(A,2,3,4,5,6,7,8,9,0,J,Q,K) Represents the principal face value .1.4 Design function :
def set_main_color(main_color): Players are told what the main decor is ,main_color Is a character (D,C,H,S)
Indicates the main Decor .1.5 Design function :
def player_init(): Now start a new game , And initialize related variables Design function : def
set_role(role): Players are told what their role is ,role Is a string
("banker","banker_opposite","banker_left","banker_right") .1.6 Design function :
def play_out_cards(turn, current_turn_out_cards): turn Indicates the current round of cards ,
current_turn_out_cards Represents a triple (order,role,card) Of list, Each triplet represents this round of you
Information about the cards played by someone before playing , order It's an integer , Indicates the order of cards (1,2,3,4) role It's a word
Fu string , Said role ("banker","banker_opposite","banker_left","banker_right") card It's a card
The function needs to return the decided card .1.7 Design function :
def show_cards(): You need to return the current player's hand ( The length is 2 Of string list) .2)UI explain
1.1 import UI
1.2 Add code in the game initialization module :
# Initialize pygame
pygame.init()
setting = UI.Setting()
SCREEN_WIDTH, SCREEN_HEIGHT = setting.SCREEN_WIDTH, setting.SCREEN_HEIGHT
x, y = 150, 60
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption(" upgrade ")
background = UI.Background(screen, setting)1.3 Use interface description :
a) initial(self): Each round of game initialization function , Reset card set and other functions ;
b) add_card(self, card, turn): Licensing stage ,turn For the purpose of licensing the player's position 0-3,card Deal for
value ;
c) add_cards_over(self, inputs, outputs, main_color, master): Call this... After the licensing phase ends
function ;input For the dealer 6 Zhang Di card ,output For the bottom of the banker 6 card ;mian_color This is the head of the Bureau
color ,master It's the position of the dealer player 0-3;
d) push_cards(self, cards, turn): The stage of playing cards , The meaning of the function is turn Players play cards,cards by
card list , That is, all the cards played value ;
e) turn_over(self): The end of a round ; Clear all cards played by four players ;
f) update_point (self, point, level1, level2): The end of a round , Update the current score and grade ;point
Score for the current ,level1 Play for things The current level of home ,level2 It is the current level of North and South players .1.4 Pass variable description :
a) card: (D,C,H,S) + (A,2,3,4,5,6,7,8,9,0,J,Q,K) use "jk"、"JK" It means Xiao Wang 、 King Spade -
spade Heart -heart Fang Kuai -diamond Grass flower -club Spade 3 : card = ‘s3’
b) turn: Integers 0-3 (0, 1, 2, 3) Equivalent to ('East', 'North', 'West', 'South')Two 、 Running environment
1) The environment used by Xiaobian :Python3、Pycharm Community Edition 、Pygame The module is not included one by one
Show it .
Module installation :pip install -i https://pypi.douban.com/simple/+ Module name 2) material ( Pictures, etc )
background 、 Playing cards, etc ( Too many pictures show only part of the material )

3、 ... and 、 Code display
Reference resources demo: judge For the referee module ,myPlayer by AI The player , function judge.py.
The main program judge.py:
# coding:utf-8
import random
import pygame
import os
import time
import myPlayer as p1
import myPlayer as p2
import myPlayer as p3
import myPlayer as p4
import UI
# H S D C
# Heart Spade Diamond Club
# K - King 0 - small king , 1 - big king
class Judge():
def __init__(self):
self.cards = None
self.players = []
self.players.append(p1.Player('East'))
self.players.append(p2.Player('North'))
self.players.append(p3.Player('West'))
self.players.append(p4.Player('South'))
self.level = [2,2]
self.master = None
self.false = [0 , 0, 0, 0] # Record the number of mistakes each person makes
self.main_color = None
self.main_num = 2
self.loser = 0 # Record the party who made the mistake first , The final decision is to lose
def covert(self, s):
if s == 1 or s == 14:
return 'A'
elif s < 10:
return str(s)
elif s == 10:
return '0'
elif s == 11:
return 'J'
elif s == 12:
return 'Q'
elif s == 13:
return 'K'
# New game , initialization
def new_game(self, background):
self.main_color = None
self.false = [0 , 0, 0, 0]
self.loser = -1
self.bottom = []
self.point = 0
self.biggest = [0, 0, 0, 0]
self.player_cards = [[],[],[],[]]
cards = self.create_card()
random.shuffle(cards)
for i in range(4):
self.players[i].player_init()
l = ['a', 'b', 'c', 'd']
for i in range(4):
self.players[i].set_role(l[i])
for y in self.players:
#y.initial_new_game()
y.set_main_value(self.covert(self.main_num))
# Licensing
turn = 0
for i in range(48):
x = self.players[turn].add_card_and_is_snatch(cards[i])
self.player_cards[turn].append(cards[i])
if x != '' and x[1] == self.covert(self.main_num) and self.main_color == None:
self.main_color = x[0]
if self.master == None:
self.master = turn
for y in self.players:
y.set_main_color(self.main_color)
elif x == '':
None
else:
self.false[turn] += 1
if self.loser == -1:
self.loser = turn
background.add_card(cards[i], turn)
turn += 1
turn %= 4
if self.main_color == None:
col = ['H', 'C', 'D', 'S']
self.main_color = random.choice(col)
for y in self.players:
y.set_main_color(self.main_color)
if self.master == None:
self.master = random.randint(0, 3)
self.bottom = self.players[self.master].add_left_cards(cards[48:])
for x in cards[48:]:
self.player_cards[self.master].append(x)
if len(self.bottom) != 6:
self.false[self.master] += 1
if self.loser == -1:
self.loser = self.master
else:
for x in self.bottom:
if x in self.player_cards[self.master]:
self.player_cards[self.master].remove(x)
else:
if self.loser == -1:
self.loser = self.master
background.add_cards_over(cards[48:], self.bottom, self.main_color, self.master)
''' Generate a deck of cards '''
def create_card(self):
colors = ['H', 'S', 'D', 'C']
nums = 'A234567890JQK'
cards = []
for color in colors:
for i in range(13):
c = color + nums[i]
cards.append(c)
cards.append('jk')
cards.append('JK')
return cards
# Judge whether the player has the suit in his hand ,y Indicates whether the main card is to be played in this round
def find_color(self,p_cards, this_color, y):
for x in p_cards:
if y == True:
if x == this_color or x == 'jk' or x=='JK' or x ==self.covert(self.main_num):
return True
else:
if x == this_color:
return True
return False
# a First out , Judge b Whether the number of is greater than a
def is_big(self,b, a):
num_order = ['A', 'K', 'Q', 'J', '0', '9','8','7','6','5','4','3','2']
for x in num_order:
if x == a:
return False
if x == b:
return True
# Judge a Is it greater than b,a First out
def is_bigger(self,a , b, this_color):
if a == 'JK':
return True
if a == 'jk':
if b == 'JK':
return False
else :
return True
if a[1] == self.main_num:
if b == 'jk' or b=='JK' or b[0]==self.main_color and b[1]==self.covert(self.main_num):
return False
else:
return True
if a[0] == self.main_color:
if b =='jk' or b=='JK' or b[1]==self.covert(self.main_num) or b[0]==self.main_color and self.is_big(b[1],a[1]):
return False
else:
return True
if a[0] == this_color:
if b =='jk' or b=='JK' or b[1]==self.covert(self.main_num) or b[0]==self.main_color or b[0]==this_color and self.is_big(b[1],a[1]):
return False
else:
return True
if b =='jk' or b=='JK' or b[1]==self.covert(self.main_num) or b[0]==self.main_color or b[0]==this_color or self.is_big(b[1],a[1]):
return False
else:
return True
def add_points(self, cards):
for x in cards:
if x[1] == '5':
self.point += 5
elif x[1] == '0' or x[1] == 'K':
self.point += 10
# Judge who played the biggest card in a round , Whether to add points
def get_max_index_and_add_points(self, cards, turn, this_color):
index = 0
max_card = cards[0]
for i in range(1,4):
if not self.is_bigger(max_card, cards[i], this_color):
index = i
max_card = cards[i]
if index % 2 != self.master % 2:
self.add_points(cards)
return (turn + index) % 4
def is_a_card(self, s):
if s == 'jk' or s == 'JK':
return True
if s[0] in ['H', 'S', 'D', 'C'] and s[1] in ['A', 'K', 'Q', 'J', '0', '9','8','7','6','5','4','3','2']:
return True
else:
return False
# Play cards to the end
def run_game(self, background):
turn = self.master
for i in range(12):
UI.check_events()
this_turn_cards = []
first_card = self.players[turn].play_out_cards(0 , this_turn_cards)
this_turn_cards.append(first_card)
if first_card in self.player_cards[turn]:
self.player_cards[turn].remove(first_card)
else:
if self.loser == -1:
self.loser = turn
background.push_cards([first_card], turn)
turn += 1
turn %= 4
if not self.is_a_card(first_card):
print('Please input a card')
self.false[turn] += 1
if first_card == 'jk' or first_card == 'JK' or first_card[0]==self.main_color or first_card[1]==self.covert(self.main_num):
this_color = self.main_color
else:
this_color = first_card[0]
for j in range(1, 4):
a_cards = self.players[turn].play_out_cards(j, this_turn_cards)
if a_cards in self.player_cards[turn]:
self.player_cards[turn].remove(a_cards)
else:
if self.loser == -1:
self.loser = turn
this_turn_cards.append(a_cards)
#p_cards = self.players[turn].show_cards()
p_cards = self.player_cards[turn]
#print('a_cards = ', a_cards) ###############
if a_cards[0] == this_color:
None
elif this_color == self.main_color:
if a_cards == 'jk' or a_cards == 'JK' or a_cards[1]==self.covert(self.main_num):
None
elif not self.find_color(p_cards, this_color, True):
None
else:
self.false[turn] += 1
if self.loser == -1:
self.loser = turn
else:
if self.find_color(p_cards, this_color, False):
self.false[turn] += 1
if self.loser == -1:
self.loser = turn
background.push_cards([a_cards], turn)
turn += 1
turn %= 4
# Tell all players the cards in this round
for i in range(4):
self.players[i].finish_one_round(this_turn_cards, (i + turn ) % 4 )
max_index = self.get_max_index_and_add_points(this_turn_cards, turn, this_color)
turn = max_index
self.biggest[max_index] += 1
background.update_point(self.point, self.level[0], self.level[1])
background.turn_over()
# Whether the cards are scored
if turn % 2 != self.master % 2:
self.add_points(self.bottom)
if self.loser % 2 == self.master:
self.main_num = self.level[(self.master + 1) % 2]
self.master = (self.master + 1) % 2
elif self.loser % 2 != self.master and self.loser != -1:
self.level[self.master % 2] += 1
self.main_num = self.level[self.master % 2]
if self.master == self.master % 2:
self.master += 2
else:
self.master %= 2
elif self.point < 40:
self.level[self.master % 2] += 1
self.main_num = self.level[self.master % 2]
if self.master == self.master % 2:
self.master += 2
else:
self.master %= 2
else:
self.main_num = self.level[(self.master + 1) % 2]
self.master = (self.master + 1) % 2
# print(self.biggest)
if __name__ == '__main__':
# Initialize pygame
pygame.init()
setting = UI.Setting()
SCREEN_WIDTH, SCREEN_HEIGHT = setting.SCREEN_WIDTH, setting.SCREEN_HEIGHT
x, y = 150, 60
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption(" upgrade ")
background = UI.Background(screen, setting)
judge = Judge()
#judge.level = [12,13]
while True:
time.sleep(0.5)
judge.new_game(background)
judge.run_game(background)
background.initial()
if judge.level[0] == 13 or judge.level[1] == 13:
print(judge.level)
if judge.level[0] > judge.level[1]:
print('East and West WIN')
else:
print('South and North WIN')
break
Four 、 Effect display

Run a screenshot ——

summary
All right, all right ! This simple little game ends here , See whose it is here DNA It's moving ? Xi xi xi
A friendly reminder : Small gambling , Gambling hurts the body and feelings . Enjoy playing cards , But remember that losing heart is too heavy !
The old rule of spreading material, complete source code and others who pay attention to me all know it. Go and get it by yourself
Complete free source code collection office : Find me ! Public at the end of the article hao You can get it by yourself , Didi, I can also !
I recommend previous articles ——
project 1.0 Super Marie
project 1.1 Mine clearance
project 1.4 Fruit ninja
project 2.0 Connected to the Internet 、 Man machine Gobang game
project 2.1 Universe battle shooting game
A summary of the article ——
project 1.0 Python—2021 | Summary of existing articles | Continuous updating , Just read this article directly
( More + The source code is summarized in the article !! Welcome to ~)

![]()
边栏推荐
- OPNsense – 多功能高可靠易使用的防火墙(二)
- Skills to learn before going to primary school
- Clickhouse, let the query fly!!!
- [machine learning basics] unsupervised learning (5) -- generation model
- Jsd-2204 session management filter day19
- go : gin Urlencoded 格式
- STL map属性
- 第一篇 项目基本情况介绍
- RTA一种广告精准投放的新玩法?
- 读写锁ReadWriteLock还是不够快?再试试S…
猜你喜欢

7.13WEB安全作业
[email protected]]#颜色"/>修改ssh命令行[[email protected]]#颜色

Getting started with Prometheus (III)

7.13web safety operation

Redis布隆过滤器

BGP联邦实验

Dynamic planning - force buckle

Deep understanding of CAS (spin lock)

易基因|靶基因DNA甲基化测序(Target-BS)

Selenium in the crawler realizes automatic collection of CSDN bloggers' articles
随机推荐
Part II how to design an RBAC authority system
【7.16】代码源 -【数组划分】【拆拆】【选数2】【最大公约数】
Solve the problem that kotlin writes the Android project compilation report execution failed for task ': app:kaptdebugkotlin'. Exception
centos7 中彻底卸载mysql
基于PSO优化的多目标最优值求解matlab仿真
Shell脚本案例---3
[solve the exception] Flink uploads the jar package to the cluster environment, and the operation report does not serialize the exception
Uniapp realizes horizontal click and slide menu
xlswriter - excel导出
turbo编译码误码率性能matlab仿真
基于simulink的双闭环矢量控制的电压型PWM整流器仿真
494. Objectives and
安全7.18作业
Multiple backpacks!
Redis bloom filter
[200 opencv routines] 225. Fourier descriptor for feature extraction
Deep learning single image 3D face reconstruction
Start other independent programs through fmmonitoredprocess in unreal
800V高压快充落地进程加快均胜电子获5亿欧元项目定点
The problem of double type precision loss and its solution