はじめに
discordでchatbotを使うためにダイス判定処理をどのようにしているのか調べてみたら
正規表現を使って配列に分解する手法が一般的らしいの正規表現を試してみた。
概要
nDs、Dsと指定したダイス判定を行うプログラム。
n ...振りたいダイスの数量を指定する
s ...ダイスの種類を指定する(100面体,20面体,18面体,12面体,10面体,8面体,6面体,4面体)
正規表現で分解する構成
グループ1 判定するダイスの数
グループ2 ダイス宣言 ... D or d (一応大文字、小文字対応)
グループ3 ダイスの種類 ... 100 or 20 or 18 or 12 or 10 or 8 or 6 or 4
コード
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace RollingDice
{
class Program
{
static void Main(string[] args)
{
//繰り返しテストできるように無限ループ
while (true) {
Console.Write("input dice > ");
string input = Console.ReadLine();
string regex_rule = @"^([1-9]??)(|d|D)(100|20|18|12|10|8|6|4)*$";
var regex = new Regex(regex_rule);
Match match = regex.Match(input);
GroupCollection groups = match.Groups;
//処理が間違ってたら後続処理を中断
if (match.Groups[0].Length == 0)
{
Console.WriteLine("その指定は使用できません");
continue;
}
// ダイス判定処理
int NumberOfDice=0;
int SizeOfDice=0;
//ダイスの数量指定がない時は1を指定する
if(match.Groups[1].Length > 0)
{
NumberOfDice = int.Parse(match.Groups[1].ToString());
} else
{
NumberOfDice = 1;
}
if (match.Groups[3].Length > 0)
{
SizeOfDice = int.Parse(match.Groups[3].ToString());
}
string ResultOfRolls = null;
int TotalOfRolls = 0;
int i;
for(i=0; i < NumberOfDice; i++)
{
Random randomizer = new Random();
TotalOfRolls += randomizer.Next(1, SizeOfDice);
}
string ResultOfRolls = "コロコロコロ..." + match.Groups[0] +":" + TotalOfRolls;
Console.WriteLine(ResultOfRolls);
}
}
}
}
今後の課題
3d6+10とかd4-1とか加算・減算を交えた処理をしたかったが、正規表現がうまく動かず。普段使わなすぎ。
後、クラスとか使って処理を見やすくする努力を覚えよう。