Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Основная";
Текущий архив: 2002.08.05;
Скачать: [xml.tar.bz2];

Вниз

Толи я туплю, толи Delphi…   Найти похожие ветки 

 
Matrics   (2002-07-22 17:13) [0]

Толи я туплю, толи Delphi…

Помогите разобраться пожалуйста…

Задача:
На форме лежат Image & Button, в Image загружена картинка, Button имеет высоту и ширину 9 п.
При нажатии на клавиши вниз, вверх, влево, вправо на дополнительной клавиатуре, кнопочка должна соответственно двигаться по картинке, если правда ей не мешает «препятствие», у меня это черный цвет на картинке, то есть, кнопку можно двигать в стороны, пока она «не ударится» об какую-нибудь фигурку черного цвета нарисованную на Image…
Ну в общем понятно, да?
Код я написал, вот:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Menus;

type
TForm1 = class(TForm)
Image1: TImage;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
x,y: integer;
can: boolean;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
x := 8;
y := 12;
can := true;
end;

procedure TForm1.Button1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=102 then
begin
if (image1.Canvas.Pixels[x+9,y]) and (image1.Canvas.Pixels[x+9,y+1]) and (image1.Canvas.Pixels[x+9,y+2]) and (image1.Canvas.Pixels[x+9,y+3]) and (image1.Canvas.Pixels[x+9,y+4]) and (image1.Canvas.Pixels[x+9,y+5]) and (image1.Canvas.Pixels[x+9,y+6]) and (image1.Canvas.Pixels[x+9,y+7]) and (image1.Canvas.Pixels[x+9,y+8])=clBlack then
can := False
else
can := True;
if can then
begin
x := x+1;
button1.Left := x;
end;
end;

if key=100 then
begin
if (image1.Canvas.Pixels[x-1,y]) and (image1.Canvas.Pixels[x-1,y+1]) and (image1.Canvas.Pixels[x-1,y+2]) and (image1.Canvas.Pixels[x-1,y+3]) and (image1.Canvas.Pixels[x-1,y+4]) and (image1.Canvas.Pixels[x-1,y+5]) and (image1.Canvas.Pixels[x-1,y+6]) and (image1.Canvas.Pixels[x-1,y+7]) and (image1.Canvas.Pixels[x-1,y+8])=clBlack then
can := False
else
can := True;
if can then
begin
x := x-1;
button1.Left := x;
end;
end;

if key=104 then
begin
if (image1.Canvas.Pixels[x,y-1]) and (image1.Canvas.Pixels[x+1,y-1]) and (image1.Canvas.Pixels[x+2,y-1]) and (image1.Canvas.Pixels[x+3,y-1]) and (image1.Canvas.Pixels[x+4,y-1]) and (image1.Canvas.Pixels[x+5,y-1]) and (image1.Canvas.Pixels[x+6,y-1]) and (image1.Canvas.Pixels[x+7,y-1]) and (image1.Canvas.Pixels[x+8,y-1])=clBlack then
can := False
else
can := True;
if can then
begin
y := y-1;
button1.Top := y;
end;
end;

if key=98 then
begin
if (image1.Canvas.Pixels[x,y+9]) and (image1.Canvas.Pixels[x+1,y+9]) and (image1.Canvas.Pixels[x+2,y+9]) and (image1.Canvas.Pixels[x+3,y+9]) and (image1.Canvas.Pixels[x+4,y+9]) and (image1.Canvas.Pixels[x+5,y+9]) and (image1.Canvas.Pixels[x+6,y+9]) and (image1.Canvas.Pixels[x+7,y+9]) and (image1.Canvas.Pixels[x+8,y+9])=clBlack then
can := False
else
can := True;
if can then
begin
y := y+1;
button1.Top := y;
end;
end;

end;

end.


Вроде работает нормально, но все-таки глючит, то она ездит то нет, вот например, картинка у меня вся зеленного цвета, а посреди синий прямоугольник, так вот, ставлю кнопку так, чтобы половина была на зеленом, половина на синем – вниз вверх ездит, а в стороны нет! Почему, ведь черного нигде нету?!
Точно также я сделал второй раз, только нарисовал вместо синего прямоугольника, желтый, и все работало!
Таких примеров можно привести много…
В чем тут дело, может в коде, может Windows дальтоник?

Помогите, мастера, пожалуйста!


 
Skier   (2002-07-22 17:21) [1]

>Matrics
Ну...для начала поставь везде вместо своих констант,
дельфийские :

VK_LEFT
VK_UP
VK_RIGHT
VK_DOWN


 
TTCustomDelphiMaster   (2002-07-22 17:45) [2]


> Толи я туплю, толи Delphi

Однозначно первое :)

> if (image1.Canvas.Pixels[x+9,y]) and (image1.Canvas.Pixels[x+9,y+1])
> and (image1.Canvas.Pixels[x+9,y+2]) and (image1.Canvas.Pixels[x+9,y+3])
> and (image1.Canvas.Pixels[x+9,y+4]) and (image1.Canvas.Pixels[x+9,y+5])
> and (image1.Canvas.Pixels[x+9,y+6]) and (image1.Canvas.Pixels[x+9,y+7])
> and (image1.Canvas.Pixels[x+9,y+8])=clBlack

