
import javax.swing.*;
import java.awt.*;
import java.util.Random;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

// move letter around on invisible grid using keyboard input alone

public class MoveLetter implements KeyListener {

	int x = 0;
	int y = 0;
	
	int font_size = 18;
	Font font = new Font("Monospace", Font.PLAIN, font_size);
	
	int char_h = 22;    // precomputed from FontMetrics block below for above parameters...
	int char_w = 19; 
	int char_ascent = 17;
	
	int panel_cols, panel_rows;
	int current_col, current_row;
	
	int panel_w, panel_h;   
	int win_w, win_h; 
	
	JFrame frame;
	MyDrawPanel drawPanel;
	
	//----------------------------------------------------------------------------

	public MoveLetter(int rows, int cols) 
	{
		panel_cols = rows;
		panel_rows = cols;

		current_col = panel_cols / 2;
		current_row = panel_rows / 2;
		
		panel_w = panel_cols * char_w;   // 400
		panel_h = panel_rows * char_h;   // 400
		win_w = panel_w + 5; //  
		win_h = panel_h + 30;
		
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		drawPanel = new MyDrawPanel();
		
		frame.getContentPane().add(drawPanel);
		frame.setSize(win_w, win_h);
		frame.setVisible(true);
	
		frame.addKeyListener(this);
		
		System.out.println("w = up, s = down, a = left, d = right");
		
	}
	
	//----------------------------------------------------------------------------

	static char rand_letter()
	{
		Random r = new Random();
		char c = (char)(r.nextInt(26) + 'A');
		return c;
	}
	
	//----------------------------------------------------------------------------

	public void keyTyped(KeyEvent evt)
	{
		
	}

	//----------------------------------------------------------------------------

	public void keyPressed(KeyEvent evt)
	{
		
	}
	
	//----------------------------------------------------------------------------

	public void keyReleased(KeyEvent evt)
	{		
		char ch = evt.getKeyChar();
	
		switch(ch){
	
		case 'w': 
			if (current_row > 0)
				current_row--;
			drawPanel.repaint();
			break;
		case 's': 
			if (current_row < panel_rows - 1)
				current_row++;
			drawPanel.repaint();
			break;
		case 'a': 
			if (current_col > 0)
				current_col--;
			drawPanel.repaint();
			break;
		case 'd': 
			if (current_col < panel_cols - 1)
				current_col++;
			drawPanel.repaint();
			break;
	
		}
	
	}
	
	//----------------------------------------------------------------------------

	public static void main(String[] args) 
	{
		MoveLetter gui = new MoveLetter(10, 10);
	}

	//----------------------------------------------------------------------------

	class MyDrawPanel extends JPanel {
		
		public void paintComponent(Graphics g)
		{
			g.setFont(font);
			
			g.setColor(Color.white);
			g.fillRect(0, 0, this.getWidth(), this.getHeight());
			
			g.setColor(Color.black);
			
			// current location
			
			x = current_col * char_w;
			y = char_ascent + current_row * char_h;
			g.drawString("X", x, y);
			
		}
	}
}
