1

Всем привет, я снова с глупым вопросом по Swi-prolog. В чём суть - у меня есть файл, с которого я должен отталкиваться для вывода картинки на экран.

% draw(+Size)
% draws a graphics with a given Size

draw(Size) :-
   % define size of the display (picture size + scroll bar area)
   SizeD is Size+20,
   % create a new display and open it
   new(Display,picture('*** Window with Pictire ***',size(SizeD,SizeD))),
   send(Display,open),
   send(Display,background,colour(black)), %* MK: ggf. Farbe auf 'white' stellen

   % draw the object on the display
   (
        draw_object(Display,Size,Size /* , ***add additional parameters if needed *** */);
        true
   ),
   % if desired save the display as .jpg
   write_ln('Save the graphics (y/n): '),
   get_single_char(A),
   put_code(A),nl,
   (A=:=121 ->
     (write_ln('enter file name: '),
      read_line_to_codes(user_input,X),
      atom_codes(File,X),
      atom_concat(File,'.jpg',FileName),
      get(Display,image,Image),
      send(Image,save,FileName,jpeg) ) ; true ),

   !.


% draw_object(Display,Size,CurrentSize,*** add additional parameters here, if needed ***)
% draws a gradient graphics of size Size into Display
% CurrentSize is decreased recursively fom Size to 0
draw_object(_,_,0 /* , *** add additional parameters here, if needed *** */). 
draw_object(Name,Size,CSize /* , *** add additional parameters here, if needed *** */) :- 
   CSize > 0 ,        % only for positive integers

  % *** insert the computation of graphical parameters here ***

  % *** create and draw the current graphical object here ***

  % *** send all additional parameters to the current graphical object ***

  % decrement CurrentSize and call draw_object recursively
  CSizeNew is CSize - 2,

% writeln(CSizeNew),
  draw_object(Name,Size,CSizeNew).



% Call the program and see the result
:- draw( 400 ).   % specify the desired display size in pixel here (required argument)   




% ========== Tests from XPCE-guide Ch 5 ==========

% destroy objects
mkfree :-
   free(@p),
   free(@bo),
   free(@ci),
   free(@bm),
   free(@tx),
   free(@bz).

% create picture / window
mkp :-
   new( @p , picture('Demo Picture') ) ,
   send( @p , open ).

% generate objects in picture / window
mkbo :-
   send( @p , display , new(@bo,box(100,100)) ).
mkci :-
   send( @p , display , new(@ci,circle(50)) , point(25,25) ).
mkbm :-
   send( @p , display , new(@bm,bitmap('32x32/books.xpm')) , point(100,100) ).
mktx :-
   send( @p , display , new(@tx,text('Hello')) , point(120,50) ).
mkbz :-
   send( @p , display , new(@bz,bezier_curve(
     point(50,100),point(120,132),point(50,160),point(120,200))) ).

% modify objects
mkboc :-
   send( @bo , radius , 10 ).
mkcic :-
   send( @ci , fill_pattern , colour(orange) ).
mktxc :-
   send( @tx , font , font(times,bold,18) ).
mkbzc :-
   send( @bz , arrows , both ).

Проблема в том, что я не понимаю, как оно работает и как я могу вывести на экран даже вот эти тестовые данные. Например, если я просто открываю файл, то у меня автоматом появляется окошко с чёрным фоном. Та самая картинка

Но при этом я не могу вызвать предикаты из командной строки.

?- mkp.
ERROR: Unknown procedure: kp/0 (DWIM could not correct goal)

Если я вставляю после комментария

 % *** create and draw the current graphical object here ***

код, например, такой:

mkbo :-
        send( Display , display , new(Display,box(100,100)) ).

то при вызове файла появляется только чёрное окно без ожидаемого мною квадрата в нём, зато в консоли есть следующие ошибки:

