enchant.js 熊を探せ

x軸y軸をランダムに表示させて、touchstartで、位置とスコアを変えていくゲームスクリプトです。

enchant();

window.onload = function(){
    var core = new Core(320, 320);
    core.preload('chara1.png');
    core.fps = 15;

    var score = 0;
    var timeLeft = 5 * core.fps;

    core.onload = function(){
        var bear = new Sprite(32, 32);
        bear.x = rand(320);
        bear.y = rand(320);
        bear.frame = 0;
        bear.image = core.assets['chara1.png'];

        bear.on('touchstart', function(){
            score++;
            scoreLabel.text = 'Score: ' + score;
            this.x = rand(320);
            this.y = rand(320);
        });

        var scoreLabel = new Label('Score: 0');
        scoreLabel.x = 200;
        scoreLabel.y = 5;

        var timeLabel = new Label('Time: 0');
        timeLabel.x = 5;
        timeLabel.y = 5;

        core.on('enterframe', function(){
            timeLeft--;
            timeLabel.text = 'Time: ' + timeLeft;
            if (timeLeft <= 0){
                alert('Your score: ' + score);
                this.stop();
            }
        });

        core.rootScene.addChild(scoreLabel);
        core.rootScene.addChild(timeLabel);
        core.rootScene.addChild(bear);


        core.rootScene.addChild(bear);
    }
    core.start();
}

