Форум программистов, компьютерный форум, киберфорум
PascalABC.NET
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.55/11: Рейтинг темы: голосов - 11, средняя оценка - 4.55
Alvin Seville
 Аватар для Соколиный глаз
343 / 273 / 134
Регистрация: 25.07.2014
Сообщений: 4,537
Записей в блоге: 22

System.NullReferenceException: Ссылка на объект не указывает на экземпляр объекта

15.07.2017, 11:39. Показов 2085. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Internal compiler error in module [pabcnetc.exe] :'System.Exception: System.NullReferenceException: Ссылка на объект не указывает на экземпляр объекта.
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.hard_node_test_and_visit(syntax_tree_node tn)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit_procedure_header(procedure_header _procedure_header)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit_type_list(List`1 types)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(template_type_reference _template_type_reference)
   в PascalABCCompiler.TreeConverter.returner.visit(type_definition type_def)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.convert_strong(type_definition type_def)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(var_def_statement _var_def_statement)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(class_members _class_members)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(class_body _class_body)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(class_definition _class_definition)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(type_declaration _type_declaration)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(type_declarations _type_declarations)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(declarations _subprogram_definitions)
   в PascalABCCompiler.TreeConverter.syntax_tree_visitor.visit(unit_module _unit_module)
   в PascalABCCompiler.TreeConverter.SyntaxTreeToSemanticTreeConverter.CompileInterface(compilation_unit SyntaxUnit, unit_node_list UsedUnits, List`1 ErrorsList, List`1 WarningsList, SyntaxError parser_error, Hashtable bad_nodes, using_namespace_list namespaces, Dictionary`2 docs, Boolean debug, Boolean debugging)
   в PascalABCCompiler.Compiler.CompileUnit(unit_node_list Units, unit_or_namespace SyntaxUsesUnit)
   в PascalABCCompiler.Compiler.CompileUnit(unit_node_list Units, unit_or_namespace SyntaxUsesUnit)
   в PascalABCCompiler.Compiler.Compile()'
Добавлено через 3 минуты
Исключение начало вылетать при компиляции кода и мини-игрового движка:
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
unit GameEngine;
 
uses GraphABC, Timers;
 
type
  SpriteBorderStyle = (bsRectangle, bsEllipse);
 
type
  KeyList = class
  private 
    Keys: List<char>;
    Procedures: List<procedure>;
  public 
    constructor ();begin Keys := new List<char>();Procedures := new List<procedure>(); end;
    
    ///Adds new key to list.
    procedure Add(key: char; p: procedure);
    begin
      Keys.Add(key);Procedures.Add(p);
    end;
    
    ///Removes object from objects list.
    function Remove(key: char; p: procedure): boolean;
    begin
      var a := Keys.Remove(key);
      var b := Procedures.Remove(p);
      Result := a and b;
    end;
    
    ///Count.
    function Count()  := Keys.Count;
    
    ///Run procedure.
    function Run(key: char) := Procedures[Keys.IndexOf(key)];
  end;
  
  //Physics and vizualization.
  GameObjectOptions = class
  private 
    xP, yP, wP, hP: int64;
    VelocityXP, VelocityYP: int64;
    KeysP: KeyList;
    
    procedure KeyDown(Key: integer);
    begin
      try
        KeysP.Run(Key);
      except 
        on Exception do end;
    end;
  
  public 
      ///X coordinate of high left angle.
    property X: int64 read xP write xP;
    ///Y coordinate of high left angle.
    property Y: int64 read yP write yP;
    ///Width.
    property W: int64 read wP write wP;
    ///Height.
    property H: int64 read hP write hP;
    ///Velocity X.
    property VelocityX: int64 read VelocityXP write VelocityXP;
    ///Velocity Y.
    property VelocityY: int64 read VelocityYP write VelocityYP;
    ///Velocity Y.
    property Keys: KeysList read KeysP write KeysP;
    
    constructor ();begin Keys := new KeyList(); OnKeyDown := KeyDown; end;
  end;
  
  
  Sprite = class(GameObjectOptions)
  private 
    visibleP: boolean;
    BorderColorP: Color;
    BorderWidthP: integer;
    BorderStyleP: SpriteBorderStyle;
    FillColorP: Color;
    ImageP: Picture;
  
  public 
    ///Visibility.
    property Visibile: boolean read visibleP write visibleP;
    ///Border's color.
    property BorderColor: Color read BorderColorP write BorderColorP;
    ///Border's width.
    property BorderWidth: integer read BorderWidthP write BorderWidthP;
    ///Border's width.
    property BorderStyle: SpriteBorderStyle read BorderStyleP write BorderStyleP;
    ///Filling color.
    property FillColor: Color read FillColorP write FillColorP;
    ///Picture to be drawed instead FillColor.
    property Image: Picture read ImageP write ImageP;
    
    constructor ();begin Visibile := true;BorderStyle := bsRectangle;BorderColor := clBlack;FillColor := clGray; end;
    
    ///Draws game object.
    procedure Draw();
    begin
      try
        if Visibile and (X + W >= 0) and (Y + H >= 0) and (X <= Window.Width) and (Y <= Window.Height) then
        begin
          if Image = nil then
          begin
            SetBrushColor(FillColor);
            case BorderStyle of
              bsRectangle: FillRect(X, Y, X + W, Y + H);
              bsEllipse: FillEllipse(X, Y, X + W, Y + H);
            end;
          end
          else
          begin
            Image.Width := W;
            Image.Height := H;
            Image.Draw(X, Y);
          end;
          SetPenColor(BorderColor);
          SetPenWidth(BorderWidth);
          case BorderStyle of
            bsRectangle: DrawRectangle(X, Y, X + W, Y + H);
            bsEllipse: DrawEllipse(X, Y, X + W, Y + H);
          end;
        end;
        X := X + VelocityX;
        Y := Y + VelocityY;
      except 
        on Exception do end;
    end;
  end;
 
