Tuesday, August 23, 2011

Data

Variables: 변수

Data를 다룰 때 변수는 가장 중요한 요소라 할 수있다. 변수를 어떻게 설정하는가에 따라서 코드를 이해할 수도 있고 없을 수도있을 것이다. 예를 들자면 여러분들이 이미지를 x1,y1좌표에서 x2,y2좌표로 이동하려고 할때 x1,y1,x2,y2라는 변수 를 어떻한 값, 즉 int(정수), float(소수)등으로 설정하는가에 따라 그 의미는 달라질 것이다. 아래와 같이 프로세싱 기본예제를 틍하여 예를 들어보자.














size(200, 200);

background(0);
stroke(153);

int a = 20;
int b = 50;
int c = a*8;
int d = a*9;
int e = b-a;
int f = b*2;
int g = f+e;

line(a, f, b, g);
line(b, e, b, g);
line(b, e, d, c);
line(a, e, d-e, c);

위에 제시된 예제의 모든 변수는 정수로 선언되었고 선을 그리기위한 변수들이다. 그리고 변수들은 순차적으로 저장되어 각 그리려고 하는 선의 변수로 활용되었다.

Integer and Float: 정수와 소수

아래의 예제에서는 정수와 소수의 쓰임새에 대해서 잘 알수 있는 예제이다. 정수는 보통 "int"로 알려져있고, 소수는 "float"이라 알려져있다. 정수는 아는 바와 같이 소수점이 없으므로 그 쓰임새가 정확하면 정확할수록 소수를 많이 쓰게된다. 아래의 예제는 정수, 소수의 변수가 변함에 따라 왼쪽에서 오른쪽으로 진행하는 선의 움직임을 잘 보여주는 코드이다.














int a = 0;      // Create a variable "a" of the datatype "int"

float b = 0.0; // Create a variable "b" of the datatype "float"

void setup()
{
size(200, 200);
stroke(255);
frameRate(30);
}

void draw()
{
background(51);

a = a + 1;
b = b + 0.2;
line(a, 0, a, height/2);
line(b, height/2, b, height);

if(a > width) {
a = 0;
}
if(b > width) {
b = 0;
}
}


Boolean: True of False

이번에는 유명한 참/거짓에 대한 변수의 방식을 알아보자. 이러한 변수의 방식을 "boolean"이라고 하는데 변수를 선언할 때 "boolean f = false;"의 방식으로 한다. 아래의 예제는 이러한 "one bit" 변수에 대한 것이다.














boolean x = false;


size(200, 200);
background(0);
stroke(0);

for (int i = 1; i < width; i += 2)
{
if (i < width/2)
{
x = true;
} else {
x = false;
}

if (x)
{
stroke(255);
line(i, 1, i, height-1);
}

if (!x)
{
stroke(126);
line(width/2 , i, width-2, i);
}
}

위의 예제를 살펴보면 참/거짓 변수는 조건문과 같이 쓰이고 있는 것을 볼 수 있다. 변수 x가 참일 때, 변수 x가 거짓일 때 그림을 그린다. 먼저 참과 거짓의 조건을 살펴보면 정수 i가 2씩 디스플레이 너비의 값까지 증가하는데 만일 디스플레이를 반으로 나눈 값보다 작을 경우 "참" 그렇지 않을 경우 "거짓"의 두가지 조건이 if와 else로 표현되었다. 그리고 거짓일 경우 참일 경우 "line(i, 1, i, height-1);", 참일 경우 "line(width/2 , i, width-2, i);"의 선을 그린다. 주의할 점은 시작점이 point(1,1)이고, 끝점이 point(width-2,width-2)라는 점이다.

Data Conversion: 데이터 변환

때로 프로그래밍을 할 때 데이터변환은 한 좋은 방법일 수 있다. 왜냐하면 주변기기들과의 소통을 위해서 특정한 데이터를 다룰 수 있기 때문이기도하고 혹, 데이터의 스케일링에서도 이러한 문제가 자주 일어날 수 있다. 아래의 예제는 이러한 데이터의 변환에 대한 다양한 예를 보인다.














size(200, 200);

background(51);
noStroke();

char c; // Chars are used for storing typographic symbols
float f; // Floats are decimal numbers
int i; // Ints are values between 2,147,483,647 and -2147483648
byte b; // Bytes are values between -128 and 128

c = 'A';
f = float(c); // Sets f = 65.0
i = int(f * 1.4); // Sets i to 91
b = byte(c / 2); // Sets b to 32

rect(f, 0, 40, 66);
fill(204);
rect(i, 67, 40, 66);
fill(255);
rect(b, 134, 40, 66);


좀더 설명을 해보자면 위의 예제에서 보듯 변수의 방식에 따라서 표현할 수 있는 정도의 차이도 생길 수 있는 것이다. 그렇지만 때로 이 모든 가능성을 수용하도록 컴퓨터가 고안된 것은 아니다. 말하자면 필요한 값의 범위가 -128에서 128인 경우에 큰 정수의 범위가 필요한 것은 아니다. 혹 데이터를 변형시켰을 때, 때로 좋은 결과(말하자면 의외의 결과)를 얻는 경우도 있을 것이다.