В этой строчке выполняется операция AND над значениями цвета точек, расположенных вокруг кнопки. В результате получается непонятно какой цвет. После этого он сравнивается с черным.
Допустим все точки синего цвета ($00FF0000), тогда операция $00FF0000 and $00FF0000 вернет $00FF0000, что не равно $00000000 (черный цвет).
А если одна точка зеленая, то $00FF0000 and $0000FF00 равно $00000000 - черный цвет и кнопка двигаться естественно не будет.


 
Matrics   (2002-07-22 18:01) [3]


> TTCustomDelphiMaster © (22.07.02 17:45)

А как правильно будет? Чем этот код можно заменить?


 
TTCustomDelphiMaster   (2002-07-22 18:09) [4]


> Matrics (22.07.02 18:01)
>
> > TTCustomDelphiMaster © (22.07.02 17:45)
>
> А как правильно будет? Чем этот код можно заменить?


Если сам не придумаешь, то как ты будешь дальше программы писать?

ЗЫ: Может Skier поможет. Он любит программы у которых ошибка в 17 строке :)


 
Skier   (2002-07-22 18:10) [5]

>TTCustomDelphiMaster
Это ему дорого станет... :)


 
Matrics   (2002-07-22 18:20) [6]

Ну пожалуйста!


 
Skier   (2002-07-22 18:24) [7]

>Matrics
А ты что пишешь ?
Блуждание по лабиринту ? :))


 
Matrics   (2002-07-22 18:27) [8]

В общем, да.
Помогите пожалуйста, я в Delphi несилен!


 
Matrics   (2002-07-22 19:08) [9]

Ну пожалуйста! Помогите новичку


 
Skier   (2002-07-22 19:19) [10]

>Matrics
Могу на выходных повозится...если будет время.


 
Matrics   (2002-07-22 19:32) [11]

Вроде я понял, проверьте пожалуйста как код:

if key=102 then
begin
if (image1.Canvas.Pixels[x+9,y])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+1])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+2])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+3])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+4])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+5])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+6])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+7])<>clBlack then
if (image1.Canvas.Pixels[x+9,y+8])<>clBlack then
begin
x := x+1;
button1.Left := x;
end;
end;

if key=100 then
begin
if (image1.Canvas.Pixels[x-1,y])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+1])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+2])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+3])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+4])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+5])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+6])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+7])<>clBlack then
if (image1.Canvas.Pixels[x-1,y+8])<>clBlack then
begin
x := x-1;
button1.Left := x;
end;
end;

if key=104 then
begin
if (image1.Canvas.Pixels[x,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+1,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+2,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+3,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+4,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+5,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+6,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+7,y-1])<>clBlack then
if (image1.Canvas.Pixels[x+8,y-1])<>clBlack then
begin
y := y-1;
button1.Top := y;
end;
end;

if key=98 then
begin
if (image1.Canvas.Pixels[x,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+1,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+2,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+3,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+4,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+5,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+6,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+7,y+9])<>clBlack then
if (image1.Canvas.Pixels[x+8,y+9])<>clBlack then
begin
y := y+1;
button1.Top := y;
end;
end;


По-моему, даже очень неплохо получилось…


 
TTCustomDelphiMaster   (2002-07-22 20:16) [12]


> Matrics (22.07.02 19:32)

Отлично!

ЗЫ:
А вот как должно было выглядеть сначала:
if key=VK_RIGHT then
if (image1.Canvas.Pixels[x+9,y]<>clBlack) and
(image1.Canvas.Pixels[x+9,y+1]<>clBlack) and
...
(image1.Canvas.Pixels[x+9,y+8]<>clBlack) then
begin
x := x+1;
button1.Left := x;
end;


 
Billy   (2002-07-23 00:26) [13]

Учитывая специфику данного вопроса (то, что все точки должны быть чёрными) и тот факт, что черный цвет - это $000000, то можно пермножить все точки и сравнить результат с 0.


 
TTCustomDelphiMaster   (2002-07-23 10:50) [14]

Billy © (23.07.02 00:26)

Перемножать все цвета тоже нельзя, потому что на рисунках с преобладанием синего цвета в результате перемножения получится черный.
Свойство Pixels возвращает 4 байта цвета точки. Четырех байтные величины заносятся в регистры процессора и перемножаются командой imul. Результат этой операции тоже помещается в регистр процессора. При перемножении двух синих цветов $00FF0000 * $00FF0000 получаем $FE0100000000, при этом результат равен младшим четырем байтам $00000000 (уже черный) и включается флаг переполнения CF. Этот результат сравнивается с черным цветом.



Страницы: 1 вся ветка

Форум: "Основная";
Текущий архив: 2002.08.05;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.49 MB
Время: 0.007 c
1-13609
Filat
2002-07-24 19:59
2002.08.05
Вот уж не думал, что тут не будет работать.......


4-13852
roadstar
2002-05-29 14:24
2002.08.05
Как програмно открыть папку


14-13819
DenKop
2002-07-10 02:01
2002.08.05
Вопрос любителям PIC и I2S


1-13687
Администратор
2002-07-23 23:05
2002.08.05
Плорер.. ;)


1-13613
MARcoDEN
2002-07-23 21:28
2002.08.05
Combining signed and unsigned types





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский