2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GASでスプレッドシートにズンドコキヨシを出力する

Posted at

ズンドコキヨシ

ここ数日、「ズンドコキヨシ」の投稿が何件かあったので、
休憩がてらに作成してみました。

ズンドコキヨシをLINQでゴリ押してみる
1行で書く『「ズン」「ドコ」のいずれかをランダムで出力し続けて「ズン」「ズン」「ズン」「ズン」「ドコ」の配列が出たら「キ・ヨ・シ!」って出力した後終了』

元ネタはこちら

実行結果

cap_01.png

cap_02.png

実装

kiyoshi.gs

function doKiyoshi() {
  //キヨシ定数
  const kiyoshi = "KI・YO・SHI !!";
  //ズンドコ定数配列
  const zundoko = ["ZUN","DOKO"];

  var sheet = new PushSheet();//シート操作
  var queue = new Queue();//出力履歴保持用キュー
  
  //使い切ることはないと思うが、一応上限を設定しておく
  for(var i=1;i<=1000;i++){
    var index = Math.floor(Math.random()*10)% 2;
    queue.enqueue(index);
    sheet.pushSheet(zundoko[index]);
    
    //ズンドコキヨシチェック
    if(queue.kiyoshi())break;
  }
  sheet.pushSheet(kiyoshi);
  sheet.kiyoshiColor("");
}
Queue.gs

//要素の上限が5のキュー
function Queue() {
  this.__queue = new Array();
}
//エンキュー
Queue.prototype.enqueue = function(o) {
  this.__queue.push(o);
  if(this.__queue.length> 5)this.dequeue();
}
//デキュー
Queue.prototype.dequeue = function() {
	if( this.__queue.length > 0 ) {
		return this.__queue.shift();
	}
	return null;
}

//ズン(0)、ズン(0)、ズン(0)、ズン(0)、ドコ(1)しているかチェック
Queue.prototype.kiyoshi = function() {
  if( this.__queue.length < 5) {
	return false;
  }
  return this.__queue.join().equals("0,0,0,0,1");
}

PushSheet.gs
//シート操作
function PushSheet() {
  this.__sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  this.__sheet.clear();
  this.__lastRow = this.__sheet.getLastRow();
}
//最後の行に文字を挿入
PushSheet.prototype.pushSheet = function(o) {
  this.__sheet.getRange(this.__lastRow+1, 1).setValue(o);
  this.__lastRow = this.__lastRow + 1;
}
//文字色の設定、文字サイズ変更、太文字に変更して最後の行付近にフォーカスを合わせる
PushSheet.prototype.kiyoshiColor = function(o){
  var range = this.__sheet.getRange(this.__lastRow -5, 1, 6)
                          .setBackground(o)
                          .setFontSize(20)
                          .setFontWeight("bold");

  this.__sheet.setActiveRange(this.__sheet.getRange(this.__lastRow+5, 1));
}
//初期化
PushSheet.prototype.clear = function(o) {
  this.__sheet.clear();
}

ボタンの設置はこの記事あたりを参考にしてください。
Spreadsheet GAS 入門 「マクロを図形に割り当てる」

実装の解説

  • ズンドコ履歴をどうやって保持させるか迷ったので、なんとなく思い浮かんだキューっぽいものを作って保持することにした。
  • ズンドコをシートへ出力する処理をループ内に書いているので重くなるかと思ったが、そこまでループしないのであまり気にはならない。
  • doKiyoshi関数がごちゃごちゃするのが嫌だったので、シート操作は外出にした。
  • 最初はスプレッドシートのアドオンにしようかと思ったが、思いの外手間がかかりそうだったの断念。

まとめ

くだらないものを書いているときが一番楽しい。

 

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?