Variable Scope: 변수의 유효범위

아래의 예제를 보면 변수의 유효범위에 대해 이해할 수 있는데 광범위하게 쓰일 수 있는 변수와 지엽적으로 쓰일 수 있는 변수가 있다고 생각하면 된다. 예를 들어 "setup()"이나 "draw()"의 범위 밖, 처음에 변수가 선언되었다면 글로벌하다고 할 수 있다. 말하자면 어느 기능에서나 쓰일 수 있다. 하지만 만일 아래와 같이 "draw()"안에서 선언된 변수라면 여타의 다른 범위, 즉 "setup()"이나 "draw2()"등의 범위 안에서는 사용될 수 없다. 때문에 변수, 그 쓰임새에 따라서 여러분들은 변수를 선언할 수 있다. 아래의 예제를 살펴보자. 같은 변수 "a"더라도 어느 곳에 선언되었는가에 따라 다르게 쓰일 수 있다. 만일 변수 "a"가 글로벌로 선언되었다고 할 지라도 아래와 같이 로컬로 다시 선언되었다면 글로벌 변수 "a"는 무시되고 로컬 "a"가 쓰이게 된다. 만일 로컬 변수 "a"가 선언되지 않았다면 변수는 글로벌 "a"가 쓰이게된다.














int a = 20;  // Create a global variable "a"


void setup()
{
size(200, 200);
background(51);
stroke(255);
noLoop();
}

void draw()
{
// Draw a line using the global variable "a"
line(a, 0, a, height);

// Create a new variable "a" local to the for() statement
for(int a=50; a<80; a += 2) {
line(a, 0, a, height);
}

// Create a new variable "a" local to the loop() method
int a = 100;
// Draw a line using the new local variable "a"
line(a, 0, a, height);

// Make a call to the custom function drawAnotherLine()
drawAnotherLine();

// Make a call to the custom function setYetAnotherLine()
drawYetAnotherLine();
}

void drawAnotherLine()
{
// Create a new variable "a" local to this method
int a = 185;
// Draw a line using the local variable "a"
line(a, 0, a, height);
}

void drawYetAnotherLine()
{
// Because no new local variable "a" is set,
// this lines draws using the original global
// variable "a" which is set to the value 20.
line(a+2, 0, a+2, height);
}

Charater and String: 문자와 문자열

여기서 "Character(문자)"란 여러분들이 치고 있는 타이프에 보이는 문자라 생각하면 될 것이고, "String(문자열)"이란 이러한 문자들의 나열을 의미한다. 좀 더 전문적으로 이해를 하려면 우리가 쓰고 있는 문자의 타입이 공인 인증된 방식으로 쓰이는 한 문자표현의 방식이라고 할 수 있는데 대표적인 것이 Unicode이다. 물론 프로세싱에서도 문자의 방식을 Unicode로 인식한다. 이러한 문자의 방식은 단지 표현의 방식을 의미하지는 않는다. 언어의 다양성에 따라서 여러가지 종류가 있다. 때문에 특수문자의 경우 어떻게 표현할 수 있을 지를 아마도 여러분들은 고민하게 될 것이다. 왜냐하면 한글의 경우는 좀 복잡하기 때문이다. 예를 들어 "'P'"라는 글자가 있을 때 이러한 "String"은 "'"과 "P", "'"의 연속된 기호라 할 수 있다.















 

PImage frog;
PFont font;
int xoffset;
char letter;

void setup()
{
size(200, 200, P2D);

font = loadFont("Eureka-90.vlw");
textFont(font);
// Draw text more accurately and efficiently.
textMode(SCREEN);
textAlign(CENTER);

// The String datatype must be capitalized because it is a complex datatype.
// A String is actually a class with its own methods, some of which are
// featured below.
String name = "rathausFrog";
String extension = ".jpg";
int nameLength = name.length();
println("The length of " + name + " is " + nameLength + ".");
name = name.concat(extension);
nameLength = name.length();
println("The length of " + name + " is " + nameLength + ".");

// The parameter for the loadImage() method must be a string
// This line could also be written "frog = loadImage("rathausFrog.jpg");
frog = loadImage(name);
}

void draw()
{
background(51); // Set background to dark gray

// Same as image(frog, xoffset, 0), but more efficient
// because no transformations or tint() or smooth() are used.
set(xoffset, 0, frog);

// Draw an X
line(0, 0, width, height);
line(0, height, width, 0);

// // Get the width of the letter
// float letterWidth = textWidth(letter);
//
// Draw the letter to the center of the screen
text(letter, width/2, height/2);
}

void keyPressed()
{
// The variable "key" always contains the value of the most recent key pressed.
// If the key is an upper or lowercase letter between 'A' and 'z'
// the image is shifted to the corresponding value of that key
if (key >= 'A' && key <= 'z') {
// Map the index of the key pressed from the range between 'A' and 'z',
// into a position for the left edge of the image. The maximum xoffset
// is the width of the drawing area minus the size of the image.
xoffset = int(map(key, 'A', 'z', 0, width - frog.width));
// Update the letter shown to the screen
letter = key;
// Write the letter to the console
println(key);
}
}