2023年2月1日 星期三

python for pypoker 普克遊戲設計 範例1

 


class Card():

    def __init__(self, suit, rank):

        self.suit = suit

        self.rank = rank

    

    def __repr__(self):

        return f"{self.rank} of {self.suit}"


class Deck():

    def __init__(self):

        suits = ["Hearts", "Diamonds", "Spades", "Clubs"]

        ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

        self.cards = [Card(suit, rank) for suit in suits for rank in ranks]

    

    def __repr__(self):

        return f"Deck of {self.count()} cards"

    

    def count(self):

        return len(self.cards)

    

    def _deal(self, count):

        count = min(count, self.count())

        return [self.cards.pop() for _ in range(count)]

    

    def deal_card(self):

        return self._deal(1)[0]

    

    def deal_hand(self, hand_size):

        return self._deal(hand_size)

    

    def shuffle(self):

        if self.count() < 52:

            raise ValueError("Only full decks can be shuffled")

        

        #self.shuffle(self.cards)

        return self


def main():

    deck = Deck()

    deck.shuffle()


    hand = deck.deal_hand(5)

    print(hand)

    hand = deck.deal_hand(5)

    print(hand)



if __name__ == '__main__':

    main()

python for MYSQL CUDA 操作套件 範例

#python demo code for MySQL drive 

#使用 pymysql 套件

import pymysql

#############################################################

class Database:

    def __init__(self, host, user, password, database, charset='utf8mb4'):

        self.conn = pymysql.connect(

            host=host,

            user=user,

            password=password,

            database=database,

            charset=charset

        )

        self.cursor = self.conn.cursor()


    def insert(self, table, data):

        # Build the INSERT statement

        columns = ', '.join(data.keys())

        values = ', '.join("'" + str(value) + "'" for value in data.values())

        sql = f"INSERT INTO {table} ({columns}) VALUES ({values})"


        # Execute the INSERT statement

        self.cursor.execute(sql)

        self.conn.commit()


    def select(self, table, conditions=None):

        # Build the SELECT statement

        sql = f"SELECT * FROM {table}"

        if conditions:

            sql += " WHERE " + " AND ".join([f"{key}='{value}'" for key, value in conditions.items()])


        # Execute the SELECT statement

        self.cursor.execute(sql)

        rows = self.cursor.fetchall()


        return rows


    def update(self, table, data, conditions):

        # Build the UPDATE statement

        set_values = ', '.join([f"{key}='{value}'" for key, value in data.items()])

        where_conditions = " AND ".join([f"{key}='{value}'" for key, value in conditions.items()])

        sql = f"UPDATE {table} SET {set_values} WHERE {where_conditions}"


        # Execute the UPDATE statement

        self.cursor.execute(sql)

        self.conn.commit()


    def delete(self, table, conditions):

        # Build the DELETE statement

        where_conditions = " AND ".join([f"{key}='{value}'" for key, value in conditions.items()])

        sql = f"DELETE FROM {table} WHERE {where_conditions}"


        # Execute the DELETE statement

        self.cursor.execute(sql)

        self.conn.commit()


    def close(self):

        self.cursor.close()

        self.conn.close()


########################################################

python class 使用範例

# Create an instance of the Database class

db = Database(host='hostname', user='username', password='password', database='database_name')


# Insert data into the database

data = {

    'column1': 'value1',

    'column2': 'value2',

    'column3': 'value3'

}

db.insert('table_name', data)


# Select data from the database

rows = db.select('table_name')

for row in rows:

    print(row)


# Update data in the database

