Кубики (Дайсы)

Данные скрипты позволят "кидать кубики" прямо у Вас на форуме. Скрипты будут более актуальны для ролевых форумов. После установки скрипта в форме ответа появится кнопка "Кинуть кубики", после нажатия скрипт спрашивает сколько кубиков бросаем, сколько граней у кубиков и.т.п После этого в форме ответа формируется код, который после отправки формирует результаты броска. Выберите один из ниже предложенных скриптов и поставьте в HTML форма ответа:

Первый вариант:

Код:
<input type="button" onclick="dice()" value="Кинуть кубики" />
<script type="text/javascript">
function dice()
{
	var FoundErrors = '';
	var diceRes=""
	var CountCube = prompt("Количество кубиков", "3");
	var SideCube = prompt("Сколько граней у кубика?", "6");
	if(CountCube>9){
	alert("Нельзя бросать столько кубиков"); 
	return false;}
	if(SideCube>9){
	alert("Не бывает таких кубиков"); 
	return false;}
	if (!CountCube)
	{return false;}
	if (!SideCube)
	{return false;}
	for(i=0; i<CountCube;i++){
	var dice = (Math.round(Math.random()*SideCube))
	if(dice==0) dice=1;
	diceRes += dice*1936+"-"
	}
	smile('[dice='+diceRes+CountCube+SideCube+']')
}
</script>
<script>
function addDice(str,from,internal){
var pos=0,pos2=0,newpos=0
if((pos=str.indexOf("[dice=",from))==-1) return str;
if((pos2=str.indexOf("]"),pos+6)==-1) return str;
newpos=str.indexOf("]",pos+6)
if(newpos<pos2 && newpos!=-1) str=addDice(str,pos+6,true)
if((pos2=str.indexOf("]",pos+6))==-1) return str;
str=str.substring(0,pos)+makeDice(str.substring(pos+6,pos2))+str.substring(pos2+1,str.length)
if( str.indexOf("[dice=")!=-1 && internal==false) str=addDice(str,0,false)
return str}

function makeDice(dice){
diceMass = dice.split("-")
diceC = dice.substring(dice.length-2, dice.length-1)
diceS = dice.substring(dice.length-1, dice.length)
var diceR=0, diceRu="";
for(i=0;i<diceMass.length-1;i++){diceR+=diceMass[i]/1936;}
for(i=0;i<diceMass.length-1;i++){if(diceMass[i]==diceMass[diceMass.length-2]){diceRu+=diceMass[i]/1936;}else{diceRu+=parseInt(diceMass[i]/1936)+"+";}}
txt="<div class=\"quote-box\"><blockquote><p><b>Количество кубиков</b>: "+diceC+"<br /><b>Граней в кубике</b>: "+diceS+"<br /><br /><b>Результаты броска</b>: ("+diceRu+")="+diceR+"</p></blockquote></div>"
return txt}

if(document.URL.indexOf("viewtopic.php")!=-1){
elm=document.getElementById("pun-main").getElementsByTagName("div")
for(x in elm) if(elm[x].className=="post-content"){
var post=elm[x]
post.innerHTML=addDice(post.innerHTML,0,false)}}
</script>

Второй вариант:

Код:
<input type="button" onclick="dice()" value="Кинуть кубики" />
<script type="text/javascript">
function dice()
{
	var FoundErrors = '';
	var diceRes=""
	var CountCube = prompt("Количество кубиков", "3");
	var SideCube = prompt("Сколько граней у кубика?", "6");
	if(CountCube>9){
	alert("Нельзя бросать столько кубиков"); 
	return false;}
	if(SideCube>9){
	alert("Не бывает таких кубиков"); 
	return false;}
	if (!CountCube)
	{return false;}
	if (!SideCube)
	{return false;}
	for(i=0; i<CountCube;i++){
	var dice = (Math.round(Math.random()*SideCube))
	if(dice==0) dice=1;
	diceRes += dice*1936+"-"
	}
	smile('[dice='+diceRes+CountCube+SideCube+']')
}
</script>
<script>
function addDice(str,from,internal){
var pos=0,pos2=0,newpos=0
if((pos=str.indexOf("[dice=",from))==-1) return str;
if((pos2=str.indexOf("]"),pos+6)==-1) return str;
newpos=str.indexOf("]",pos+6)
if(newpos<pos2 && newpos!=-1) str=addDice(str,pos+6,true)
if((pos2=str.indexOf("]",pos+6))==-1) return str;
str=str.substring(0,pos)+makeDice(str.substring(pos+6,pos2))+str.substring(pos2+1,str.length)
if( str.indexOf("[dice=")!=-1 && internal==false) str=addDice(str,0,false)
return str}

function makeDice(dice){
diceMass = dice.split("-")
diceC = dice.substring(dice.length-2, dice.length-1)
diceS = dice.substring(dice.length-1, dice.length)
var diceR=0, diceRu="";
for(i=0;i<diceMass.length-1;i++){diceR+=diceMass[i]/1936;}
for(i=0;i<diceMass.length-1;i++){if(diceMass[i]==diceMass[diceMass.length-2]){diceRu+=diceMass[i]/1936;}else{diceRu+=parseInt(diceMass[i]/1936)+"+";}}
txt="<div class=\"quote-box\"><blockquote><p><b>Исходный бросок</b>: "+diceC+"d"+diceS+"<br /><br /><b>Результаты броска</b>: ("+diceRu+")="+diceR+"</p></blockquote></div>"
return txt}

