[英]Drawing mountains using 1px swing rectangles
我正在嘗試使用1寬度矩形(類似於積分)繪制山脈背景。 我將第一個點隨機化到屏幕的最左側,將二進制數隨機化並繪制第一個矩形。
如果二進制數為0,則下一個矩形將低1px。 其他更高。 等等在for循環中。
在下一個循環中,有95%的可能性方向不會改變,並且會不斷上升/下降。 方向改變的機會為5%。 為此,我使用的是1到1000之間的隨機數。
public Landscape(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
Random rand = new Random();
int first = rand.nextInt((800 - 200) + 1) + 200;
g2d.fillRect(0, 800 - first, 1, first);
int d = first % 2;
for(int i = 1; i <= 800; i++) {
int choose = rand.nextInt((1000 - 1) + 1) + 1;
if(choose > 950) {
d = -(d);
}
if(d == -1) {
first += 1;
} else {
first -= 1;
}
g2d.fillRect(i, 800 - first, 1, first);
}
}
這就是我在一半情況下得到的效果。 但是有時候我會得到這樣的東西:
這怎么可能? 怎么了
這里:
int d = first % 2;
d為1或0。如果d分配為0,則if(d == -1) {
始終為false,因此圖將單調向下移動。
您正在尋找兩種狀態的解決方案來確定山是上升還是下降,因此請使用布爾值。 也許像這樣:
boolean direction = rand.nextBoolean();
// 1 in 20 chance, same as 5 in 100, same as 50 in 1000 chance
if (rand.nextInt(20) == 0) {
direction = !direction;
}
if (direction) {
// ...
} else {
// ...
}
我自己,我會考慮使用分形。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.