「python」カテゴリーアーカイブ

支援デバイス Ver6コード

支援デバイスVer6コード

# ODEKAKE Beacon 2018ver4
from microbit import *
#import microbit
import music
import radio
import os

display.scroll('RadV6')
radio.config(channel=10, power=5, length =64)#BLE init  length
radio.on()#BLE ON

btnChk = False
myID = 1
grCount  = 1
grChk = False
oneTime = False
missing = False
timerA = 0
timerB = 0
config = '0,0'#myID,grCount,
tune1 = ["D4:1"]
tune2 = ["E4:1"]
tune3 = ["F4:1"]
timB = 30000
interval = 3000#change to 1sec Feb.16
#IDlist = []
#IDlist2 = []
idDic = {}#ID + time dictionary

#File read
if 'config.txt' in os.listdir():
    with open('config.txt') as my_config:
        conftxt = my_config.read()
        conf = conftxt.split(',')#split by commma to list
        myID = int(conf[0])#myID read and set
        grCount  = int(conf[1])#my grCount read and set

while True:
    if button_a.is_pressed() and button_b.is_pressed():
        ##setingMode
        if btnChk is False:
            btnChk = True
            display.scroll('SET')
            display.scroll('ID=' + str(myID))
        elif btnChk is True:
            btnChk = False #end set mode
            shakeChk = False #end shake mode
            display.show(Image.YES)
    elif button_a.is_pressed():
        if btnChk is True and grChk is False:#ID count mode
            if myID < 20:
                myID += 1
            else:
                myID = 0
            display.scroll('ID=' + str(myID) ,delay = 80)
            #sleep(200)
            #display.clear()
        elif btnChk is False and grChk is True:#group count mode
            if grCount < 20:
               grCount += 1
            else:
                grCount = 0
            display.scroll('GR=' + str(grCount) ,delay = 80)
        else:#normal mode
            if(idDic):
                mList2 = []#initialize and clear
                for k, v in idDic.items():
                    sabun2 = timA - v
                    if sabun2 < 10000:#if 20sec no access
                        mList2.append(k)
                nagasa = int(len(mList2)) + 1#own ID add
                display.scroll(str(nagasa), delay = 80)
                if nagasa == int(grCount):
                    display.scroll('OK!', delay = 80)
                    missing = False
                elif nagasa < int(grCount):
                    display.show(Image.SAD)
                else:
                    display.scroll('??', delay = 100)
                    ##music.play(tune2)
                radio.send(str(myID) + ',' +  str(grCount) + ',nohelp,noset')
            else:
                display.show(Image.DUCK)
            sleep(500)
            display.clear()
            
    elif button_b.is_pressed():
        if btnChk is False and grChk is False:#HELP SEND
            radio.config(power=7)#HelpMode
            radio.send(str(myID) + ',' +  str(grCount) + ',HELP' + ',noset')
            radio.config(power=5)#HelpMode
            display.scroll('HELP')
            sleep(800)
            display.clear()
        elif btnChk is False and grChk is True:#end gr set mode
            btnChk = False #end set mode
            grChk = False #end shake mode
            radio.send(str(myID) + ',' +  str(grCount) + ',nohelp' + ',set')
            display.show(Image.YES)
            sleep(500)
            display.clear()
            #File Save
            saveConfig = str(myID) + ',' + str(grCount)
            with open('config.txt', 'w') as my_conf:#save list my_conf
                my_conf.write(saveConfig)
            #with open('gr.txt', 'w') as gr_id:
            #    gr_id.write(str(grCount))
        elif btnChk is True and grChk is False:#end id set mode
            btnChk = False
            grChk = True#to Group set mode
            display.show(Image.YES)
            sleep(500)
            display.clear()
            display.scroll('GR=' + str(grCount))
    #else:
        #display.scroll('')
        
    #radio message 'myID,grCount,HELP'
    try:
        s = radio.receive()
        if(s):
            sList = s.split(',')#split by , to list
            if sList[2] == 'HELP':
                display.scroll('!')
                music.play(music.BADDY)
                display.show(Image.SAD)
                sleep(3000)
                display.clear()
            elif btnChk is False and grChk is False:
                if sList[3] == 'set':
                    grCount = sList[1]
                    saveConfig = str(myID) + ',' + str(grCount)
                    display.scroll('GR=' + str(grCount))
                    with open('config.txt', 'w') as gr_id:
                        gr_id.write(saveConfig)
                #elif sList[2] == 'nohelp' and sList[3] == 'noset':
                else:#recieve ID check
                    if(not myID == sList[0]):#without own device
                        #time check
                        nowTime = running_time()
                        if(not idDic.get(sList[0])):#not in dictionary add ID and time
                            updValue = {sList[0] : nowTime} 
                            idDic.update(updValue)
                            #music.play(tune3)
                        else:
                            updValue = {sList[0]:nowTime} 
                            idDic.update(updValue)
    except ValueError:#PacketError
        display.show(Image.DUCK)
        radio.reset()
        sleep(200)
        radio.config(channel=10, power=5, length =64)
        display.clear()
        
    #send Beacon interval time            
    timA = running_time()
    if timA > timB:
        #del IDlist[:]#initialaize list
        if btnChk is False and grChk is False:
            radio.send(str(myID) + ',' +  str(grCount) + ',nohelp,noset')
        #display.scroll(str(timA))
            timB = timA + interval
            #display.show(Image.PITCHFORK)
            #sleep(100)
            #display.clear()
            #music.play(tune1)
        
    if(idDic):
        mList = []#initialize and clear
        #mList.clear()#need()?
        for k, v in idDic.items():
            sabun2 = timA - v
            if sabun2 > 200000:#200sec
                mList.append(k)
        
        if(mList):
            
            ids  = ''
            for t in mList:
                ids += t + '_'
            #display.scroll('ID=' + ids + 'missing', delay = 200)
            if missing is False:
                music.play(music.POWER_DOWN)
                missing = True
            display.scroll('ID' + ids + 'missing')
            sleep(5000)

    #sleep(100)

 

micro:bitでDictionary

micro:bitでDictionaryつかえるやん,,,数時間無駄にした

from microbit import *
myDict = {
    'id':1000,
    'id2':2000
}

while True:
    if button_a.is_pressed():
        cat = myDict.get('id')
        display.scroll(str(cat))
        #display.show(Image.HEART)
        sleep(2000)
    if button_b.is_pressed():
        cat = myDict.get('id2')
        display.scroll(str(cat))
        #display.show(Image.HEART)
        sleep(2000)

値を更新と追加は

inu = {'key2':400}
myDict.update(inu)

Dictionaryの中身をチェックするには(Key,Valueの両方)

for k, v in myDict.items():

これでk にkeyがvにValueが入る


スクロール速度速く

display.scroll('cat', delay = 100)

 

micro:bit お出かけサポート

お出かけサポートシステム(ver2くらい あまり動作しない)

# Add your Python code here. E.g.
from microbit import *
#import microbit
import music
import radio
import os

display.scroll('RadioV1')
radio.config(channel=10, power=4)#BLE init
radio.on()#BLE ON

btnChk = False
myID = 1
grCount  = 1
grChk = False
oneTime = False
timerA = 0
timerB = 0
#tune = ["C4:4", "D4:4", "E4:4", "C4:4", "C4:4", "D4:4", "E4:4", "C4:4","E4:4", "F4:4", "G4:8", "E4:4", "F4:4", "G4:8"]
tune2 = ["E4:1"]

#File read
if 'id.txt' in os.listdir():
    with open('id.txt') as my_id:
        myidtxt = my_id.read()
        myID = int(myidtxt) 
if 'gr.txt' in os.listdir():
    with open('gr.txt') as gr_id:
        mygridtxt = gr_id.read()
        grCount  = int(mygridtxt)

while True:
    if button_a.is_pressed() and button_b.is_pressed():
        ##setingMode
        if btnChk is False:
            btnChk = True
            display.scroll('SET')
            display.scroll('ID=' + str(myID))
        elif btnChk is True:
            btnChk = False #end set mode
            shakeChk = False #end shake mode
            display.show(Image.YES)
    elif button_a.is_pressed():
        if btnChk is True and grChk is False:#ID count mode
            if myID < 20:
                myID += 1
            else:
                myID = 0
            display.scroll('ID' + str(myID))
            #sleep(200)
            #display.clear()
        elif btnChk is False and grChk is True:#group count mode
            if grCount < 20:
                grCount += 1
            else:
                grCount = 0
            display.scroll('GR' + str(grCount))
        else:
            music.play(tune2)
    elif button_b.is_pressed():
        if btnChk is False and grChk is False:
            radio.config(power=7)#HelpMode
            radio.send('HELP')
            radio.config(power=4)#HelpMode
            display.scroll('HELP')
            sleep(800)
            display.clear()
        elif btnChk is False and grChk is True:#end gr set mode
            btnChk = False #end set mode
            grChk = False #end shake mode
            radio.send(str(grCount))
            display.show(Image.YES)
            sleep(500)
            display.clear()
            #File Save
            with open('id.txt', 'w') as my_id:
                my_id.write(str(myID))
            with open('gr.txt', 'w') as gr_id:
                gr_id.write(str(grCount))
        if btnChk is True and grChk is False:#end id set mode
            btnChk = False
            grChk = True#to Group set mode
            display.show(Image.YES)
            sleep(500)
            display.clear()
            display.scroll('GR=' + str(grCount))
    #else:
        #display.scroll('')
        
    s = radio.receive()
    if s == 'flash':
        display.scroll('Recieve')
    elif s == 'HELP':
        display.scroll('!')
        music.play(music.RINGTONE)
        display.show(Image.SAD)
        sleep(3000)
        display.clear()
    elif(s):
        if btnChk is False and grChk is False:
            grCount = int(s)
            display.scroll('GR=' + str(grCount))
            with open('gr.txt', 'w') as gr_id:
                gr_id.write(str(grCount))
   # display.show(Image.HEART)
   
   if running_time() > timerA:
       #sendID
    sleep(100)
    

 

