Public feed
#603559
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.regex.*;
import java.util.*;
public class JLogo extends JFrame {
private JTextArea textarea;
private JPanel jp;
private int tx, ty, angulo;
private String errores;
ArrayList instrucciones = new ArrayList();
JLogo()
{
super("JLogo");
setLayout( new GridLayout(1, 3));
Box bx = Box.createVerticalBox();
textarea = new JTextArea( "", 10, 15 );
bx.add( new JScrollPane( textarea ), BorderLayout.CENTER );
JButton button = new JButton ( " Dibujar ", new ImageIcon( getClass().getResource("/img/visual.png") ) );
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
analizar();
}
});
bx.add( button );
add(bx, BorderLayout.EAST);
jp = new JPanel();
jp.setSize( 600, 300 );
jp.setBackground( Color.WHITE );
add( jp, BorderLayout.WEST);
}
public void analizar()
{
if( !analizarOrdenes( textarea.getText() ) )
{
// Error de sintaxis
JOptionPane.showMessageDialog( null, errores );
}
else
{
// Dibujar instrucciones
moverTortuga();
}
}
public void moverTortuga()
{
Graphics g = jp.getGraphics();
tx = (jp.getWidth() / 2);
ty = (jp.getHeight() / 2);
Pattern reg = Pattern.compile("([a-z]+)(\\s+)([0-9]+)");
Matcher ma;
String ex, move;
int num, ntx = tx, nty = ty;
Color col = Color.BLACK;
instrucciones.trimToSize();
for( Iterator it = instrucciones.iterator(); it.hasNext(); )
{
move = (String) it.next();
try
{
if( move.equals("levantarpluma") )
{
col = Color.WHITE;
}
else if( move.equals("bajarpluma") )
{
col = Color.BLACK;
}
else
{
g.setColor( col );
ma = reg.matcher( move );
while( ma.find() )
{
ex = ma.group(1);
num = Integer.parseInt( ma.group(3) );
if( ex.equals("dibuja") )
{
ntx = tx + (int)(Math.cos((angulo * Math.PI / 180)) * num);
nty = ty + (int)(Math.sin((angulo * Math.PI / 180)) * num);
g.drawLine( tx, ty, ntx, nty );
tx = ntx;
ty = nty;
}
else if( ex.equals("derecha") )
{
angulo += num;
while( angulo >= 360 )
angulo = (angulo - 360);
}
else if( ex.equals("izquierda") )
{
angulo -= num;
while( angulo < 0 )
angulo = (angulo + 360);
}
}
}
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
private boolean analizarOrdenes(String str)
{
str = str.replaceAll("/\\*([\\w\\W]+)\\*/", "");
StringTokenizer tk = new StringTokenizer(str, "\n");
int lines = 0;
boolean comp = true;
String cline = "";
errores = "";
//instrucciones.clear();
//angulo = 270;
while( tk.hasMoreTokens())
{
lines++;
cline = tk.nextToken().trim().toLowerCase();
if( cline.equals("") )
{
//Linea ignorada
}
else if( (cline.matches("(dibuja|derecha|izquierda){1}((\\s|\\t)+)([0-9]+)((\\s|\\n|\\t)?)")) || cline.matches("(levantarpluma|bajarpluma)") )
{
instrucciones.add(cline);
}
else
{
errores += "Error en linea " + lines + ": " + cline + "\n";
comp = false;
}
}
return comp;
}
public static void main(String[] args)
{
JLogo jl = new JLogo();
jl.setSize(600, 500);
jl.setVisible(true);
jl.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}