function rand(n){
    return Math.floor(Math.random() * (n+1));
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <script type="text/javascript" src="enchant.js"></script>
    <script type="text/javascript" src="main.js"></script>
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
</body>
</html>

%e7%84%a1%e9%a1%8c

Unity Game作成

他のシーンを呼び出すには、build settingで設定します。
%e7%84%a1%e9%a1%8c

呼び出しのスクリプトです。

#pragma strict

var ball : Transform;
var n : int = 0;

function Update () {
	if (Input.GetButtonUp("Jump")){
	Instantiate(ball, transform.position, transform.rotation);
	n++;
	}

	if (n > 10){
	Application.LoadLevel("gameover");
	}
}

Gameの書き出しは、build and settingでbuidl and rundで行います。

player

#pragma strict

function Update () {
	var x: float = Input.GetAxis("Horizontal");
	transform.Translate(x * 0.2, 0, 0);

}

function OnCollisionEnter(obj: Collision) {
	if (obj.gameObject.name == "Enemy(Clone)"){
	 transform.localScale.x -= Random.Range(0.1, 0.5);
	 if (transform.localScale.x < 1.0) transform.localScale.x = 1.0;
	} 

}

enemy

#pragma strict


function Update () {
	transform.position.z -= 0.1;
	transform.Rotate(1, 1, 1);
	if (transform.position.z < -12.0){
	Application.LoadLevel("GameOver");
	}

}

function OnCollisionEnter(){
	Destroy(gameObject);
}
#pragma strict

var enemy: Transform;
function Update () {
	if(Time.frameCount % 60 == 0){
	Instantiate(enemy, Vector3(Random.Range(-5.0,5.0),1,8), transform.rotation);
	}
}
#pragma strict

var style: GUIStyle;

function OnGUI(){
	GUI.Label(Rect(10, 10, 100, 30), "GameOver", style);
}

unity JavaScript

Unityのスクリプトリファレンスです。
https://docs.unity3d.com/ScriptReference/index.html

objectに対するスクリプトを記述していきます。

#pragma strict

function Start () {
 Debug.Log("hello world");
}

function Update () {

}

unityのJSは変数の宣言など書き方が少し異なります。

#pragma strict

var x : int = 5;

function Start () {
 Debug.Log("hello world ->" + x);
}

function Update () {

}

オブジェクトを動かす際には、transformのポジションを動かします。

function Update () {
	transform.position.z += 0.1;
}

vector3でオブジェクトを移動させることもできます。

function Update () {
	transform.position += Vector3(0, 0, 0.1);
}

ユーザの入力受付

function Update () {
	if (Input.GetButtonUp("Jump")){
	Debug.Log("Jumped!");
	}
}

%e7%84%a1%e9%a1%8c

Edit->ProjectSetting->Inspectorで値を参照できます。

左右キーでオブジェクトを移動させます。

function Update () {
	if (Input.GetButtonUp("Jump")){
	Debug.Log("Jumped!");
	}

	var x : float = Input.GetAxis("Horizontal");
	transform.Translate(x * 0.2, 0, 0);
}

Digitbodyを設定して、以下のように記載すると、衝突判定ができます。

#pragma strict

function Start () {
 
}

function Update () {
	if (Input.GetButtonUp("Jump")){
	Debug.Log("Jumped!");
	}

	var x : float = Input.GetAxis("Horizontal");
	transform.Translate(x * 0.2, 0, 0);
}

function OnCollisionEnter(){
	Debug.Log("Hit!");
}

%e7%84%a1%e9%a1%8c

#pragma strict

var ball : Transform;

function Update () {
	if (Input.GetButtonUp("Jump")){
	Instantiate(ball, transform.position, transform.rotation);
	}
}

unity GameObjectの操作

%e7%84%a1%e9%a1%8c

位置の調整はtransformでもできます。
%e7%84%a1%e9%a1%8c

RigitBodyのコンポーネントの追加。Massを指定して、再生で動かすことができます。
%e7%84%a1%e9%a1%8c

ボールが跳ねるには、physic materialでbouncinessを設定します。
bounciness

Directional rightで全方位的にライトを照らします。

GameObjectは階層化させて一緒に動かすこともできます。カーレースで、車と一緒にカメラをつけて、動きに合わせて表示するというふうによく使われます。
%e7%84%a1%e9%a1%8c

Prefabを使って、データをAssetに移動させて、複製することも可能です。
%e7%84%a1%e9%a1%8c

オブジェクトにスクリプトを書いて動かすには、Projectでscriptを選択し、動かしたいgameobjectにドラックします。
%e7%84%a1%e9%a1%8c

Google Apps Script

Google Apps ScriptはGoogleの各サービスを制御するスクリプトです。googleのサーバー上で動いており、JavaScriptで書いていきます。

Google Apps Script
%e7%84%a1%e9%a1%8c

まずは、スプレッドシートから見てみます。
%e7%84%a1%e9%a1%8c

表示=>ログ で書いた内容を表示できます。

function hello() {
  Logger.log("hello world");
}

ブラウザ表示

function hello() {
  Browser.msgBox("Hello");
}

カスタム関数の作成

function getDouble(n){
  return n * 2;
}

任意のスプレッドシートへの値の挿入

function setData(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var range = sheet.getRange("A1");
  
  range.setValue(100);
}
function setData(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var range = sheet.getRange(1, 2);
  
  range.setValue(100);
  range.setBackground("red");
}
function getResults(){
  var sheet = SpreadsheetApp.getActiveSheet();
  for (var i = 1; i <= sheet.getLastRow(); i++){
    if(sheet.getRange(i, 2).getValue() >= 70){
     sheet.getRange(i, 3).setValue("OK").setBackground("green");
    } else {
      sheet.getRange(i, 3).setValue("NG").setBackground("red");
    }
  }
}

mailApp

function sendReport(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var n = 0;
  for (var i = 1; i <= sheet.getLastRow(); i++){
    if(sheet.getRange(i, 2).getValue() >= 70){
      n++;
    }
  }
  MailApp.sendEmail(
    "hogehoge@gmail.com",
    "合格者の数",
    n + "名合格しました!"
   );
}

トリガーを設定して、毎日N時にメールを送ることも可能です。
%e7%84%a1%e9%a1%8c

Google Formの送信

function sendReport(e) {
  var rs = '';
  
  var name = e.namedValues['お名前'];
  var email = e.namedValues['メールアドレス'];
  var attend = e.namedValues['参加?'];
  
  rs = "name: "+name+"\nemail: "+email+"attend: "+attend;
  
  MailApp.sendEmail("hogehoge@gmail.com", "回答ありました", rs)
}

Excel VBA2

Select: Whenのようにcaseを書いていく構文です。

Sub SelectTest()
    Dim signal As String
    signal = Range("a1").Value
    
    Dim result As Range
    Set result = Range("a2")
    
    Select Case signal
    
    Case "red"
        result.Value = "Stop!"
    Case "green"
        result.Value = "Go"
    Case "yellow"
        result.Value = "Caution"
    Case Else
        result.Value = "n.a"
        
    End Select
    
End Sub

while文

Sub WhileTest()
    Dim i As Integer
    i = 1
    
    Do While i < 10
        Cells(i, 1).Value = i
        i = i + 1
    Loop
End Sub

For文

Sub ForTest()
    Dim i As Integer
    
    For i = 1 To 9
        Cells(i, 2).Value = i
    Next i

End Subl

ForEachによるループ

Sub EachTest()
    Dim names As Variant
    names = Array("yamada", "taro", "sakamoto")
    
    For Each Name In names
        Debug.Print Name
    Next Name
End Sub

プロシージャの呼び出し

Sub CallTest()
    Dim names As Variant
    names = Array("okamoto", "nakamura", "hayashi")
    
    For Each name In names
        Call SayHi(name)
    Next name
End Sub

Sub SayHi(ByVal name As String)
 Debug.Print "hi, " & name
End Sub

返り値を返すfunctionプロシージャ

Sub CallTest()
    Dim names As Variant
    names = Array("okamoto", "nakamura", "hayashi")
    
    For Each name In names
        Debug.Print SayHi(name)
    Next name
End Sub

Function SayHi(ByVal name As String)
  SayHi = "hi, " & name
End Function

成績表 :一定数以下の数字をカウントして、メッセージ表示

Sub FindLowScores()
    Dim i As Long
    Dim n As Long
    i = 2
    n = 0
    
    Do While Cells(i, 1).Value <> ""
        If Cells(i, 2).Value < 40 Then
            Cells(i, 2).Interior.Color = vbRed
            n = n + 1
        End If
        i = i + 1
        Loop
    
    MsgBox (n & "件該当しました!")

End Sub

a

Excel VBA

Excel VBAの開発には、Visual Basci Editorを使います。
ツール => マクロ => VBE

s

プログラムを書いていくには、標準モジュールを使います。プロシージャーはSubから書き始めていきましょう。

Sub HelloWorld()
    MsgBox ("hello wolrd")
End Sub

セルにデータを書き込む

Sub CellChange()
    Worksheets("Sheet1").Range("A1").Value = "hello"
    Range("A2").Value = "hello2"
    Cells(3, 1).Value = "hello3"
End Sub
Sub CellChange()
    Range("A1", "B3").Value = "hello"
    Range("A5:C7").Value = "hello2"
    Range("4:4").Value = "row 4"
    Range("C:C").Value = "Column C"
End Sub

withで複数の命令を重ねる

Sub WithTest()
    With Range("A1")
    .Value = "hello"
    With .Font
      .Bold = True
      .Size = 16
    End With
     .Interior.Color = vbRed
    End With
End Sub

値の取得

Sub GetTest()
    MsgBox (Range("A1").Value)
End Sub

メソッドで処理を呼び出し

Sub MethodTest()
    'Range("B3").Delete shift:=xlShiftUp
    Worksheets.Add after:=Worksheets("sheet1"), Count:=3
End Sub

変数計算

Sub VariableTest()
    Dim x As Integer
    x = 10 + 5
    x = x + 1
    'Range("A1").Value = x
    Debug.Print x
End Sub

配列

Sub VariableTest()
    Dim sales As Variant
    sales = Array(200, 150, 300)
    Debug.Print sales(2)
    
End Sub

条件分岐

Sub IfTest()
    If Range("A1").Value > 15 Then
        Range("A2").Value = "OK"
    Else
        Range("A2").Value = "NG!"
    End If
    
End Sub

Python基礎

python3とpython2では記法が異なっている点があるので注意が必要です。

print ("hello world!")

変数

msg = "hello world"
print (msg)

整数と小数の演算は小数、整数同士の割り算は、小数点以下切り捨てとなります。

繰り返し処理

print (u"無駄"*10)

\\, \*なども

改行表現

print ("""<html>
<body>
</body>
</html>""")

整数値と文字列はpythonでは明示する

print (5 + int("5"))
print ("i am " + str(20) + "years old.")

配列、存在チェック

sales = [200, 100, 342, 1230, 122]
print (100 in sales)

ソート、reverse

sales = [52, 100, 80, 45]
sales.sort()
print (sales)

タプル:変更不可

a = (2, 5, 8)
print (a * 3)

セット:重複を許さない

a = set([1, 2, 3, 4])
print (a)

差集合

a = set([1, 2, 3, 4])
b = set([4, 5, 6, 7])
print (b - a)

辞書

sales = {"yamada": 200, "yoshida": 300, "sakura": 240}
print (sales)

key、value、items(一覧)

sales = {"yamada": 200, "yoshida": 300, "sakura": 240}
print (sales.values())

文字列へのデータ組み込み

a = 10
b = 123.345
c = "sakaki"
d = {"yamada":200, "yoshimoto": 300}
print ("age: %d" % a)

条件分岐

score = 70
if score > 60:
    print ("ok")

条件分岐2

score = 55
if score > 60:
    print ("ok")
elif score > 50:
    print ("soso")
else:
    print ("NG!")

forループ

sales = [13, 235, 312, 2232]
for sale in sales:
    print (sale)

繰り返し処理 ※インデントに注意

for i in range(10):
    print(i)

空処理

def hello2():
    pass

python module:
https://docs.python.org/3/library/index.html

wp mytheme

mythemeを作成していく際には、indexをまず作成し、それをheader, sidebar, footer, functions, style.cssなどにファイル分割していきます。wp_header、wp_footer、ウェジェットなど独自のルールが幾つかありますが、調べながら進めるとよいでしょう。
ショートコードなども簡単に作成できます。

<?php get_header(); ?>
    <div id="main" class="container">
      <div id="posts">

        <?php
        if (have_posts()):
          while(have_posts()):
            the_post();
          ?>
        <div class="post">
            <div class="post-header">
              <h2>
                <a href="<?php echo the_permalink(); ?>"><php the_title(); ?></a>
              </2>
              <div class="post-meta">
                <?php echo get_the_date(); ?>【<?php the_category(', '); ?>】
              </div>
            </div>
            <div class="post-content">
                <div class="post-image">
                  <?php if (has_post_thumbnail()): ?>
                  <?php the_post_thumbnail(array(100, 100)); ?>
                  <?php else: ?>
                    <img src="<?php echo get_template_directory_uri();?>img/noimage.png" width="100" height="100">
                  <?php endif; ?>
                </div>
                <div class="post-body">
                  <p>
                    <?php the_excerpt(); ?>
                  </p>
                </div>
            </div>
        </div>

      <?php endwhile;
    else:
      ?>
      <p>記事はありません! </p>
      <?php
    endif;
     ?>

        <div class="navigation">
            <div class="prev"><?php previous_posts_link(); ?></div>
            <div class="next"><?php next_posts_link(); ?></div>
        </div>
      </div><!-- /posts -->

      <?php get_sidebar(); ?>
    </div><!-- /main -->
<?php get_footer(); ?>
<?php

add_theme_support('menus');
register_sidebar(
  array(
    'before_widget' => '<div class="widget">',
    'after_widget' => '<div>',
    'before_title' => '<h3>',
    'after_title' => '</h3>',
  )
);

add_theme_support('post_thumbnails');

function shortcode_tw(){
  return '<a href="http://twitter.com/hogehoge">@hogehoge</a>をフォローしてね'
}
add_shortcode('tw','shortcode_tw');

WP mytheme header情報の挿入

mythemを作る場合は、stylecssにヘッダー情報を挿入しなければなりません。
wordpress codexよりコピーします。
wordpress codex them_Development

/*
Theme Name: Twenty Thirteen
Theme URI: http://wordpress.org/themes/twentythirteen
Author: the WordPress team
Author URI: http://wordpress.org/
Description: The 2013 theme for WordPress takes us back to the blog, featuring a full range of post formats, each displayed beautifully in their own unique way. Design details abound, starting with a vibrant color scheme and matching header images, beautiful typography and icons, and a flexible layout that looks great on any device, big or small.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: black, brown, orange, tan, white, yellow, light, one-column, two-columns, right-sidebar, flexible-width, custom-header, custom-menu, editor-style, featured-images, microformats, post-formats, rtl-language-support, sticky-post, translation-ready
Text Domain: twentythirteen

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/

そうすると、管理画面からテーマの編集ができるようになります。