I tried playing mahjong with Python (single mahjong edition)

Overview

I am making my own program that can play mahjong with Python.

This time, it ’s a mahjong program for one person, just cutting the tiles

The ultimate goal is to gradually add functions and create Mahjong AI.

rule

--Manko (man's), tube (pins), cordo (swords) with numbers from 1 to 9 written on it A total of 136 tiles, including 34 types of tiles with the words "East", "South", "West", "North", "White", "Departure", and "Middle", are used. ――The player holds 13 tiles (hand tiles), draws one tile from the remaining tiles (mountain), and replaces it with one hand tile. It is a game that clears the game when the Tehai meets certain conditions. ――14 tiles in the mountain are called king tiles, and the player cannot check the contents or draw tiles from them. Depending on the king's tile, it may not be possible to go up.

Implementation

The source code looks like this

#!/usr/bin/env python
#Mahjong program
#Currently, only one mahjong can be cut by cutting
#Unimplemented:Agari judgment,Hand judgment,Squeal,river,
from enum import Enum
import sys
import random
import datetime


class Pai(Enum):  #Tile class Defines the type of tile
    #Manko
    m1 = 'Ichiman'
    m2 = 'Niman'
    m3 = 'Sanman'
    m4 = 'Shima'
    m5 = 'Goman'
    m6 = 'Rokuman'
    m7 = 'Nanaman'
    m8 = 'Hachiman'
    m9 = 'Kuman'
    #Tsutsuko
    p1 = 'One cylinder'
    p2 = 'Two cylinders'
    p3 = 'Three cylinders'
    p4 = 'Four cylinders'
    p5 = 'Five cylinders'
    p6 = 'Six cylinders'
    p7 = 'Seven cylinders'
    p8 = 'Eight cylinders'
    p9 = 'Nine cylinders'
    #Cord
    s1 = 'One search'
    s2 = 'Two ropes'
    s3 = 'Three ropes'
    s4 = 'Four ropes'
    s5 = 'Five ropes'
    s6 = 'Six ropes'
    s7 = 'Seven ropes'
    s8 = 'Eight ropes'
    s9 = 'Nine ropes'
    #Tile
    z1 = 'east'
    z2 = 'South'
    z3 = 'West'
    z4 = 'North'
    z5 = 'White'
    z6 = 'Departure'
    z7 = 'During ~'

    def __str__(self):  #Define the display method in the print function
        return self.value


class Yama:  #Management of mountain class mountains, kings, etc.

    def __init__(self):
        self.yama = [*Pai] * 4  #Mountain initialization
        random.shuffle(self.yama)

        self.wanpai = self.yama[0:14]  #Initialization of the king
        del self.yama[0:14]

    def tsumo(self):  #Return the last tile of the mountain
        return self.yama.pop()

    def haipai(self):  #13 Give the tile to the player
        haipai = self.yama[0:13]
        del self.yama[0:13]
        return haipai


class Player:  #Player class Tehai management

    def __init__(self):
        self.tehai = []

    def haipai(self,pai):  #Take 13 tiles from the mountain at the beginning of the game
        self.tehai = pai
        self.tehai.sort(key = lambda x: str(x.name))
        print('Distribution\n',*self.tehai,'\n')

    def tsumo(self,pai):  #Take one tile from the mountain and discard one from the hand tile
        print(*self.tehai, 'Tsumo', pai)
        self.tehai.append(pai)
        sutehai = self.tehai.pop(int(input()))
        #Specify the tile to cut by keyboard input
        self.tehai.sort(key = lambda x: str(x.name))
        print('Hit',sutehai,'\n')
        return sutehai
        

random.seed(datetime.datetime.now())
yama1 = Yama()  #Mountain generation
player1 = Player()  #Player generation
player1.haipai(yama1.haipai())
while(len(yama1.yama)!=0):  #Until the number of tiles in the mountain reaches 0
   player1.tsumo(yama1.tsumo())  #Cut one piece

(Edit history)

--2021/01/01 I learned about the existence of the official Python coding standard PEP8 and decided to modify it for readability. How to delete encoding settings, write import, etc.

――At first, I wrote the part where the tiles are generated in the list comprehensive notation, but I could write it smarter by using * (asterisk).

self.yama = [pai for pai in Pai] * 4  #List comprehensive notation

self.yama = [*Pai] * 4  #Notation using an asterisk
# [Pai.m1,Pai.m2,...Pai.z7] *Same meaning as 4

--When you output the Tehai in the top module, you bothered to write pai.value, but by overloading the special method __str__, you could define the output in the print statement.

class Pai:
    def __str__(self):
        return self.value

tehai = [Pai.m1,Pai.p2,Pai.s3]
print(*tehai)  # print(tehai[0],tehai[1],tehai[2])Same meaning as
#Execution result
#Ichiman, two cylinders, three ropes

Execution result

キャプチャ.PNG

I tried to run it on the command prompt. I think that you can display, sort, and replace the tiles normally.

Task

――It is a little difficult to see because the hand tiles are displayed in letters. --Agari judgment is not implemented

I will write these two points in the next article.

At the end

I tried it to practice python. This is my first time to publish the code I wrote, so I would be grateful if you could point it out in the comments if there is something to dig into.

Reference article

How to write python https://note.nkmk.me/ I referred to this site.

Recommended Posts

I tried playing mahjong with Python (single mahjong edition)
I tried L-Chika with Raspberry Pi 4 (Python edition)
I tried fp-growth with python
I tried scraping with Python
I tried gRPC with Python
I tried scraping with python
I tried web scraping with python.
I tried running prolog with python 3.8.2.
I tried SMTP communication with Python
I tried sending an email with python.
I tried non-photorealistic rendering with Python + opencv
I tried a functional language with Python
I tried playing with the image with Pillow
I tried scraping Yahoo weather (Python edition)
#I tried something like Vlookup with Python # 2
I tried to solve the ant book beginner's edition with python
[System trade] I tried playing with Stochastic Oscillator by decomposing with python ♬
I tried "smoothing" the image with Python + OpenCV
I tried hundreds of millions of SQLite with python
I tried "differentiating" the image with Python + OpenCV
I tried playing a typing game in Python
I tried Python> autopep8
I tried playing with PartiQL and MongoDB connected
I tried Jacobian and partial differential with python
I tried to get CloudWatch data with Python
I tried using mecab with python2.7, ruby2.3, php7
I tried function synthesis and curry with python
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried "binarizing" the image with Python + OpenCV
I tried running faiss with python, Go, Rust
I tried running Deep Floor Plan with Python 3.6.10.
I tried sending an email with SendGrid + Python
I tried Python> decorator
I tried playing with the calculator on tkinter
I tried to implement Minesweeper on terminal with python
I tried to get started with blender python script_Part 01
I tried to touch the CSV file with Python
I tried to draw a route map with Python
[OpenCV / Python] I tried image analysis of cells with OpenCV
I tried to solve the soma cube with python
I tried to get started with blender python script_Part 02
I tried to implement an artificial perceptron with python
I tried LeetCode every day 136. Single Number (Python, Go)
I tried to automatically generate a password with Python3
Mayungo's Python Learning Episode 1: I tried printing with print
I tried to solve the problem with Python Vol.1
I tried to analyze J League data with Python
[Introduction to AWS] I tried playing with voice-text conversion ♪
I tried "morphology conversion" of images with Python + OpenCV
I tried hitting the API with echonest's python client
I tried to solve AOJ's number theory with Python
I tried Learning-to-Rank with Elasticsearch!
I made blackjack with python!
I tried clustering with PyCaret
Error when playing with python
I tried Python C extension
[Python] I tried using OpenPose
I made blackjack with Python.
I made wordcloud with Python.
I tried deploying Kubernetes Pods / Helm Chart with Pulumi (Python)
I tried to find the entropy of the image with python