演習の解答例
演習1
import processing.net.*;
Server myServer;
int val = 0;
void setup() {
size(200, 200);
myServer = new Server(this, 5204);
}
void draw() {
if (mousePressed) {
myServer.write(0);
} else {
myServer.write(255);
}
}
演習2
サーバープログラム
import processing.net.*;
Server myServer;
int val = 0;
void setup() {
size(200, 200);
myServer = new Server(this, 5204);
}
void draw() {
}
void mouseClicked() {
val = (val + 1) % 3;
myServer.write(val);
}
クライアントプログラム
import processing.net.*;
Client myClient;
color backgroundColor = color(255, 0, 0);
void setup() {
size(200, 200);
myClient = new Client(this, "127.0.0.1", 5204);
}
void draw() {
background(backgroundColor);
}
void clientEvent(Client client) {
int val = client.read();
if (val == 0) {
backgroundColor = color(255, 0, 0);
} else if (val == 1) {
backgroundColor = color(0, 255, 0);
} else {
backgroundColor = color(0, 0, 255);
}
}
演習3
サーバープログラム
import processing.net.*;
Server myServer;
int x;
int y;
int dx = 5;
int dy = 5;
int r = 50;
void setup() {
size(600, 400);
myServer = new Server(this, 5204);
x = width / 2;
y = height / 2;
}
void draw() {
background(255);
fill(0);
ellipse(x, y, 2 * r, 2 * r);
if (x - r < 0 || width <= x + r) {
dx *= -1;
}
if (y - r < 0 || height <= y + r) {
dy *= -1;
}
x += dx;
y += dy;
String s = "" + x + ',' + y + '\n';
myServer.write(s);
}
void clientEvent(Client client) {
while (client.available() > 0) {
String[] xy = split(client.readStringUntil('\n').trim(), ',');
int mx = int(xy[0]);
int my = int(xy[1]);
if (dist(x, y, mx, my) <= r) {
dx = 0;
dy = 0;
}
}
}
クライアントプログラム
import processing.net.*;
Client myClient;
int x, y;
int r = 50;
void setup() {
size(600, 400);
myClient = new Client(this, "127.0.0.1", 5204);
}
void draw() {
background(255);
fill(0);
ellipse(x, y, 2 * r, 2 * r);
}
void mouseClicked() {
String s = "" + mouseX + ',' + mouseY + '\n';
myClient.write(s);
}
void clientEvent(Client client) {
while (client.available() > 0) {
String[] xy = split(client.readStringUntil('\n').trim(), ',');
x = int(xy[0]);
y = int(xy[1]);
}
}