ERROR: j:/grafik.pl:38:89: Syntax error: Operator priority clash
Warning: j:/grafik.pl:50:
Warning:    Singleton variables: [CSize,Name,Size]
ERROR: j:/grafik.pl:50:
ERROR:    Full stop in clause-body?  Cannot redefine ,/2

(при это все) ссылаются на строку 50:

CSizeNew is CSize - 2,

Если я закрываю окно сразу после старта и пытаюсь вызвать предикат, например, mkp, то при попытке вызова любого теста вылезает ошибки с Syntax Error и ссылками на все строками с тестами.

Может мне кто-нибудь объяснить, как я могу вывести на экран эти вот самые тестовые данные (квадрат, круг, кривая Безье итд)?

1 ответ 1

1

С большим трудом но всё же осилил. Моя проблема была в том, что не изменял цвет и после создания объекта, перед отправкой на дисплей надо указывать цвет отличный от фона, например:

new(Line, bezier_curve( point(Size2,CSize),point(CSize,Size), point(CSize,0),point(0,CSize))),
send(Line, colour(orange)),
send(Name, display, Line1)

Ну и полный пример итоговой программы (рисует много кривых Безье):

% draw(+Size)
% draws a graphics with a given Size


draw(Size) :-
   % define size of the display (picture size + scroll bar area)
   SizeD is Size+20,
   % create a new display and open it
   new(Display,picture('bezier curven',size(SizeD,SizeD))),
   send(Display,open),
   send(Display,background,colour(black)), %* MK: ggf. Farbe auf 'white' stellen
   % draw the object on the display
   (
        draw_object(Display,Size,Size /* , ***add additional parameters if needed *** */);
        true
   ),
   % if desired save the display as .jpg
   write_ln('Save the graphics (y/n): '),
   get_single_char(A),
   put_code(A),nl,
   (A=:=121 ->
     (write_ln('enter file name: '),
      read_line_to_codes(user_input,X),
      atom_codes(File,X),
      atom_concat(File,'.jpg',FileName),
      get(Display,image,Image),
      send(Image,save,FileName,jpeg) ) ; true ),

   !.


% draw_object(Display,Size,CurrentSize,*** add additional parameters here, if needed ***)
% draws a gradient graphics of size Size into Display
% CurrentSize is decreased recursively fom Size to 0
draw_object(_,_,0 /* , *** add additional parameters here, if needed *** */). 
draw_object(Name,Size,CSize /* , *** add additional parameters here, if needed *** */) :- 

   CSize > 0 ,        % only for positive integers

   % *** insert the computation of graphical parameters here ***
   Size1 is CSize*(1)/2,
   Size2 is CSize*(-1),
   Size3 is CSize*(-2)/3,
   Size4 is CSize*(1)/3,
   Size5 is CSize*(2)/3,

   new(_, colour(col1, 60000, 0, 20000, rgb)),
   new(_, colour(col2, 0, 60000, 12000, rgb)),


  % *** create and draw the current graphical object here ***
  new(Line1, bezier_curve( point(Size2,CSize),point(CSize,Size), point(CSize,0),point(0,CSize))),
  send(Line1, colour(col2)),
  send(Name, display, Line1),

  new(Line2, bezier_curve(point(CSize,Size2),point(Size3,CSize), point(0,CSize),point(CSize,0))),
  send(Line2, colour(col1)),
  send(Name, display, Line2),

  new(Line3, bezier_curve(point(Size3,Size3), point(Size,Size), point(Size2,0), point(0,Size2))),
  send(Line3, colour(orange)),
  send(Name, display, Line3),

  new(Line4, bezier_curve(point(Size1,Size5), point(Size3,Size4), point(Size5,0), point(0,Size4))),
  send(Line4, colour(red)),
  send(Name, display, Line4),

  % decrement CurrentSize and call draw_object recursively
  CSizeNew is CSize - 5,

  draw_object(Name,Size,CSizeNew).

% Call the program and see the result
:- draw( 1000 ).   % specify the desired display size in pixel here (required argument)   

Результат:

Итог

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.