java实现咖啡店模拟_java - 试图让我的代码看起来像咖啡馆的墙壁错觉 - SO中文参考 - www.soinside.com...

@ drifter265我想回答,但我也希望你学习,因为这似乎是一个专为教学设计的入门级项目。

因此,请直接提供答案,而是通过解释当前程序当前正在执行的操作,向您显示错误的位置。

// size is the pixel width/height of a square.

// multiples is the number of black/white pairs to draw.

// x,y are the screen position of the top left corner.

// offset is the amount to offset by.

public static void grid(Graphics g, int size, int multiples, int x, int y, int offset) {

for (int i = 0; i < multiples * 2; i++) {

row(g, size, multiples, x + (offset * i), y + (size * i) + (2 * i));

}

}

这里的代码相对简单。

它正在从0增量1循环,表示您想要绘制的黑色和白色方块的总数。 (在倍数* 2之前停止,从0开始是正确的)

每次循环时,它都会调用row。

它大致相当于

row(g, size, 2, x + (offset * 0), y + (size * 0) + (2 * 0));

row(g, size, 2, x + (offset * 1), y + (size * 1) + (2 * 1));

row(g, size, 2, x + (offset * 2), y + (size * 2) + (2 * 2));

row(g, size, 2, x + (offset * 3), y + (size * 3) + (2 * 3));

(它创建的行数是黑色列的两倍)

你遇到的问题是,你的偏移总是在增长,而不是来回摆动。

where x = 0, and offset = 10

rowoffset = x + (offset * 0) = 0

rowoffset = x + (offset * 1) = 10

rowoffset = x + (offset * 2) = 20

rowoffset = x + (offset * 3) = 30

但是你想要的是

where x = 0, and offset = 10

rowoffset = 0; // where i == 0

rowoffset = 10 // where i == 1

rowoffset = 0 // where i == 2

rowoffset = 10 // where i == 3

实现分支行为的常用方法取决于要做出的决定是使用if语句。

因此,不是将x+offset*i传递给行,而是可以在那里引入变量,这取决于我是奇数还是偶数。

计算整数是奇数还是偶数的常用方法是使用remainder operator (%),传递数字2.(但是在使用任何一方的负值时必须小心)

0%2 == 0

1%2 == 1

2%2 == 0

3%2 == 1

~~~

8%2 == 0

9%2 == 1

因此,您现在可以使用数学或if语句,以使您的zig zag像模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值