MayaでPython(3)

繰り返し処理

以下のコードを新しく作成したファイルに記述し,test2.py で保存せよ

import maya.cmds as mc
for i in range(5):
 mc.polyCube(w=0.5, h=0.5, d=0.5, sx=1, sy=1, sz=1)
 mc.move( i, 0, 0 )

 

ブロック

Pythonの場合,ブロックはインデント(行頭からの空白)で判定する.スペースやタブを使うとよい

import maya.cmds as mc
for i in range(5):
 mc.polyCube(w=0.5, h=0.5, d=0.5, sx=1, sy=1, sz=1)
 mc.move( i, 0, 0 )
 print("for")
print("not for")

実行結果は

for

for

for

for

for

not for となる


実験1

以下のスクリプトを実行してみること.

import maya.cmds as mc
for i in range(10):
 for n in range(10):
  mc.polyCube(w=0.5, h=0.5, d=0.5, sx=1, sy=1, sz=1)
  mc.move( i, 0, n )

in変数である

各Cube間の間隔を広げる場合は, 4行目と5行目の間に i = i +1 を書き足すこと.ブロックの(空白の下図)は前後と同じにすること

ミニ課題

10個×10個×10個のCube又はSphereを生成するスクリプトを作成せよ(下図参考)

 

ミニ課題

1000個のCubeが少しずつ傾いているスクリプトを作成せよ(下図参考)

レンダリング例

戻る

MayaでPython(2)

移動

作成したオブジェクトを移動する

作成したオブジェクトを一旦削除し,スクリプトの最後の行に

mc.move( 3, 3, 3 )

を追加し実行する.

 

その他のコマンド

ポリゴン球を作成

mc.polySphere(r=2 ,sx=10, sy=10)

rは半径

ポリゴン円錐を作成

mc.polyCone(r=1, h=3, sx=10, sy=10, sz=10)

hは高さ

ポリゴン円柱を作成

mc.polyCylinder(r=0.3, h=6, sx=6, sy=6, sz=2)

 

回転

mc.rotate( 45, 10, 20)

または

mc.rotate( '45deg', 0, 0)

 

もどる)(つぎへ

MayaでPython(1)

スクリプト

Mayaにはスクリプトでコントロールできるシステムがある.

主にMELスクリプトとPythonスクリプトの2種が使用できる.MELは以前から使用されてきたため情報は豊富である.一方でPythonは汎用性が高く記述もシンプルなため,近年人気が高まっている.YoutubeやInstagramなどに使用されているほか,ディープラーニングなどにも応用されている.

今回は汎用性の高いPythonを用いて簡単なコーディングを体験してもらう.

ワークフロー

スクリプトをメモ帳などに記述し,保存.このファイルをMayaのスクリプトエディタで開き実行する


作成1

テキストエディタ(メモ帳などで可)の1行目に

import maya.cmds as mc

と記入し,ファイル名を test1.py (※今回は拡張子を書き換えてかまわない)と保存する.

mcという名前でmayaのシステムを読み込む の意味

実行

Mayaに戻り,右下のスクリプトエディタボタンをクリックし,スクリプトエディタを開く.

このファイルを実行する

スクリプトエディタを開き,ファイル>スクリプトのロード>(保存したファイルを選び)開く を選択

スクリプトを実行ボタンをクリックする

今回は何も起こらないので次に進む


コメント

コメントは行頭に#をつける

import maya.cmds as mc
#mcという名前でmayaのシステムを読み込む

コメント行はプログラム実行時に無視される

 

ポリゴンのcubeを作成する

import maya.cmds as mc
#mcという名前でmayaのシステムを読み込む
mc.polyCube()

デフォルト設定のCubeが作成される

 

数値を指定して作成する

作成したCubeを削除する

3行目を

mc.polyCube(w=1, h=1, d=1, sx=2, sy=2, sz=2)

に変更する.変化の違いを確認する.

w,h,dは幅(width),高さ(height).奥行き(depth)の値

sxはsubdivide のx方向の意味で,sy,szも同様

 

練習

幅3,高さ5,奥行き2,x方向の分割2,y方向の分割4,z方向の分割1のCubeを作成せよ

次へ