下列是processing中的发送程序请帮我改进程序并显示import processingserial;Serial port;void setup port=new SerialthisCOM39600; Arduino板的端口号 size200500; textSize150;void draw background225; String floors =F9 F8 F7 F6
以下为改进后的程序:
import processing.serial.*;
Serial port;
void setup() { size(200, 500); textSize(150); textAlign(CENTER, CENTER); port = new Serial(this, "COM3", 9600); // Arduino板的端口号 }
void draw() { background(225);
String floors = "F9 F8 F7 F6 F5 F4 F3 F2 F1"; textSize(24); fill(255, 0, 0); textLeading(50); text(floors, 20, 25, 40, 500);
for (int i = 0; i < 9; i++) { fill(100); rect(50, i * 50, 100, 50); } }
void mouseClicked() { int currentFloor = -1; for (int i = 0; i < 9; i++) { if (mouseX >= 50 && mouseX <= 150 && mouseY >= i * 50 && mouseY <= (i + 1) * 50) { currentFloor = i + 1; break; } } if (currentFloor > 0) { println(currentFloor + " floor"); port.write(currentFloor); } }
改进说明:
- 简化绘制楼层按钮的代码,使用for循环遍历绘制,使代码更加简洁。
- 重构鼠标点击事件的代码,使用for循环判断点击的按钮是哪一个楼层,避免了大量的if语句,使代码更加简洁。
- 修改了文本的对齐方式,使其居中显示。
- 修复了鼠标点击事件中的逻辑错误,原先的逻辑是当鼠标点击区域在任何一个按钮范围内时都会发送数据,现在改为只有当鼠标点击区域在某个按钮范围内时才会发送数据
原文地址: https://www.cveoy.top/t/topic/dFph 著作权归作者所有。请勿转载和采集!