if(document.URL.indexOf("viewtopic.php")!=-1){
elm=document.getElementById("pun-main").getElementsByTagName("div")
for(x in elm) if(elm[x].className=="post-content"){
var post=elm[x]
post.innerHTML=addDice(post.innerHTML,0,false)}}
</script>

Третий вариант (на мой взгляд самый лучший):

Код:
<input type="button" onclick="dice()" value="Кинуть кубики" />
<script type="text/javascript"> 
 
function unhtml(s)
{ return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
 
function numword(s,one,two,many)
{ return(((s%100>=10 && s%100<=20) || s%10>=5) ? many : 
          (s%10==1 ? one : two)); }
 
function dice()
{
        var FoundErrors = '';
        var diceRes=""
        var CountCube = prompt("Количество кубиков", "1");
        if(CountCube>100 || CountCube<=0) {
        alert("Нельзя бросать столько кубиков");  return false;}
        var SideCube = prompt("Сколько граней у кубика?", "10");
        if(SideCube>1000 || SideCube<=0){
        alert("Не бывает таких кубиков");         return false;}
        var BonusCube = parseInt(prompt("Какой бонус прибавляем?", "+0"));
        var ReasonCube = unhtml(prompt("По какому поводу бросок?", "").
           replace(/\s+/g," ").replace("]"," "));
        
        for(i=0; i<CountCube;i++)
        {
          var dice = (Math.round(Math.random()*SideCube));
          if(dice==0) dice=1;
          diceRes += dice*1936+"-";
        }
        smile('[dice='+diceRes+CountCube+':'+SideCube+
              ':'+BonusCube+':'+ReasonCube+']');
}
 
function addDice(post,from,internal)
{
  var str=post.innerHTML, num=-1, date=-1, a, fCanRandomise=0, u=""; 
  while(post=post.parentNode) 
    if(post.className=="container")
      if(post=post.parentNode)
      {
        if(a=post.innerHTML.match(
          /class[^<>]+permalink[^<>]+#p(\d+)[^<>]*>[^<>]*(\d+):(\d+):(\d+)[^<>]*<\/a>/i))
            { num=a[1]; date=a[4]; 
              fCanRandomise=1; break; }
      }
 
  var ran=parseInt(num+date);
  return str.replace(
     /\[dice=((?:\d+-)*)(?:(\d)(\d+)|(\d+)(:)(\d+)(?::(-?\d+):([^\]]*))?)]/g,
  function(a,dice,diceC,diceS,adieC,fNewScheme,adieS,adieB,adieR) 
  {
    diceC=parseInt(fNewScheme ? adieC : diceC);
    diceS=parseInt(fNewScheme ? adieS : diceS);
    adieB=parseInt(adieB ? adieB : 0);
    if(adieB>0) adieB='+'+adieB;
    if(!fCanRandomise && fNewScheme)
      return '<div class="quote-box"><blockquote><p><b>СБОЙ ДАЙСОМЕТАЛКИ - СООБЩИТЕ МАСТЕРАМ</b></p></blockquote></div> ';
 
    var i,diceR=0,
        s='<div class="quote-box"><blockquote '+  
          'style="text-align:left"><p>'+
           '<b>Игрок кинул '
           +diceC+numword(diceC,' куб с ',' куба с ',' кубов с ')
           +diceS+numword(diceS,' гранью',' гранями',' гранями')
           +(adieB ? (adieB>0 ? ' и бонусом ' : ' и пенальти ')+adieB : '')+
           (adieR ? ', моделируя событие:</b><br><i>'+adieR+'</i><b>' : '')
           +'<br /><br />Результаты броска '+
           (fNewScheme ? '' : '(старая схема)')+'</b>: (';
 
    dice=dice.split("-"); 
    for(i=0; i<dice.length-1; ++i)
    {
       var d=parseInt(dice[i]/1936); 
       date=((date>>1)+((date&1)<<21))&0x3fffff;
       num=((num>>1)+((num&1)<<22))&0x7fffff;
       if(fNewScheme) d=(ran=(((ran>>1)+(((ran&1) ? 0 : 1)<<23)+d+date)^num)&0xffffff)%diceS +1;
       diceR+=d;
       s+= (i?' + ':'') + d;
    } 
 
    if(adieB) diceR+=parseInt(adieB);
    return(s+ (adieB ? ')'+adieB : ')')+ 
           '=' + diceR + '</p></blockquote></div>');
  });
}
if(document.URL.indexOf("viewtopic.php")!=-1)
{
  elm=document.getElementById("pun-main").getElementsByTagName("div");
  for(x=0; x<elm.length; ++x) 
    if(elm[x].className=="post-content")
      elm[x].innerHTML=addDice(elm[x]); 
}
</script>

Если Вы хотите чтоб кнопка красиво размещалась возле кнопок "Отправить" и "Посмотреть", то замените первую строчку в скрипте:

Код:
<input type="button" onclick="dice()" value="Кинуть кубики" />

На:

Код:
<script type="text/javascript">
$(document).ready(function() {
$(".formsubmit").append("<input type='button' onclick='dice()' value='Кинуть кубики' />");
});
</script>