PDA

View Full Version : Implementing a Turtle Viewing System



RobinD
10-22-2011, 07:15 PM
Hi,
I'm trying to create a library of functions that draws lines using a turtle object. The turtle has a pen which it can set up or down, it can also move forward and rotate. The problem I'm having is that when I try to run the program, only a white window appears, regardless of the clear color I set. Can you please help?
Here's my code:
/*******TurtleNoLib.h*******/
#ifndef TURTLE_H
#define TURTLE_H

#include<cmath>
#include<iostream>
using namespace std;

#include<GL/glut.h>

#define PI 3.14159265

class Turtle{
public:
//constructors
Turtle();
Turtle(GLint x, GLint y, GLfloat theta);
//members
enum status {UP, DOWN};
GLfloat pos[2];
GLfloat angle;
int tPen;
//methods
void init(GLint x, GLint y, GLfloat theta);
void right(GLfloat theta);
void left(GLfloat theta);
void forward(GLfloat distance);
void pen(status s);
};
//constructors
Turtle::Turtle(){
pos[0] = 0.0;
pos[1] = 0.0;
angle = 45.0;
tPen = UP;
}
Turtle::Turtle(GLint x, GLint y, GLfloat theta){
pos[0] = x;
pos[1] = y;
angle = theta;
tPen = UP;
}
//methods
void Turtle::init(GLint x, GLint y, GLfloat theta){
angle = theta;
pos[0] = x;
pos[1] = y;
}
void Turtle::right(GLfloat theta){
angle += theta;
}
void Turtle::left(GLfloat theta){
angle -= theta;
}
void Turtle::forward(GLfloat distance){
GLfloat old[2], direc[2];
//store initial turtle position
old[0] = pos[0];
old[1] = pos[1];

//convert angle to radians
GLfloat a;
a = Turtle::angle/180.0 * PI;

//init directional vector
direc[0] = cos(a);
direc[1] = sin(a);

//update position
for(int i = 0; i < 2; i++){
pos[i] = distance * direc[i];
}
//if pen down draw line
if(tPen == DOWN){
glBegin(GL_LINES);
glVertex2fv(old);
glVertex2fv(pos);
glEnd();
glFlush();
}
}
void Turtle::pen(status s){
tPen = s;
}
#endif

/*******TurtleNoLib.cpp*******/
#include "TurtleNoLib.h"

void myInit(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
glMatrixMode(GL_MODELVIEW);

glClearColor(0.0, 1.0, 1.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}

void display(){
//initialize turtle
Turtle turtle(0.0, 0.0, 45.0);
//draw line across screen
turtle.tPen = Turtle::DOWN;
turtle.forward(2.0);

glFlush();
}

int main(int argc, char **argv){
glutInit(&amp;argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(300, 300);
glutInitWindowPosition(0, 0);
glutCreateWindow("Turtle");
glutDisplayFunc(display);
myInit();
glutMainLoop();
}