type
  ///List of game objects.
  ObjectsList = class
  private 
    ObjectsP: List<Sprite>;
  
  public 
    constructor ();begin ObjectsP := new List<Sprite>(); end;
    
    ///Adds new object to objects list.
    procedure Add(obj: Sprite) := ObjectsP.Add(obj);
    ///Removes object from objects list.
    function Remove(obj: Sprite) := ObjectsP.Remove(obj);
    ///Represents objects list as array.
    function AsArray(obj: Sprite) := ObjectsP.ToArray();
    ///Count.
    function Count()  := ObjectsP.Count;
    ///Returns game object.
    function GetObject(i: integer) := ObjectsP.Item[i];
  end;
 
//Scene and vizualization.
type
  ///Game scene.
  Scene = class
  private 
    backgroundP: Color;
    ObjectsP: ObjectsList;
  public 
    ///Background color of the scene.
    property Background: Color read backgroundP write backgroundP;
    ///Objects in scene.
    property Objects: ObjectsList read ObjectsP write ObjectsP;
    
    constructor ();begin Objects := new ObjectsList(); end;
    
    procedure Draw();
    begin
      ClearWindow;
      SetBrushColor(Background);
      FillRectangle(0, 0, Window.Width, Window.Height);
      for var i := 0 to Objects.Count - 1 do Objects.GetObject(i).Draw();
      Redraw;
    end;
  end;
  
  ///Game options.
  GameOptions = class
  private 
    class MainTimerP: Timer;
    class ActiveScene: Scene;
  
  public 
    ///Initializes game.
    class procedure GameStart(scn: Scene; str: string);
    begin
      SetWindowCaption(str);
      MainTimerP := new Timer(1, scn.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets active scene.
    class procedure SetActiveScene(scn: Scene);
    begin
      ActiveScene := scn;
      MainTimerP := new Timer(1, ActiveScene.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets interval between frames drawing.
    class procedure SetInterval(i: integer) := MainTimerP.Interval := i;
  end;
 
initialization
  LockDrawing;
end.
Так, и программы для его тестирования:
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
uses GameEngine, GraphABC;
var
  Scn: Scene;
  Square: Sprite;
 
procedure Stop();
begin
  Square.VelocityX := 0;Square.VelocityY := 0;
end;
 
begin
  Square := new Sprite();
  Square.X := 10;Square.Y := 10;
  Square.W := 50;Square.H := 50;
  Square.VelocityX := 2;Square.VelocityY := 2;
  Square.FillColor := clRed;
  Square.BorderColor := clOrange;
  Square.Keys.Add(GraphABC.VK_Enter, Stop);
  
  Scn := new Scene();
  Scn.Background := clLightCyan;
  Scn.Objects.Add(Square);
  
  GameOptions.GameStart(Scn, 'Square');
end.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
15.07.2017, 11:39
Ответы с готовыми решениями:

Ссылка на объект не указывает на экземпляр объекта
Здравствуйте. Помогите, пожалуйста, разобраться с ошибкой и причиной ее возникновения, а также подскажите, пожалуйста, способ ее...

Ссылка на объект не указывает на экземпляр объекта
При попытке компиляции возникает ошибка в данной функции(сейчас строка №9): Ошибка времени выполнения: Ссылка на объект не указывает на...

Ссылка на объект не указывает на экземпляр объекта
вот код uses graphABC, ABCobjects; var xPlayer, yPlayer, speedPlayer, damagePlayer, speedBall, xBall, yBall: integer; spritePlayer,...

6
Супер-модератор
Эксперт Pascal/DelphiАвтор FAQ
 Аватар для volvo
33374 / 21499 / 8235
Регистрация: 22.10.2011
Сообщений: 36,894
Записей в блоге: 11
15.07.2017, 12:16
Лучший ответ Сообщение было отмечено Volobuev Ilya как решение

Решение

Вот так не вылетает:
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
unit GameEngine;
 
uses GraphABC, Timers;
 
type
  SpriteBorderStyle = (bsRectangle, bsEllipse);
 
type
  pr = procedure;
  KeyList = class
  private 
    Keys: List<char>;
    Procedures: List<pr>;
  public 
    constructor ();begin Keys := new List<char>();Procedures := new List<pr>(); end;
    
    ///Adds new key to list.
    procedure Add(key: char; p: pr);
    begin
      Keys.Add(key);Procedures.Add(p);
    end;
    
    ///Removes object from objects list.
    function Remove(key: char; p: pr): boolean;
    begin
      var a := Keys.Remove(key);
      var b := Procedures.Remove(p);
      Result := a and b;
    end;
    
    ///Count.
    function Count()  := Keys.Count;
    
    ///Run procedure.
    function Run(key: char) := Procedures[Keys.IndexOf(key)];
  end;
  
  //Physics and vizualization.
  GameObjectOptions = class
  private 
    xP, yP, wP, hP: int64;
    VelocityXP, VelocityYP: int64;
    KeysP: KeyList;
    
    procedure KeyDown(Key: integer);
    begin
      try
        KeysP.Run(Key);
      except 
        on Exception do end;
    end;
  
  public 
      ///X coordinate of high left angle.
    property X: int64 read xP write xP;
    ///Y coordinate of high left angle.
    property Y: int64 read yP write yP;
    ///Width.
    property W: int64 read wP write wP;
    ///Height.
    property H: int64 read hP write hP;
    ///Velocity X.
    property VelocityX: int64 read VelocityXP write VelocityXP;
    ///Velocity Y.
    property VelocityY: int64 read VelocityYP write VelocityYP;
    ///Velocity Y.
    property Keys: KeysList read KeysP write KeysP;
    
    constructor ();begin Keys := new KeyList(); OnKeyDown := KeyDown; end;
  end;
  
  Sprite = class(GameObjectOptions)
  private 
    visibleP: boolean;
    BorderColorP: Color;
    BorderWidthP: integer;
    BorderStyleP: SpriteBorderStyle;
    FillColorP: Color;
    ImageP: Picture;
  
  public 
    ///Visibility.
    property Visibile: boolean read visibleP write visibleP;
    ///Border's color.
    property BorderColor: Color read BorderColorP write BorderColorP;
    ///Border's width.
    property BorderWidth: integer read BorderWidthP write BorderWidthP;
    ///Border's width.
    property BorderStyle: SpriteBorderStyle read BorderStyleP write BorderStyleP;
    ///Filling color.
    property FillColor: Color read FillColorP write FillColorP;
    ///Picture to be drawed instead FillColor.
    property Image: Picture read ImageP write ImageP;
    
    constructor ();begin Visibile := true;BorderStyle := bsRectangle;BorderColor := clBlack;FillColor := clGray; end;
    
    ///Draws game object.
    procedure Draw();
    begin
      try
        if Visibile and (X + W >= 0) and (Y + H >= 0) and (X <= Window.Width) and (Y <= Window.Height) then
        begin
          if Image = nil then
          begin
            SetBrushColor(FillColor);
            case BorderStyle of
              bsRectangle: FillRect(X, Y, X + W, Y + H);
              bsEllipse: FillEllipse(X, Y, X + W, Y + H);
            end;
          end
          else
          begin
            Image.Width := W;
            Image.Height := H;
            Image.Draw(X, Y);
          end;
          SetPenColor(BorderColor);
          SetPenWidth(BorderWidth);
          case BorderStyle of
            bsRectangle: DrawRectangle(X, Y, X + W, Y + H);
            bsEllipse: DrawEllipse(X, Y, X + W, Y + H);
          end;
        end;
        X := X + VelocityX;
        Y := Y + VelocityY;
      except 
        on Exception do end;
    end;
  end;
 
type
  ///List of game objects.
  ObjectsList = class
  private 
    ObjectsP: List<Sprite>;
  
  public 
    constructor ();begin ObjectsP := new List<Sprite>(); end;
    
    ///Adds new object to objects list.
    procedure Add(obj: Sprite) := ObjectsP.Add(obj);
    ///Removes object from objects list.
    function Remove(obj: Sprite) := ObjectsP.Remove(obj);
    ///Represents objects list as array.
    function AsArray(obj: Sprite) := ObjectsP.ToArray();
    ///Count.
    function Count()  := ObjectsP.Count;
    ///Returns game object.
    function GetObject(i: integer) := ObjectsP.Item[i];
  end;
 
//Scene and vizualization.
type
  ///Game scene.
  Scene = class
  private 
    backgroundP: Color;
    ObjectsP: ObjectsList;
  public 
    ///Background color of the scene.
    property Background: Color read backgroundP write backgroundP;
    ///Objects in scene.
    property Objects: ObjectsList read ObjectsP write ObjectsP;
    
    constructor ();begin Objects := new ObjectsList(); end;
    
    procedure Draw();
    begin
      ClearWindow;
      SetBrushColor(Background);
      FillRectangle(0, 0, Window.Width, Window.Height);
      for var i := 0 to Objects.Count - 1 do Objects.GetObject(i).Draw();
      Redraw;
    end;
  end;
  
  ///Game options.
  GameOptions = class
  private 
    class MainTimerP: Timer;
    class ActiveScene: Scene;
  
  public 
    ///Initializes game.
    class procedure GameStart(scn: Scene; str: string);
    begin
      SetWindowCaption(str);
      MainTimerP := new Timer(1, scn.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets active scene.
    class procedure SetActiveScene(scn: Scene);
    begin
      ActiveScene := scn;
      MainTimerP := new Timer(1, ActiveScene.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets interval between frames drawing.
    class procedure SetInterval(i: integer) := MainTimerP.Interval := i;
  end;
 
initialization
  LockDrawing;
end.
, но есть ошибки компиляции (несовместимость типов и так далее). Дорабатывай.
1
Alvin Seville
 Аватар для Соколиный глаз
343 / 273 / 134
Регистрация: 25.07.2014
Сообщений: 4,537
Записей в блоге: 22
15.07.2017, 12:44  [ТС]
Компилируется, но на нажатия клавиш не реагирует:
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
unit GameEngine;
 
uses GraphABC, Timers;
 
type
  SpriteBorderStyle = (bsRectangle, bsEllipse);
 
type
  pr = procedure;
  KeyList = class
  private 
    Keys: List<integer>;
    Procedures: List<pr>;
  public 
    constructor ();begin Keys := new List<integer>();Procedures := new List<pr>(); end;
    
    ///Adds new key to list.
    procedure Add(key: integer; p: pr);
    begin
      Keys.Add(key);Procedures.Add(p);
    end;
    
    ///Removes object from objects list.
    function Remove(key: integer; p: pr): boolean;
    begin
      var a := Keys.Remove(key);
      var b := Procedures.Remove(p);
      Result := a and b;
    end;
    
    ///Count.
    function Count()  := Keys.Count;
    
    ///Run procedure.
    function Run(key: integer) := Procedures[Keys.IndexOf(key)];
  end;
  
  //Physics and vizualization.
  GameObjectOptions = class
  private 
    xP, yP, wP, hP: int64;
    VelocityXP, VelocityYP: int64;
    KeysP: KeyList;
    
    procedure KeyDown(Key: integer);
    begin
      try
        KeysP.Run(Key);
      except 
        on Exception do end;
    end;
  
  public 
      ///X coordinate of high left angle.
    property X: int64 read xP write xP;
    ///Y coordinate of high left angle.
    property Y: int64 read yP write yP;
    ///Width.
    property W: int64 read wP write wP;
    ///Height.
    property H: int64 read hP write hP;
    ///Velocity X.
    property VelocityX: int64 read VelocityXP write VelocityXP;
    ///Velocity Y.
    property VelocityY: int64 read VelocityYP write VelocityYP;
    ///Velocity Y.
    property Keys: KeyList read KeysP write KeysP;
    
    constructor ();begin Keys := new KeyList(); OnKeyDown := KeyDown; end;
  end;
  
  Sprite = class(GameObjectOptions)
  private 
    visibleP: boolean;
    BorderColorP: Color;
    BorderWidthP: integer;
    BorderStyleP: SpriteBorderStyle;
    FillColorP: Color;
    ImageP: Picture;
  
  public 
    ///Visibility.
    property Visibile: boolean read visibleP write visibleP;
    ///Border's color.
    property BorderColor: Color read BorderColorP write BorderColorP;
    ///Border's width.
    property BorderWidth: integer read BorderWidthP write BorderWidthP;
    ///Border's width.
    property BorderStyle: SpriteBorderStyle read BorderStyleP write BorderStyleP;
    ///Filling color.
    property FillColor: Color read FillColorP write FillColorP;
    ///Picture to be drawed instead FillColor.
    property Image: Picture read ImageP write ImageP;
    
    constructor ();begin Visibile := true;BorderStyle := bsRectangle;BorderColor := clBlack;FillColor := clGray; end;
    
    ///Draws game object.
    procedure Draw();
    begin
      try
        if Visibile and (X + W >= 0) and (Y + H >= 0) and (X <= Window.Width) and (Y <= Window.Height) then
        begin
          if Image = nil then
          begin
            SetBrushColor(FillColor);
            case BorderStyle of
              bsRectangle: FillRect(X, Y, X + W, Y + H);
              bsEllipse: FillEllipse(X, Y, X + W, Y + H);
            end;
          end
          else
          begin
            Image.Width := W;
            Image.Height := H;
            Image.Draw(X, Y);
          end;
          SetPenColor(BorderColor);
          SetPenWidth(BorderWidth);
          case BorderStyle of
            bsRectangle: DrawRectangle(X, Y, X + W, Y + H);
            bsEllipse: DrawEllipse(X, Y, X + W, Y + H);
          end;
        end;
        X := X + VelocityX;
        Y := Y + VelocityY;
      except 
        on Exception do end;
    end;
  end;
 
type
  ///List of game objects.
  ObjectsList = class
  private 
    ObjectsP: List<Sprite>;
  
  public 
    constructor ();begin ObjectsP := new List<Sprite>(); end;
    
    ///Adds new object to objects list.
    procedure Add(obj: Sprite) := ObjectsP.Add(obj);
    ///Removes object from objects list.
    function Remove(obj: Sprite) := ObjectsP.Remove(obj);
    ///Represents objects list as array.
    function AsArray(obj: Sprite) := ObjectsP.ToArray();
    ///Count.
    function Count()  := ObjectsP.Count;
    ///Returns game object.
    function GetObject(i: integer) := ObjectsP.Item[i];
  end;
 
//Scene and vizualization.
type
  ///Game scene.
  Scene = class
  private 
    backgroundP: Color;
    ObjectsP: ObjectsList;
  public 
    ///Background color of the scene.
    property Background: Color read backgroundP write backgroundP;
    ///Objects in scene.
    property Objects: ObjectsList read ObjectsP write ObjectsP;
    
    constructor ();begin Objects := new ObjectsList(); end;
    
    procedure Draw();
    begin
      ClearWindow;
      SetBrushColor(Background);
      FillRectangle(0, 0, Window.Width, Window.Height);
      for var i := 0 to Objects.Count - 1 do Objects.GetObject(i).Draw();
      Redraw;
    end;
  end;
  
  ///Game options.
  GameOptions = class
  private 
    class MainTimerP: Timer;
    class ActiveScene: Scene;
  
  public 
    ///Initializes game.
    class procedure GameStart(scn: Scene; str: string);
    begin
      SetWindowCaption(str);
      MainTimerP := new Timer(1, scn.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets active scene.
    class procedure SetActiveScene(scn: Scene);
    begin
      ActiveScene := scn;
      MainTimerP := new Timer(1, ActiveScene.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets interval between frames drawing.
    class procedure SetInterval(i: integer) := MainTimerP.Interval := i;
  end;
 
initialization
  LockDrawing;
end.
0
Супер-модератор
Эксперт Pascal/DelphiАвтор FAQ
 Аватар для volvo
33374 / 21499 / 8235
Регистрация: 22.10.2011
Сообщений: 36,894
Записей в блоге: 11
15.07.2017, 13:59
Лучший ответ Сообщение было отмечено Volobuev Ilya как решение

Решение

Я бы переписал класс KeyList вот так:
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
type
  pr = procedure;
  KeyList = class
  private 
    kp : Dictionary<integer, pr>;
  public 
    constructor ();begin kp := new Dictionary<integer, pr>() end;
    
    ///Adds new key to list.
    procedure Add(key: integer; p: pr);
    begin
      kp.Add(key, p);
    end;
    
    ///Removes object from objects list.
    function Remove(key: integer; p: pr): boolean;
    begin
      // соответственно тоже изменить на работу с Dictionary вместо пары списков
      (*
      var a := Keys.Remove(key);
      var b := Procedures.Remove(p);
      Result := a and b;
      *)
    end;
    
    ///Count.
    function Count()  := kp.Count;
    
    ///Run procedure.
    procedure Run(key: integer);
    begin 
      if kp.Keys.Contains(key) then kp[key]();
    end;
  end;
, теперь прекрасно реагирует на нажатие Enter-а
1
Alvin Seville
 Аватар для Соколиный глаз
343 / 273 / 134
Регистрация: 25.07.2014
Сообщений: 4,537
Записей в блоге: 22
15.07.2017, 15:26  [ТС]
Почему движок лагает при малом количестве объектов?
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
uses GraphABC,GameEngine;
 
var
  n := 400;
 
var
  Scn: Scene;
  Blocks: List<Sprite>;
  y: integer;
 
procedure Stop();
begin
  for var i := 0 to Blocks.Count - 1 do
    Blocks[i].VelocityY := 3;
end;
 
begin
  Scn := new Scene();
  y := -2000;
  Blocks := new List<Sprite>();
  for var i := 0 to n do
  begin
    Blocks.Add(new Sprite());
    var Block := Blocks[Blocks.Count - 1];
    Block.X := Random(Window.Width) div 50 * 50;Block.Y := y;
    Inc(y, 50);
    Block.W := 50;Block.H := 50;
    Block.Image := new Picture(1, 1);
    Block.Image.Load('C:\Ilya\Ground.jpg');
    Block.Keys.Add(GraphABC.VK_Enter, Stop);
    Scn.Objects.Add(Block);
  end;
  
  GameOptions.GameStart(Scn, 'Square');
  SetWindowIsFixedSize(true);
end.
Добавлено через 5 минут
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
uses GraphABC,GameEngine;
 
var
  n := 400;
 
var
  Scn: Scene;
  Blocks: List<Sprite>;
  y: integer;
 
procedure Stop();
begin
  for var i := 0 to Blocks.Count - 1 do
    Blocks[i].VelocityY := 3;
end;
 
begin
  var pic:=new Picture(50,50);
  pic.Load('C:\Ilya\Ground.jpg');
  Scn := new Scene();
  y := -2000;
  Blocks := new List<Sprite>();
  for var i := 0 to n do
  begin
    Blocks.Add(new Sprite());
    var Block := Blocks[Blocks.Count - 1];
    Block.X := Random(Window.Width) div 50 * 50;Block.Y := y;
    Inc(y, 50);
    Block.W := 50;Block.H := 50;
    Block.Image := pic;
    Block.Keys.Add(GraphABC.VK_Enter, Stop);
    Scn.Objects.Add(Block);
  end;
  
  GameOptions.GameStart(Scn, 'Square');
  SetWindowIsFixedSize(true);
end.
Добавлено через 45 минут
Почему блоки разъезжаются?
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
uses GraphABC,GameEngine;
 
const
  n = 100;
  m = 4;
  BlockW = 50;
 
var
  Scn: Scene;
  MaxY: integer;
  num, border: byte;
 
procedure Start();
begin
  for var i := 0 to Scn.Objects.AsArray.Length - 1 do
    Scn.Objects.AsArray[i].VelocityY := 5;
end;
 
begin
  var pic := new Picture(BlockW, BlockW);
  pic.Load('C:\Ilya\Ground.jpg');
  
  MaxY := -BlockW * n+Window.Height;
  
  Scn := new Scene();
  
  for var i := 0 to n do
  begin
    for var j := 0 to m do
    begin
      num := 100-Random(100);
      if num > border  then
      begin
        var obj := new Sprite();
        obj.X := BlockW * j;obj.Y := MaxY + BlockW * i;
        obj.W := BlockW;obj.H := BlockW;
        obj.Image := pic;
        obj.Keys.Add(VK_Enter, Start);
        Scn.Objects.Add(obj);
      end;
      Inc(border, 15);
    end;
    border:=0;
  end;
  
  for var i := 0 to n do
  begin
    for var j := 12 downto 12-m do
    begin
      num := Random(100);
      if num > border  then
      begin
        var obj := new Sprite();
        obj.X := BlockW * j;obj.Y := MaxY + BlockW * i;
        obj.W := BlockW;obj.H := BlockW;
        obj.Image := pic;
        obj.Keys.Add(VK_Enter, Start);
        Scn.Objects.Add(obj);
      end;
      Inc(border, 15);
    end;
    border:=0;
  end;
  
  GameOptions.GameStart(Scn, 'Square');
  SetWindowIsFixedSize(true);
end.
0
Супер-модератор
Эксперт Pascal/DelphiАвтор FAQ
 Аватар для volvo
33374 / 21499 / 8235
Регистрация: 22.10.2011
Сообщений: 36,894
Записей в блоге: 11
15.07.2017, 16:00
Цитата Сообщение от Volobuev Ilya Посмотреть сообщение
Почему блоки разъезжаются?
Этот код вообще не компилируется с предыдущей версией модуля. Скорее всего, опять вносились изменения.
0
Alvin Seville
 Аватар для Соколиный глаз
343 / 273 / 134
Регистрация: 25.07.2014
Сообщений: 4,537
Записей в блоге: 22
15.07.2017, 17:56  [ТС]
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
unit GameEngine;
 
uses GraphABC, Timers;
 
var
  GravityX, GravityY: integer;
 
type
  SpriteBorderStyle = (bsRectangle, bsEllipse);
 
type
  pr = procedure;
  KeyList = class
  private 
    kp : Dictionary<integer, pr>;
  public 
    constructor ();begin kp := new Dictionary<integer, pr>() end;
    
    ///Adds new key to list.
    procedure Add(key: integer; p: pr);
    begin
      kp.Add(key, p);
    end;
    
    ///Removes object from objects list.
    function Remove(key: integer): boolean;
    begin
      Result:=kp.Remove(key);
    end;
    
    ///Count.
    function Count()  := kp.Count;
    
    ///Run procedure.
    procedure Run(key: integer);
    begin 
      if kp.Keys.Contains(key) then kp[key]();
    end;
  end;
  
  //Physics and vizualization.
  GameObjectOptions = class
  private 
    //Main options
    xP, yP, wP, hP: int64;
    VelocityXP, VelocityYP: int64;
    ActorP: boolean;
    KeysP: KeyList;
    
    procedure KeyDown(Key: integer);
    begin
      try
        KeysP.Run(Key);
      except 
        on Exception do end;
    end;
    
    protected procedure ApplyGravity();
    begin
      if Actor then
      begin
        VelocityX := VelocityX + GravityX;
        VelocityY := VelocityY + GravityY;
      end;
    end;
  
  public 
      ///X coordinate of high left angle.
    property X: int64 read xP write xP;
    ///Y coordinate of high left angle.
    property Y: int64 read yP write yP;
    ///Width.
    property W: int64 read wP write wP;
    ///Height.
    property H: int64 read hP write hP;
    ///Velocity X.
    property VelocityX: int64 read VelocityXP write VelocityXP;
    ///Velocity Y.
    property VelocityY: int64 read VelocityYP write VelocityYP;
    ///Velocity Y.
    property Keys: KeyList read KeysP write KeysP;
    ///Is Actor.
    property Actor: boolean read ActorP write ActorP;
    
    constructor ();begin Keys := new KeyList();OnKeyDown := KeyDown; end;
  end;
  
  Sprite = class(GameObjectOptions)
  private 
    visibleP: boolean;
    BorderColorP: Color;
    BorderWidthP: integer;
    BorderStyleP: SpriteBorderStyle;
    FillColorP: Color;
    ImageP: Picture;
  
  public 
    ///Visibility.
    property Visibile: boolean read visibleP write visibleP;
    ///Border's color.
    property BorderColor: Color read BorderColorP write BorderColorP;
    ///Border's width.
    property BorderWidth: integer read BorderWidthP write BorderWidthP;
    ///Border's width.
    property BorderStyle: SpriteBorderStyle read BorderStyleP write BorderStyleP;
    ///Filling color.
    property FillColor: Color read FillColorP write FillColorP;
    ///Picture to be drawed instead FillColor.
    property Image: Picture read ImageP write ImageP;
    
    constructor ();begin Visibile := true;BorderStyle := bsRectangle;BorderColor := clBlack;FillColor := clGray; end;
    
    ///Draws game object.
    procedure Draw();
    begin
      try
        if Visibile and (X + W >= 0) and (Y + H >= 0) and (X <= Window.Width) and (Y <= Window.Height) then
        begin
          if Image = nil then
          begin
            SetBrushColor(FillColor);
            case BorderStyle of
              bsRectangle: FillRect(X, Y, X + W, Y + H);
              bsEllipse: FillEllipse(X, Y, X + W, Y + H);
            end;
          end
          else
          begin
            Image.Width := W;
            Image.Height := H;
            Image.Draw(X, Y);
          end;
          SetPenColor(BorderColor);
          SetPenWidth(BorderWidth);
          case BorderStyle of
            bsRectangle: DrawRectangle(X, Y, X + W, Y + H);
            bsEllipse: DrawEllipse(X, Y, X + W, Y + H);
          end;
        end;
        X := X + VelocityX;
        Y := Y + VelocityY;
        if ActorP then ApplyGravity();
      except 
        on Exception do end;
    end;
  end;
 
type
  ///List of game objects.
  ObjectsList = class
  private 
    ObjectsP: List<Sprite>;
  
  public 
    constructor ();begin ObjectsP := new List<Sprite>(); end;
    
    ///Adds new object to objects list.
    procedure Add(obj: Sprite) := ObjectsP.Add(obj);
    ///Removes object from objects list.
    function Remove(obj: Sprite) := ObjectsP.Remove(obj);
    ///Represents objects list as array.
    function AsArray() := ObjectsP.ToArray();
    ///Count.
    function Count()  := ObjectsP.Count;
    ///Returns game object.
    function GetObject(i: integer) := ObjectsP.Item[i];
  end;
 
//Scene and vizualization.
type
  ///Game scene.
  Scene = class
  private 
    backgroundP: Color;
    ObjectsP: ObjectsList;
    
    function PointInArea(x, y: integer; obj: Sprite) := (x >= obj.X) and (y >= obj.Y) and (x <= obj.X + obj.W) and (y <= obj.Y + obj.H);
  
  public 
    ///Background color of the scene.
    property Background: Color read backgroundP write backgroundP;
    ///Objects in scene.
    property Objects: ObjectsList read ObjectsP write ObjectsP;
    
    constructor ();begin Background := clLightBlue;Objects := new ObjectsList(); end;
    
    function Collides(obj, obj2: Sprite): boolean;
    begin
      var x := obj.X;
      var y := obj.Y;
      var w := obj.W;
      var h := obj.H;
      Result := PointInArea(x, y, obj2) or PointInArea(x + w, y, obj2) or PointInArea(x + w, y + h, obj2) or PointInArea(x, y + h, obj2);
    end;
    
    procedure Draw();
    begin
      ClearWindow;
      SetBrushColor(Background);
      FillRectangle(0, 0, Window.Width, Window.Height);
      for var i := 0 to Objects.Count - 1 do Objects.GetObject(i).Draw();
      Redraw;
    end;
  end;
  
  ///Game options.
  GameOptions = class
  private 
    class MainTimerP: Timer;
    class ActiveScene: Scene;
  
  public 
    ///Initializes game.
    class procedure GameStart(scn: Scene; str: string);
    begin
      SetWindowCaption(str);
      MainTimerP := new Timer(16, scn.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets active scene.
    class procedure SetActiveScene(scn: Scene);
    begin
      ActiveScene := scn;
      MainTimerP := new Timer(16, ActiveScene.Draw);
      MainTimerP.Start();
    end;
    
    ///Sets interval between frames drawing.
    class procedure SetInterval(i: integer) := MainTimerP.Interval := i;
  end;
 
initialization
  LockDrawing;
  SetSmoothingOff;
  GravityY := 1;
end.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
15.07.2017, 17:56
Помогаю со студенческими работами здесь

Ссылка на объект не указывает на экземпляр объекта
здравствуйте всем! Возникла проблема: в коде, данном ниже, возникает ошибка &quot;ссылка на объект не указывает на экземпляр объекта&quot;. как...

Ссылка на объект не указывает на экземпляр объекта
procedure poisk( var L:LIST); var q: position;a1:real;b1:real;i:real; begin read(a1); read(b1); q:=L; repeat begin if...

Ссылка на объект не указывает на экземпляр объекта
Ошибка: tsp2.pas(18) : Ошибка времени выполнения: Ссылка на объект не указывает на экземпляр объекта. Обычно такой вид ошибки связан с...

Ссылка на объект не указывает на экземпляр объекта
Тема может и схожа с теми, что есть, но, в конечном счёте, отличается. Есть проблема, решение которой не могу найти: программа не хочет...

Ошибка времени выполнения: Ссылка на объект не указывает на экземпляр объекта
Здравствуйте. Подскажите пожалуйста как решить эту проблему: Ошибка времени выполнения: Ссылка на объект не указывает на экземпляр объекта....


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru