program move_char;
@projectsettings "system" SPECTRUM
@use "text/txt"
@use memory
var
	
	
	instruction_str: string = ("USE CURSORS/QAOP",0);
	
	key_press: byte=0;
	charat:byte;
	x,y,oldx,oldy: byte;
	this_row: integer;
	
	
begin

	// Clear screen,
	txt::cls();
	
	for this_row:=0 to 18 do
	begin
		txt::print_space(22);		
	end;
	
	
	txt::cursor_off();
	txt::move_to(4,0);
	txt::print_string(#instruction_str, False);
	


	// Test outputting consecutive rows
	// due to Apple II maddening screen memory scheme	
	fori y:= 0 to 18 do
	begin

		txt::put_char_at(3,y,y+$30);
		txt::put_char_at(20,y,64);
		
	end;
	
	// Initialise start position
	x:=10;
	y:=10;	
	txt::put_char_at(x,y,64);

	// Main loop
	while(1) do
	begin
		
		Memory::VSync();
		
		// Get keyboard input
		key_press:=txt::get_key();

		
		@ifdef X86
		key_press:=txt::LATEST_SCANCODE;
		@endif
		


		// Backup the current position			
		oldx:=x;
		oldy:=y;

			// Check the pressed key
			case key_press of
		       
				// Cursor keys defined in unit		        
				txt::CUR_U: if(y>0) then y-=1;
				txt::CUR_D: if(y<20) then y+=1;
				txt::CUR_L: if(x>0) then x-=1;
				txt::CUR_R: if(x<32) then x+=1;
		        
		        
			end;
			

			// Find out if the space we want to move to
			// is empty or if it contains anything special
			charat:=txt::get_char_at(x,y);

			
			@ifdef APPLEII
			togglebit(charat,7,0);
			@endif
			
			

			
			// $20 is space
			if(charat=$20 or charat=64) then
			begin
				
				// Keep the new position and output
				// our @ symbol
				txt::put_char_at(oldx,oldy,32);
	
			end
			else
			begin
				if(charat<>64) then
				begin
					txt::beep();
					txt::put_char_at(1,1,charat);
					txt::move_to(0,3);
					txt::print_dec(charat,false);
				end;
				x:=oldx;
				y:=oldy;

			end;

			// Draw our dude
			txt::put_char_at(x,y,64);
		
	end;

		
	loop();
		
end.

