大宮盆栽デイズ - Omiya Bonsai Days -

冗談めかす埼玉のファインマン

楽器を演奏する@コードを学ぼう3

// 楽器を演奏する@コードを学ぼう3
let blu = Graphic(image: #imageLiteral(resourceName: "Blu1@2x.png"))
let theOrigin = Point(x: 0, y: 0)
scene.place(blu, at: theOrigin)

// Event handler for Music tool.
func musicalGraphic(graphic: Graphic) {
    
    // Play a note for Blu.
    if graphic == blu {
        playInstrument(.cosmicDrums, note: 12, volume: 50)
    }
    
    // Play a note on a different instrument for each type of fruit.
    let x = randomInt(from: 0, to: 15)
    if graphic.text == "🍐" {
        playInstrument(.bassGuitar, note: x)
    } else if graphic.text == "🍊" {
        playInstrument(.electricGuitar, note: x)
    } else if graphic.text == "🍋" {
        playInstrument(.piano, note: x)
    }
}

// Event handler for Fruit tool.
func addFruit(touch: Touch) {
    if touch.previousPlaceDistance < 60 { return }
    let fruit = "🍐🍊🍋".componentsByCharacter()
    let graphic = Graphic(text: fruit.randomItem)
    scene.place(graphic, at: touch.position)
    graphic.scale = 2.0
}

// Create and add Fruit tool.
let fruitTool = Tool(name: "Fruit", emojiIcon: "🍊")
fruitTool.onFingerMoved = addFruit(touch:)
scene.tools.append(fruitTool)

// Create and add Music tool.
let musicTool = Tool(name: "Music", emojiIcon: "🎼")
musicTool.onGraphicTouched = musicalGraphic(graphic:)
scene.tools.append(musicTool)