簡體   English   中英

使用Math.random進行整數運算時會調用一個新數字

[英]Making a int with Math.random pick a new number when called

現在,我的變量都是隨機滾動的,但是只有一次。 我怎樣才能使它們在調用int時滾動一個新數字? 當前所有統計信息均相同。 一切都只能滾動一次。

int throwD4 = (int)(Math.random()*4+1);
int throwD6 = (int)(Math.random()*6+1);
int throwD8 = (int)(Math.random()*8+1);
int throwD10 = (int)(Math.random()*10+1);
int throwD12 = (int)(Math.random()*12+1);
int throwD20 = (int)(Math.random()*20+1);
int throwD100 = (int)(Math.random()*100+1);

int stat = (int)(throwD6 + throwD6 + throwD6);

String description = "A big strong dude with a cool longsword.";
String name = "Gladiator";

// stats
int STR = stat;
int DEX = stat;
int CON = stat;
int INT = stat;
int WIS = stat;
int CHA = stat;'

是的,您肯定會發現,如果您計算公式然后將其存儲在變量中,則除非重新計算公式並將其再次存儲在變量中,否則變量將保留其值。 訪問變量的值不會重新運行創建變量的公式。 變量只是一個啞數,它不記得公式。 除非您更改變量,否則變量不會更改,這一事實在程序的整個生命周期中非常方便。

考慮創建一個返回一個隨機數的方法,每次需要一個隨機數時,請調用該方法:

public int throwDice(int howManySides){
  return (int)(Math.random()*(howManySides+1));
}

如果您想了解如何使用它的更多建議,請向您的問題中添加一些有關您當前使用方式的上下文,例如throwD6

本質上,每當您考慮編寫throwD6 ,都改為改寫throwDice(6) 例如:

//rolling a 6 kills the character
if(throwDice(6) == 6)
  character.Kill();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM