javascript - 使用形状的 Fizzbuzz (p5.js)
问题描述
我目前正在尝试使用形状创建一个 fizzbuzz,但无法正确显示可被 3 和 5 整除的正方形。我搜索了答案,但似乎没有人尝试过。
编写一个程序,在屏幕上绘制 25 个水平方向的黑色圆圈。请使用从零开始的 for 循环来完成此操作,并且每次迭代都会将 iterand 向前递增 1。
然而,
当迭代数可被 3 整除时,画一个紫色圆圈当迭代数可被 5 整除时,画一个绿色正方形当迭代数可被 3 AND 5 整除时,画一个蓝色正方形代替
function setup() {
createCanvas(1500, 1500);
ellipseMode(CENTER);
}
function draw() {
background(200);
var y = 100;
// 25 black squares
for (let x = 0; x < 1250; x += 50) {
fill(0);
ellipse(x, y, 50, 50);
// sets the purple circle
if (x % 3 === 0) {
fill(153, 31, 240);
ellipse(x, y, 50, 50);
}
// sets the green squares should be on top
if (x % 5 === 0) {
fill(0, 255, 0);
square(x + 25, y - 25, 50);
}
// sets the last blue square
// issue is the is supposed to be only one at the 15 mark
if (x % 3 == 0 && x % 5 == 0) {
fill(0, 0, 255);
square(x + 25, y - 25, 50);
}
}
}
解决方案
主要问题是您的条件评估x
。注意,x
是 x 坐标和 50 的倍数。
您必须评估字段的索引。
仔细阅读您自己的说明:
[...] 使用从零开始的 for 循环来完成此操作,并且每次迭代将iterand 向前递增1。
此外,必须“改为”绘制形状。
i=0
从to运行一个循环i<25
:
for (let i = 0; i < 25; ++ i)
并使用
if () { ... } else if () { ... } else { ... }
序列:
请参阅示例:
function setup() {
createCanvas(1500, 1500);
}
function draw() {
background(200);
var y = 100;
// 25 black squares
for (let i = 0; i < 25; ++ i) {
let x = i*50;
if (i % 3 == 0 && i % 5 == 0) {
// sets the last blue square
fill(0, 0, 255);
square(x, y, 50);
}
else if (i % 5 === 0) {
// sets the green squares should be on top
fill(0, 255, 0);
square(x, y, 50);
}
else if (i % 3 === 0) {
// sets the purple circle
fill(153, 31, 240);
ellipse(x+25, y+25, 50, 50);
}
else {
// black circle
fill(0);
ellipse(x+25, y+25, 50, 50);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
推荐阅读
- arrays - BigQuery - 分组并使用数组字段作为过滤器
- windows-7 - 迁移到 AdoptOpenJDK 11 后 Windows 7 中的像素化 Java GUI
- jmeter - JMeter 综合报告生成不正确的数据
- python - 如何实现与列表搜索相反的字典/集合,以提高速度
- django - 具有两个 ForeignKey 关系的 CreateView 时出现 KeyError
- javascript - 无法从内存中删除已创建但从未附加到页面的画布元素
- list - 列表中的数字大于平均值
- node.js - 如何使用 Express 和 Puppeteer 对每个动态加载的页面进行截图?
- c# - 如果用户输入字符串而不是 int,我如何弹出错误消息
- ruby - 无限循环活动记录