data = {

    'column2':


2022年2月10日 星期四

Mosquitto acl MQTT topic存取權限管理

 

 mosquitto topic 設定ACL(Access Control List)

>>對於 Tpoic 的讀寫 有三種權限
< read , write , readwrite >

>>對於 MQTT client user  管理權限設定有三類

1#General section                 通用user 權限
2#User specific section         指定user 權限
3#Client or user ID section   由登入帳號指定權限

>> 設定格式
1#General section   < 用於不定隨機 登入者之權限管理 >
   以 topic 關鍵字 開頭 定義 指定的topic 相關讀寫權限給 不特定的 登入者 
   但若登入者有登入的 user ID 則不是適用 

 topic read  $SYS/#
 topic write $log/#
 topic readwrite $node/#


2#User specific section    <用於 指定user 權限管理 授權特定管理者帳號的操作> 
    以 user 關鍵字開頭 定義接下來的 topic 權限清單
    相關清單 均為指定之user ID 之權限

 user JOHN
 topic read $USER/#
 topic write $USER/#
 topic readwrite $USER/+/GPIO

3#Client or user ID section   <由登入帳號指定權限 授權使用者帳號 管理操作topic 權限 >
   適用在 以認證方式登入 之 user ID 以  pattern 關鍵字開頭 定義 相關之topic 讀寫權限
   %c  client ID  , %u user ID

 pattern  read   $USER/connect/%c/state
 pattern  write  $USER/connect/%c/data
 pattern  readwrite $USER/device/%u/control


2021年11月16日 星期二

MCU System for Power on & RESET 之前?

 Power on & RESET 之前?

這是個有趣的問題 ? 當應用系統 或 IC MCU 元件模組於初始之前存在的現像為何?

是個得住意的問題 !

因為得考量是否會對週邊或被控制端造成危害

這也是長常常會是不穩定設計的原因!

得有實務經驗及想像力才會去注意的問題!

也不是發生率或良率可以解釋的也是決定品質的關鍵 ! 


有下列幾個看法可以討論: 

1> i/o port 最好是內定input以避免output 使週邊誤動作 

2> watch dog 內定是 on 而非 off 否責 power on 當機誰來 wackup ? 

3> Reset for  "冷開機"  or " 熱開機" 得有分辦及處置能力    

4>週邊控制盡量由電性信號控制反應總比logic signal 快 

5> 週編控制pin 最好 low動作 否責high active 時 idel 時就是耗電!


看看 還有其他經驗歡迎來分享!! 

2020年12月26日 星期六

mpy-cross tool for mpy TEST1

Windows下生成 MicroPython的mpy库

在已安装python环境的电脑上。

1. 打开CMD命令行输入pip install mpy-cross并安装mpy-cross。
$pip install mpy-cross

2. 编写测试文件test.py。

import pyb
import test
while True:
    test.on()
    pyb.delay(100)#延时100ms
    test.off()
    pyb.delay(300)#延时300ms



3. 复制文件路径。
 copy test.py to =&gt; C:\Uusers\CLC\Desktop\test

4. 运用cmd命令(cd + 文件路径),将cmd位置定位到要生成py文件的位置,并执行
&gt;&gt;python -m mpy_cross test.py  命令生成test.mpy文件。

cd C:\Users\CLC\Desktop\test
python -m mpy_cross test.py


5. 成功生成test.mpy。



參考來源
https://makeblock-micropython-api.readthedocs.io/en/latest/tutorial/precompiled_to_mpy.html

接触过Python语言的人都知道,Python可以编译成.pyc文件,它是一种二进制文件,可以提高程序的加载速度,同时也是一种保护源代码的有效方法。 
在micropython中,也提供了类似的功能,可以将.py文件编译成.mpy文件。接下来,介绍一下具体的实现步骤。
(本文以 mingw32 工具链为例, 使用小程作为目标主板)

搭建micropython编译环境
注意: 在不同的系统环境以及不同的目标主板,micropython的开发环境安装是有差别的,
这里仅以乐鑫esp32的mingw32工具链作为示意。我们需要用到它的 xtensa-esp32-elf

参考乐鑫 设置工具链,以 windows系统为例,可以从乐鑫的官网下载 Windows all-in-one工具链 &amp; MSYS2 zip包,将zip文件解压缩到C盘的根目录(也可以是其他一些位置,但本文档假定为 C:\ ),
它将创建一个带有预先准备好的环境的msys32目录。
下载micropython源码包到本地,我下载到了G盘的根目录下。
生成mpy文件



执行msys32目录中的 mingw32.exe 切换到 /g/micropython/mpy-cross 目录执行make,编译生成mpy-cross工具。
../_images/16.png ../_images/23.png
在mpy-cross目录新建一下main.py文件,以小程为例,写一个测试程序用于验证。

import codey
import time

codey.led.show(2555,255,255)
time.sleep(2)
codey.led.off()
time.sleep(2)
while True:
    codey.led.set_red(255)
    time.sleep(1)
    codey.led.set_green(255)
    time.sleep(1)
    codey.led.set_blue(255)
    time.sleep(1)
    codey.led.off()
    time.sleep(1)

执行编译mpy文件的命令。
其他相关功能可查看同目录下的README.md文件。

命令执行成功后,你就能发现同目录下出现了一个main.mpy文件。
../_images/31.png
将 main.mpy 文件拷贝放到小程的flash中,如果是 main文件名的话,小程会自动运行。
烧录 *.py 或者 *.mpy 文件的说明见
添加自定义类库或者代码文件

2020年2月6日 星期四

Free TOOL 免費的工具軟體


VirtualBox => 練習安裝 server 模擬器工具
https://www.virtualbox.org/

AynDesk => 遠端 控制的 TOOL
https://anydesk.com/

Visual Studio Code => 最佳 IDE tool
https://code.visualstudio.com/

NodePad => 最佳的 code EDIT tool
https://notepad-plus-plus.org/downloads/

 MySQL Enterprise Edition=> MySQL  TOOL
https://www.mysql.com/downloads/

NoSQL Manager for MongoDB GUI tool=> 
https://www.mongodbmanager.com/

2019年8月13日 星期二

14 Installing Python3.6 on a Raspberry Pi


14

Installing Python3.6 on a Raspberry Pi

I’m mostly happy with older Python versions, but Python3.6 offers a new method for string generation, the f-string syntax, which i prefer over older methods.
>>Installation
Enter in the terminal

>>Test
Start Python3 with
and enter in the IDE
Links
Realpython f-string syntax introduction: https://realpython.com/python-f-strings/