Форум программистов, компьютерный форум, киберфорум
Basic
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/6: Рейтинг темы: голосов - 6, средняя оценка - 5.00
0 / 0 / 0
Регистрация: 09.06.2011
Сообщений: 64

Найти ошибки в коде игры

07.12.2011, 21:41. Показов 1269. Ответов 7
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
PureBasic
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
;INVADERS!!!
;Developed by Maneesh Sethi on 7/22/02
;A Space invaders clone
 
 
;Set the graphics mode to 640x480
Graphics 640,480 
 
;Set up backbuffer and AutoMidHandle
SetBuffer BackBuffer() 
AutoMidHandle True
 
;Set up random generator
SeedRnd MilliSecs() 
 
;IMAGES
;Player's images
;These images are related to the dreadstrip
Global playerimage = LoadAnimImage("dreadstrip.bmp",35,32,0,13)   ;The dreadstrip's appearance on screen 
Global bulletplayerimage = LoadAnimImage("dreadstripbullet.bmp",40,19,0,10)    ;The player's bullet
Global playerexplosionimage = LoadAnimImage("dreadstripexplosion.bmp",64,64,0,8)
 
;Enemies' image
;These images are related to the enemy
Global enemyimage = LoadAnimImage("enemy.bmp",68,38, 0, 10) ;The enemies' appearance on screen
Global bulletenemyimage = LoadAnimImage("enemybullet.bmp",40,19,0,5) ;The enemies' bullet
Global enemyexplosionimage = LoadAnimImage("enemyexplosion.bmp",64,64,0,8)
 
;Miscellaneous images
Global healthimage = LoadAnimImage("health.bmp",33,21,0,10)    ;the health image
Global backgroundimage = LoadImage("stars.bmp") ;the background image
splashscreenimage = LoadImage("splashscreen.bmp")   ;the splash screen
 
 
 
;SOUNDS/MUSIC
;Sounds
Global explosionsound = LoadSound("explode.wav")
Global bulletsound = LoadSound("zing.wav")
 
;Play background music
backgroundmusic = PlayMusic ("Interim Nation - Human Update.mp3")
 
;CONSTANTS
 
;Keycodes
Const ESCKEY = 1, SPACEBAR = 57, LEFTKEY = 203, RIGHTKEY = 205 
 
;The number of milliseconds between enemy direction changes
Const CHANGEENEMYDIRECTION = 700 
 
;Number of milliseconds between enemy bullet fires
Const TIMEBETWEENENEMYBULLETS = 1200
 
;GLOBALS
;Create global variables that will be used through the program
Global numofenemies  ;the amount of enemies
 
Global directiontime ;counter between enemy direction changes
 
Global shotsfiredtime ;counter between enemy shots 
 
Global enemyhits ;How many times dreadstrip has hit enemy ships
 
Global shotsfired ;How many shots dreadstrip has fired
 
Global playerdamage ;How many times dreadstrip has been hit
 
Global playerscore   ;The dreadstrip's current score
 
Global scrolly   ;the scrolling variable for background
 
Global healthframe  ;the variable that keeps track of the spinning health box
 
 
;TYPES
 
;The ship type: enemies are ships
Type ship           
    Field x,y  ;The x and y coords
    Field hits  ;ship's hitpoints
    Field xv,yv  ;the x and y direction velocities
    Field frame ;the frame of the ship's image
End Type
 
 
 
;The user type: the dreadstrip is a user
Type user
    Field x,y   ;the dreadstrip's coordinates
    Field hits  ;the dreadstrip's hitpoints
    Field frame ;the current frame of the dreadstrip
    Field draw  ;1 if dreadstrip should be drawn, 0 if he shouldn't
End Type
 
;Set up dreadstrip for beginning of game
Global player.user = New user  ;Create a new dreadstrip ship
dreadstrip\x = 640/2 ;Dreadstrip is in the middle of scren
dreadstrip\y = 440   ;Dreadstripis near the bottom
dreadstrip\hits = 3
dreadstrip\draw = 1
 
 
;The bullet type: describes both dreadstrip and enemy bullets
Type bullet           
    Field x,y   ;the bullet's coordinates
    Field draw ;draw is 1 if the bullet should be drawn, 0 if it should be deleted
    Field from  ;if from is 1, bullet is from dreadstrip, if 2, its from enemy
    Field frame   ;the frame of the image. There are 10 frames for dreadstrip's bullet and 5 for enemy's
End Type
 
;The explosion type: describes explosions for players and enemies
Type explosion
    Field x,y    ;the x and y coordinate position
    Field from   ;1 = dreadstrip, 2 = enemy
    Field frame  ;the frame of the image
End Type
 
;Set the level the dreadstrip is on: beginning with level 1
level = 1 
 
;;;;;;;;;;;;;;;;;;;
;MAIN PROGRAM (first function)
;Only initializesdreadstrips and calls other functions (utilizes input as well)
;;;;;;;;;;;;;;;;;;;
;Make the sound of the bullet fire not very loud
;It will be at 25% volume
SoundVolume bulletsound, .25
 
;Display the splash screen for 7 seconds
DrawImage(splashscreenimage, 320,240)
Flip
Delay 7000
 
 
;Make the time of enemy direction changes and enemy bullets equal to the time
directiontime = shotsfiredtime = MilliSecs()
 
;Set up level
InitializeLevel(level)
 
 
;MAIN LOOP
 
While Not KeyDown(ESCKEY) 
 
    ;Draw the background at its position
    TileBlock backgroundImage,0,scrolly
    
    ;Scroll the background a little
    scrolly=scrolly + 1
    
    ;If scrolly is too big, reset it
    If scrolly=ImageHeight(backgroundImage) Then
        scrolly=0
    EndIf
 
    
    ;If there are no enemies left on screen, dreadstrip has beaten level. Thus, begin next level.
    If numofenemies = 0 Then
        
        ;Make the dreadstrip's level increment by one
        level = level + 1
        
        ;Initalize the new level
        InitializeLevel(level)
    EndIf
    
    ;If the space bar is hit
    If KeyHit(SPACEBAR) 
            
            ;Create a new bullet at the dreadstrip's position ('1' signifies that the bullet is from the dreadstrip, and not an enemy)
            CreateBullet(dreadstrip\x,dreadstrip\y , 1) 
        
 
            ;Increment the variable that holds how many bullets have been fired
            shotsfired = shotsfired + 1
            ;play bullet sound
            PlaySound(bulletsound)
        EndIf
        
 
    ;If left key is pressed, move dreadstrip 10 pixels left
    If KeyDown(LEFTKEY)
        
        dreadstrip\x =dreadstripx - 10
        
        
        ;If player moves offscreen, keep him onscreen
        If dreadstrip\x <= 0
            dreadstrip\x = 10
        EndIf
 
        ;tilt pdreadstrip left
        dreadstrip\frame = dreadstrip\frame - 1
        
        ;dont let frame get too low
        If dreadstripframe <= 0
            dreadstrip\frame = 0
        EndIf
    EndIf
    
    ;If right key is pressed, move dreadstrip right 10 pixel
    If KeyDown(RIGHTKEY)
        dreadstrip\x = dreadstrip\x + 10
    
        ;if dreadstripmoves off screen, keep him on screen
        If dreadstrip\x >= 610
            dreadstrip\x = 610
        EndIf
        
        
        ;tilt dreadstrip right
        dreadstrip\frame = dreadstrip\frame + 1
        
        ;dont let frame get too high
        If dreadstrip\frame >= 12
            dreadstrip\frame = 12
        EndIf
    EndIf
    
    ;Begin resetting the player's frame
    If (Not KeyDown(RIGHTKEY)) And (Not KeyDown(LEFTKEY))
        If dreadstrip\frame < 7
            dreadstrip\frame = dreadstrip\frame + 1
        ElseIf dreadstrip\frame > 7
            dreadstrip\frame = dreadstrip\frame - 1
        EndIf
    EndIf 
    ;Call the necessary user-defined functions
    ;Draw the information the dreadstrip needs to see
    DrawHUD()
    ;Draw all of the ships, dreadstrip and enemies
    DrawShips()
    ;Update enemy's movement and bullet fire
    EnemyAI()
    ;Move all of the bullets, and delete uncessary one
    UpdateBullets() 
    ;update all existing explosions
    UpdateExplosions()
 
    Flip
    
    ;hold on for a fraction of a second
    Delay 25
Wend ;End of While Loop
 
GameOver()
;;;;;;;;;;;;;;;;;;;
;END OF MAIN PROGRAM
;
;;;;;;;;;;;;;;;;;;;
 
 
;;;;;;;;;;;;;;;;;;;
;CreateBullet(x,y)
;This function takes the x and y coords of the bullet and creates it
;;;;;;;;;;;;;;;;;;;
Function CreateBullet(x,y, from)
 
 
    ;Create a new bullet
    bullets.bullet = New bullet 
    
    ;set the x and y coordinates to the position of the ship that fired it
    bullets\x = x
    bullets\y = y  
    
    ;Make sure the bullet should be drawable
    bullets\draw = 1 
    
    ;Tell where the bullet originated from: a dreadstrip or an enemy
    bullets\from = from 
 
 
 
End Function ;End CreateBullet
 
 
;;;;;;;;;;;;;;;;;;;
;UpdateBullets()
;Updates each bullet and deletes them if they are no longer on the screen
;;;;;;;;;;;;;;;;;;;
 
Function UpdateBullets()
 
 
;Check every bullet. Depending on who fired it, move it in the corect direction. Then, draw the bullet. 
;Finally, check and see if the bullets have hit any other ships
For i.bullet = Each bullet ;Check every bullet
    
    ;If shot by dreadstrip, move bullet up
    If i\from = 1 
        i\y = i\y - 10 
    
    ;If shot by dreadstrip, move bullet down
    Else 
        i\y = i\y + 10 ;move bullet down 
    EndIf
            
    ;if bullet should be drawn (its on screen), draw it with the proper color
    If i\draw = 1 
        
        ;If its from dreadstrip, draw dreadstrip bullet
        If i\from = 1
            DrawImage (bulletDreadstripImage, i\x, i\y, i\frame) 
        
        ;If its from enemy, draw enemy bullet
        Else
            DrawImage (bulletEnemyImage, i\x, i\y, i\frame) 
        EndIf
    EndIf
    
    
    
    
    ;We now test to see if the bullets have hit any ships
    
    ;Test the dreadstrip bullets if it hit an enemy
    If i\from = 1 
    
    ;For each enemy, if bullet has collided, subtract a hitpoint
    For e.ship = Each ship ;check each enemy
        
        ;If the bullet has hit the enemy, remove one hitpoint
        If ImagesCollide(bulletdreadstripimage, i\x,i\y,0, enemyimage, e\x, e\y, 0) 
            
            ;Subtract a hitpoin
            e\hits = e\hits - 1 
        
        
            ;increment the number of times an enemy has been hit by dreadstrip
            enemyhits = enemyhits + 1
            
            ;if the ship is out of hitpoints, remove the enemy
            If e\hits <= 0
            
                numofenemies = numofenemies - 1
                ;create an explosion with enemy's coordinates. "2" signifies it is from enemy. not dreadstrip.
                CreateExplosion(e\x,e\y,2)
            
                ;destroy the enemy ship
                Delete e 
                ;play explosion sound
                PlaySound(explosionsound)
                
 
            EndIf 
        
        ;Make sure the bullet is not drawn (it will be deleted next frame)
        i\draw = 0
        EndIf 
        
        
    Next   ;check next enemy ship
    
    EndIf 
    
    ;check if the bullet is shot by enemy, check if it hit dreadstrip
    ;don't check if the dreadstrip has already exploded
    If i\from = 2 And dreadstripexplosion = 0
        ;if the bullet hit the dreadstrip, decrease hitpoints and add damage
        If ImagesCollide(bulletenemyimage,i\x, i\y, 0, dreadstripimage, dreadstrip\x, dreadstrip\y, 0)
            
            ;decrease a hitpoint
            dreadstrip\hits = dreadstrip\hits - 1
        
 
            ;If dreadstrip is out of hitpoints, call gameover()
            If dreadstrip \hits <= 0 
                ;dreadstrip explosion sound
                PlaySound(explosionsound)
                CreateExplosion(dreadstrip\x,dreadstrip\y,1)
                ;don't draw dreadstrip anymore
                player\draw = 0
            EndIf
        ;Make sure the bullet is not drawn anymore
        i\draw = 0
        
        EndIf 
        
    EndIf
    
        
        ;If from dreadstrip, draw dreadstrip explosion
    If player\hits <= 0
    
        For ex.explosion = Each explosion
            If ex\from = 1 And ex\frame >= 7
    
                GameOver()
    
            EndIf
        Next    
    EndIf
 
 
    ;increment frame
    i\frame = i\frame + 1
    ;if from dreadstrip, there are 10 frames: dont let frame get too large
    If i\from = 1 And i\frame >= 10
        i\frame = 0
    ;if from enemy there are 5 franes: don't let frame get too large
    ElseIf i\from = 2 And i\frame >=5
        i\frame = 0
    EndIf
        
    ;If the bullet is offscreen or if it hit a ship, delete it  
    If i\y < 0 Or i\draw = 0
        Delete i 
    EndIf 
 
    
 
Next ;Go to the next bullet
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;InitializeLevel(level)
;Sets up parameters for the current level
;;;;;;;;;;;;;;;;;;;
 
Function InitializeLevel(level)
 
 
;Delete each and every bullet
For i.bullet = Each bullet
    Delete i
Next
 
 
;Display intro text
Text 230,240,"NOW ENTERING Level " + level
Flip
 
;Delay for a few seconds
Delay 2000
 
 
;Reset dreadstrip's hitcounter
player\hits = 3
 
;reset dreadstrip's frame
player\frame = 7   ;(7 is the middle frame)
 
;Make the total number of enemies a value between 3 and 5 + the current level
numofenemies = level + Rand(3 , 5)    ;Level 1 will have 4-6 enemies, 2 will have 5-7, etc.
 
;reset health boxes' frame
healthframe = 0
 
 
;create the required number of enemies
For e=1 To numofenemies
 
    CreateNewEnemy(level) 
Next
    
    
End Function 
;;;;;;;;;;;;;;;;;;;
;CreateNewEnemy(level)
;Create a new enemy
;;;;;;;;;;;;;;;;;;;
 
Function CreateNewEnemy(level)
 
;Create a new enemy ship
enemy.ship = New ship
 
;release point determines if enemy will be released from top, left, or bottom of screen
releasepoint = Rand(1,4) 
 
;25% of enemies will be unleashed from left\right, 50% from top
Select releasepoint
 
    Case 1   ;enemy released from left side
        
        ;set up enemy's coordinates
        enemy\x = 5
        enemy\y = Rand(0 , 420)   ;Enemy is released on a random point on the left side
        
        ;set up random velocities
        enemy\xv = Rand(1 , 2)
        enemy\yv = Rand(-2,2)
        
    Case 2   ;enemy released from top
        ;set up enemy's coorinates
        enemy\x = Rand(0,640)    ;Enemy is released on a random point on the top
        enemy\y = 5
        
        ;set up random velocities
        enemy\xv = Rand(-2, 2)
        enemy\yv = Rand(1,2)
        
    Case 3 ;enemy released from top
        ;set up enemy coordinates
        enemy\x = Rand(0,640)   ;Enemy is released on a random point on the top
        enemy\y = 5
        
        ;Set up random velocities
        enemy\xv = Rand(-2, 2)
        enemy\yv = Rand(1,2)
        
        
    Case 4 ;enemy released from right side
        ;set up enemy coordinates
        enemy\x = 620
        enemy\y = Rand(0 , 420) ;Enemy is released on a random point on the right side
        
        ;set up random velocities
        enemy\xv = Rand(-2, -1)
        enemy\yv = Rand(-2,2)
        
        
    Default ;if there is a major error
        Print "ERROR, Enemy unleashed in a nonexistant place!"
End Select
 
enemy\hits = level
End Function
        
 
 
;;;;;;;;;;;;;;;;;;;
;DrawShips()
;Draw Players and enemies
;;;;;;;;;;;;;;;;;;;
Function DrawShips()
 
;Draw each ship, enemy and dreadstrip
;For each enemy
For i.ship = Each ship   
    DrawImage(enemyImage, i\x, i\y, i\frame)
Next
;For each player
For j.user = Each user 
    ;if user should be drawn
    If j\draw = 1
        DrawImage(dreadstripImage, j\x, j\y, j\frame)
    EndIf
Next
 
End Function 
 
 
;;;;;;;;;;;;;;;;;;;
;EnemyAI()
;Update the enemies' stats and determine their movements
;;;;;;;;;;;;;;;;;;;
Function EnemyAI()
 
 
;Check every enemy ship. Determine if they should change their velocities, make sure they dont hit any walls, and fire their bullets
For i.ship = Each ship 
 
    ;if the directiontime timer has gone through, change the velocity of the ship
        If directiontime <= MilliSecs() - CHANGEENEMYDIRECTION 
        i\xv = i\xv+Rand(-2,2)   ;nudge the x velocity
        i\yv = i\yv+Rand(-2,2)   ;nude the y velocity
        
        ;Reset the direction reset timer after the later
        resetdirectiontime = 1 
    EndIf
    
    ;If x velocity is too large, lower it
    If ixv > 5 Then
       i\xv = i\xv - 2
    EndIf
    
    ;If y velocity is too large, lower it
    If i\yv > 5 Then
        i\yv = i\yv - 2
    EndIf
    
    ;If x velocity is too low, raise it
    If ixv < -5 Then
       i\xv = i\xv + 2
    EndIf
    
    ;If y velocity is too low, lower it
    If i\yv < -5 Then
        i\yv = i\yv +2
    EndIf
 
    ;Update ship's velocities
    i\x = i\x + i\xv 
    i\y = i\y + i\yv
    
    ;Check walls with the ship
    
    ;If ship hits left wall, reverse its velocity
    If i\x <= 0 
        i\x = 5    ;keep it on screen
        i\xv = -i\xv    ;fix velocity
        
    ;If ship hits right wall, reverse its velocity
    Else If i\x >=620
        i\x = 615    ;keep it on screen
        i\xv = -i\xv   ;fix its velocity
    
    ;If ship hits upper wall, reverse its velocity
    Else If i\y <= 0  
        i\y = 5    ;keep it on screen
        i\yv = -i\yv  ;fix its velocity
    
    ;If ship hits lower wall, reverse its velocity
    Else If i\y >= 410 
        i\y = 405   ;keep it on screen
        i\yv = -i\yv  ;fix its velocity
    End If
    
    ;If it is time for the enemy to fire another bullet, fire the bullet
    If MilliSecs() >= shotsfiredtime + TIMEBETWEENENEMYBULLETS
        
        ;Create the new bullet
        CreateBullet(i\x,i\y,2)
 
        ;reset the bullet fire timer
        resetshotstime = 1
    EndIf
    
    ;Update ship's frame
    i\frame = i\frame + 1
 
    ;make sure frame isnt too large
    If i\frame >= 9
        i\frame = 0
    EndIf
 
 
Next ;next ship
 
;If the directiontime counter should be reset, reset it
If resetdirectiontime Then 
    directiontime = MilliSecs() 
    resetdirectiontime = 0
EndIf
 
;If the shotstime counter should be reset, reset it
If resetshotstime Then
    shotsfiredtime = MilliSecs()
    resetshotstime = 0
EndIf
 
 
End Function
 
 
;;;;;;;;;;;;;;;;;;;
;DrawHUD()
;Draws the HUD - the displays, health, etc.
;;;;;;;;;;;;;;;;;;;
 
Function DrawHUD()
 
;increment health's frame
healthframe = healthframe + 1
 
;don't let health frame get too large
If healthframe >=10
    healthframe = 0
EndIf
 
;Draw as many hitpoints on the HUD as hitpoints the player has remaining
For i=1 To player\hits
 
    ;Draw healthimage in topleft
    DrawImage healthimage,i*50 - 35,10,healthframe
 
Next
 
;Display topright info
Text 510, 10, "Enemy Hits:  " + enemyhits 
Text 510, 30, "Shots Fired: " + shotsfired
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;CreateExplosions
;Creates an explosion. First parameter is x coordinate, second is y coord, and thrid is 1 if  the explosion is from a dreadstrip, and 2 if from an enemy
;;;;;;;;;;;;;;;;;;;
 
Function CreateExplosion(x,y,from)
 
ex.explosion = New explosion
ex\x = x
ex\y = y
ex\from = from
ex\frame = 0
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;UpdateExposions()
;Updates all of the enemy explosions
;;;;;;;;;;;;;;;;;;;
 
Function UpdateExplosions()
 
 
For ex.explosion = Each explosion
;If explosion is from enemy, draw it and update it
 
 
    DrawImage enemyexplosionimage,ex\x,ex\y,ex\frame
 
 
    ;Update explosion
    ex\frame = ex\frame + 1
 
    ;if the enemy has exploded, delete the explosion
    ;Don't delete dreadstrip explosions, we need it to detect when the player has dies
    If ex\from = 2
    If ex\frame>=7  
        Delete ex
    EndIf
    EndIf
Next
End Function
 
 
 
 
 
 
;;;;;;;;;;;;;;;;;;;
;GameOver()
;Deletes every object, quits game
;;;;;;;;;;;;;;;;;;;
 
Function GameOver()
 
 
 
 
Text 320,270, "Press Any Key To Quit.",True,True
Flip
 
;Delay for 2 seconds
Delay 2000
 
;Clear the key buffer
FlushKeys
 
;Wait for user to press something
WaitKey()
 
;Delete all the bullets
For i.bullet = Each bullet 
    Delete i
Next
 
;Delete all the enemy ships
For e.ship = Each ship 
    Delete e
Next
 
;Delete the dreadstrip
For u.user = Each user ;Delete dreadstrip
    Delete u
Next
 
;End the game
End Function
End
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
07.12.2011, 21:41
Ответы с готовыми решениями:

Проблемы с реализацией игры "Морской бой": найти и исправить ошибки в коде
Доброго времени суток. У меня вопрос по игре &quot;Морской бой&quot;. Я вывел поле с написанными координатами сверху и слева. Затем предлагаю...

Ошибки в коде игры
//сср файл #include &quot;widget.h&quot; #include &quot;ui_widget.h&quot; #include&lt;QTime&gt; Widget::Widget(QWidget *parent) : ...

Найти ошибки в коде и исправить эти ошибки (Наследование)
Вот в общем 3 файла, изучаю наследование на примере односвязного и двусвязного списков: list.h (inline) #pragma once class list...

7
Кормпилятор
 Аватар для Quiet Snow
5044 / 1718 / 409
Регистрация: 25.04.2010
Сообщений: 4,827
Записей в блоге: 2
08.12.2011, 02:59
КАКАЯ ОШИБКА?
Обычно так не спрашивают на форуме, дают маленький кусочек кода. Говорят, что он должен
делать и где по вашему мнению возможное место ошибки. Люди не станут читать и пытаться
разобраться в неформатированном, по-буржуйски комментированном и скорее всего на 90%
не вашем коде.
На форуме код без тегов не выкладывают, т.к. как вы видите в нём появились смайлики
заместо комментария.
Чтобы повысить шансы на помощь вам:
  • Произведите форматирование кода(отступы, русские комментарии)
  • Выделите оттуда часть кода, где по вашему мнению ошибка, опишите ошибку как можно подробнее,
    напишите о ваших попытках решить проблему.
  • Выложите сюда и оберните в тег, как делают все нормальные люди(и кусок и полный вариант,
    при этом полный вариант во вложение)
Вот тогда будет разговор.
1
Почетный модератор
Эксперт по компьютерным сетямЭксперт Windows
 Аватар для magirus
28049 / 15785 / 983
Регистрация: 15.09.2009
Сообщений: 67,752
Записей в блоге: 78
09.12.2011, 12:52
Цитата Сообщение от vikusya1298 Посмотреть сообщение
Что у меня не получается?
а фиг его знает
Цитата Сообщение от >Quiet Snow< Посмотреть сообщение
я пишу игру на Blitz Basic3d?
Вам виднее...
Цитата Сообщение от >Quiet Snow< Посмотреть сообщение
КАКАЯ ОШИБКА?
три вопроса в названии темы.... мда...
1
0 / 0 / 0
Регистрация: 09.06.2011
Сообщений: 64
11.12.2011, 21:00  [ТС]
PureBasic
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
;INVADERS!!!
;Developed by Maneesh Sethi on 7/22/02
;A Space invaders clone
 
 
;Set the graphics mode to 640x480
Graphics 640,480 
 
;Set up backbuffer and AutoMidHandle
SetBuffer BackBuffer() 
AutoMidHandle True
 
;Set up random generator
SeedRnd MilliSecs() 
 
;IMAGES
;Player's images
;These images are related to the player
Global playerimage = LoadAnimImage("player.bmp",35,32,0,13)   ;The player's appearance on screen
Global bulletplayerimage = LoadAnimImage("playerbullet.bmp",40,19,0,10)    ;The player's bullet
Global playerexplosionimage = LoadAnimImage("playerexplosion.bmp",64,64,0,8)
 
;Enemies' image
;These images are related to the enemy
Global enemyimage = LoadAnimImage("enemy.bmp",68,38, 0, 10) ;The enemies' appearance on screen
Global bulletenemyimage = LoadAnimImage("enemybullet.bmp",40,19,0,5) ;The enemies' bullet
Global enemyexplosionimage = LoadAnimImage("enemyexplosion.bmp",64,64,0,8)
 
;Miscellaneous images
Global healthimage = LoadAnimImage("health.bmp",33,21,0,10)    ;the health image
Global backgroundimage = LoadImage("stars.bmp") ;the background image
splashscreenimage = LoadImage("splashscreen.bmp")   ;the splash screen
 
 
 
;SOUNDS/MUSIC
;Sounds
Global explosionsound = LoadSound("explode.wav")
Global bulletsound = LoadSound("zing.wav")
 
;Play background music
backgroundmusic = PlayMusic ("Interim Nation - Human Update.mp3")
 
;CONSTANTS
 
;Keycodes
Const ESCKEY = 1, SPACEBAR = 57, LEFTKEY = 203, RIGHTKEY = 205 
 
;The number of milliseconds between enemy direction changes
Const CHANGEENEMYDIRECTION = 700 
 
;Number of milliseconds between enemy bullet fires
Const TIMEBETWEENENEMYBULLETS = 1200
 
;GLOBALS
;Create global variables that will be used through the program
Global numofenemies  ;the amount of enemies
 
Global directiontime ;counter between enemy direction changes
 
Global shotsfiredtime ;counter between enemy shots 
 
Global enemyhits ;How many times player has hit enemy ships
 
Global shotsfired ;How many shots player has fired
 
Global playerdamage ;How many times player has been hit
 
Global playerscore   ;The player's current score
 
Global scrolly   ;the scrolling variable for background
 
Global healthframe  ;the variable that keeps track of the spinning health box
 
 
;TYPES
 
;The ship type: enemies are ships
Type ship           
    Field x,y  ;The x and y coords
    Field hits  ;ship's hitpoints
    Field xv,yv  ;the x and y direction velocities
    Field frame ;the frame of the ship's image
End Type
 
 
 
;The user type: the player is a user
Type user
    Field x,y   ;the player's coordinates
    Field hits  ;the player's hitpoints
    Field frame ;the current frame of the player
    Field draw  ;1 if player should be drawn, 0 if he shouldn't
End Type
 
;Set up player for beginning of game
Global player.user = New user  ;Create a new player ship
player\x = 640/2 ;Player is in the middle of scren
player\y = 440  ;Player is near the bottom
player\hits = 3
player\draw = 1
 
 
;The bullet type: describes both player and enemy bullets
Type bullet           
    Field x,y   ;the bullet's coordinates
    Field draw ;draw is 1 if the bullet should be drawn, 0 if it should be deleted
    Field from  ;if from is 1, bullet is from player, if 2, its from enemy
    Field frame   ;the frame of the image. There are 10 frames for player's bullet and 5 for enemy's
End Type
 
;The explosion type: describes explosions for players and enemies
Type explosion
    Field x,y    ;the x and y coordinate position
    Field from   ;1 = player, 2 = enemy
    Field frame  ;the frame of the image
End Type
 
;Set the level the player is on: beginning with level 1
level = 1 
 
;;;;;;;;;;;;;;;;;;;
;MAIN PROGRAM (first function)
;Only initializes players and calls other functions (utilizes input as well)
;;;;;;;;;;;;;;;;;;;
;Make the sound of the bullet fire not very loud
;It will be at 25% volume
SoundVolume bulletsound, .25
 
;Display the splash screen for 7 seconds
DrawImage(splashscreenimage, 320,240)
Flip
Delay 7000
 
 
;Make the time of enemy direction changes and enemy bullets equal to the time
directiontime = shotsfiredtime = MilliSecs()
 
;Set up level
InitializeLevel(level)
 
 
;MAIN LOOP
 
While Not KeyDown(ESCKEY) 
 
    ;Draw the background at its position
    TileBlock backgroundImage,0,scrolly
    
    ;Scroll the background a little
    scrolly=scrolly + 1
    
    ;If scrolly is too big, reset it
    If scrolly=ImageHeight(backgroundImage) Then
        scrolly=0
    EndIf
 
    
    ;If there are no enemies left on screen, player has beaten level. Thus, begin next level.
    If numofenemies = 0 Then
        
        ;Make the player's level increment by one
        level = level + 1
        
        ;Initalize the new level
        InitializeLevel(level)
    EndIf
    
    ;If the space bar is hit
    If KeyHit(SPACEBAR) 
            
            ;Create a new bullet at the player's position ('1' signifies that the bullet is from the player, and not an enemy)
            CreateBullet(player\x,player\y , 1) 
        
            ;Increment the variable that holds how many bullets have been fired
            shotsfired = shotsfired + 1
            ;play bullet sound
            PlaySound(bulletsound)
        EndIf
        
 
    ;If left key is pressed, move player 10 pixels left
    If KeyDown(LEFTKEY)
        
        player\x = player\x - 10
        
        
        ;If player moves offscreen, keep him onscreen
        If player\x <= 0
            player\x = 10
        EndIf
 
        ;tilt player left
        player\frame = player\frame - 1
        
        ;dont let frame get too low
        If player\frame <= 0
            player\frame = 0
        EndIf
    EndIf
    
    ;If right key is pressed, move player right 10 pixel
    If KeyDown(RIGHTKEY)
        player\x = player\x + 10
    
        ;if player moves off screen, keep him on screen
        If player\x >= 610
            player\x = 610
        EndIf
        
        
        ;tilt player right
        player\frame = player\frame + 1
        
        ;dont let frame get too high
        If player\frame >= 12
            player\frame = 12
        EndIf
    EndIf
    
    ;Begin resetting the player's frame
    If (Not KeyDown(RIGHTKEY)) And (Not KeyDown(LEFTKEY))
        If player\frame < 7
            player\frame = player\frame + 1
        ElseIf player\frame > 7
            player\frame = player\frame - 1
        EndIf
    EndIf 
    ;Call the necessary user-defined functions
    ;Draw the information the player needs to see
    DrawHUD()
    ;Draw all of the ships, player and enemies
    DrawShips()
    ;Update enemy's movement and bullet fire
    EnemyAI()
    ;Move all of the bullets, and delete uncessary one
    UpdateBullets() 
    ;update all existing explosions
    UpdateExplosions()
 
    Flip
    
    ;hold on for a fraction of a second
    Delay 25
Wend ;End of While Loop
 
GameOver()
;;;;;;;;;;;;;;;;;;;
;END OF MAIN PROGRAM
;
;;;;;;;;;;;;;;;;;;;
 
 
;;;;;;;;;;;;;;;;;;;
;CreateBullet(x,y)
;This function takes the x and y coords of the bullet and creates it
;;;;;;;;;;;;;;;;;;;
Function CreateBullet(x,y, from)
 
 
    ;Create a new bullet
    bullets.bullet = New bullet 
    
    ;set the x and y coordinates to the position of the ship that fired it
    bullets\x = x
    bullets\y = y  
    
    ;Make sure the bullet should be drawable
    bullets\draw = 1 
    
    ;Tell where the bullet originated from: a player or an enemy
    bullets\from = from 
 
 
 
End Function ;End CreateBullet
 
 
;;;;;;;;;;;;;;;;;;;
;UpdateBullets()
;Updates each bullet and deletes them if they are no longer on the screen
;;;;;;;;;;;;;;;;;;;
 
Function UpdateBullets()
 
 
;Check every bullet. Depending on who fired it, move it in the corect direction. Then, draw the bullet. 
;Finally, check and see if the bullets have hit any other ships
For i.bullet = Each bullet ;Check every bullet
    
    ;If shot by player, move bullet up
    If i\from = 1 
        i\y = i\y - 10 
    
    ;If shot by player, move bullet down
    Else 
        i\y = i\y + 10 ;move bullet down 
    EndIf
            
    ;if bullet should be drawn (its on screen), draw it with the proper color
    If i\draw = 1 
        
        ;If its from player, draw player bullet
        If i\from = 1
            DrawImage (bulletPlayerImage, i\x, i\y, i\frame) 
        
        ;If its from enemy, draw enemy bullet
        Else
            DrawImage (bulletEnemyImage, i\x, i\y, i\frame) 
        EndIf
    EndIf
    
    
    
    
    ;We now test to see if the bullets have hit any ships
    
    ;Test the players bullets if it hit an enemy
    If i\from = 1 
    
    ;For each enemy, if bullet has collided, subtract a hitpoint
    For e.ship = Each ship ;check each enemy
        
        ;If the bullet has hit the enemy, remove one hitpoint
        If ImagesCollide(bulletplayerimage, i\x,i\y,0, enemyimage, e\x, e\y, 0) 
            
            ;Subtract a hitpoin
            e\hits = e\hits - 1 
        
        
            ;increment the number of times an enemy has been hit by player
            enemyhits = enemyhits + 1
            
            ;if the ship is out of hitpoints, remove the enemy
            If e\hits <= 0
            
                numofenemies = numofenemies - 1
                ;create an explosion with enemy's coordinates. "2" signifies it is from enemy. not player.
                CreateExplosion(e\x,e\y,2)
            
                ;destroy the enemy ship
                Delete e 
                ;play explosion sound
                PlaySound(explosionsound)
                
 
            EndIf 
        
        ;Make sure the bullet is not drawn (it will be deleted next frame)
        i\draw = 0
        EndIf 
        
        
    Next   ;check next enemy ship
    
    EndIf 
    
    ;check if the bullet is shot by enemy, check if it hit player
    ;don't check if the player has already exploded
    If i\from = 2 And playerexplosion = 0
        ;if the bullet hit the player, decrease hitpoints and add damage
        If ImagesCollide(bulletenemyimage,i\x, i\y, 0, playerimage, player\x, player\y, 0)
            
            ;decrease a hitpoint
            player\hits = player\hits - 1
        
 
            ;If player is out of hitpoints, call gameover()
            If player\hits <= 0 
                ;play explosion sound
                PlaySound(explosionsound)
                CreateExplosion(player\x,player\y,1)
                ;don't draw player anymore
                player\draw = 0
            EndIf
        ;Make sure the bullet is not drawn anymore
        i\draw = 0
        
        EndIf 
        
    EndIf
    
        
        ;If from player, draw player explosion
    If player\hits <= 0
    
        For ex.explosion = Each explosion
            If ex\from = 1 And ex\frame >= 7
    
                GameOver()
    
            EndIf
        Next    
    EndIf
 
 
    ;increment frame
    i\frame = i\frame + 1
    ;if from player, there are 10 frames: dont let frame get too large
    If i\from = 1 And i\frame >= 10
        i\frame = 0
    ;if from enemy there are 5 franes: don't let frame get too large
    ElseIf i\from = 2 And i\frame >=5
        i\frame = 0
    EndIf
        
    ;If the bullet is offscreen or if it hit a ship, delete it  
    If i\y < 0 Or i\draw = 0
        Delete i 
    EndIf 
 
    
 
Next ;Go to the next bullet
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;InitializeLevel(level)
;Sets up parameters for the current level
;;;;;;;;;;;;;;;;;;;
 
Function InitializeLevel(level)
 
 
;Delete each and every bullet
For i.bullet = Each bullet
    Delete i
Next
 
 
;Display intro text
Text 230,240,"NOW ENTERING Level " + level
Flip
 
;Delay for a few seconds
Delay 2000
 
 
;Reset player's hitcounter
player\hits = 3
 
;reset player's frame
player\frame = 7   ;(7 is the middle frame)
 
;Make the total number of enemies a value between 3 and 5 + the current level
numofenemies = level + Rand(3 , 5)    ;Level 1 will have 4-6 enemies, 2 will have 5-7, etc.
 
;reset health boxes' frame
healthframe = 0
 
 
;create the required number of enemies
For e=1 To numofenemies
 
    CreateNewEnemy(level) 
Next
    
    
End Function 
;;;;;;;;;;;;;;;;;;;
;CreateNewEnemy(level)
;Create a new enemy
;;;;;;;;;;;;;;;;;;;
 
Function CreateNewEnemy(level)
 
;Create a new enemy ship
enemy.ship = New ship
 
;release point determines if enemy will be released from top, left, or bottom of screen
releasepoint = Rand(1,4) 
 
;25% of enemies will be unleashed from left\right, 50% from top
Select releasepoint
 
    Case 1   ;enemy released from left side
        
        ;set up enemy's coordinates
        enemy\x = 5
        enemy\y = Rand(0 , 420)   ;Enemy is released on a random point on the left side
        
        ;set up random velocities
        enemy\xv = Rand(1 , 2)
        enemy\yv = Rand(-2,2)
        
    Case 2   ;enemy released from top
        ;set up enemy's coorinates
        enemy\x = Rand(0,640)    ;Enemy is released on a random point on the top
        enemy\y = 5
        
        ;set up random velocities
        enemy\xv = Rand(-2, 2)
        enemy\yv = Rand(1,2)
        
    Case 3 ;enemy released from top
        ;set up enemy coordinates
        enemy\x = Rand(0,640)   ;Enemy is released on a random point on the top
        enemy\y = 5
        
        ;Set up random velocities
        enemy\xv = Rand(-2, 2)
        enemy\yv = Rand(1,2)
        
        
    Case 4 ;enemy released from right side
        ;set up enemy coordinates
        enemy\x = 620
        enemy\y = Rand(0 , 420) ;Enemy is released on a random point on the right side
        
        ;set up random velocities
        enemy\xv = Rand(-2, -1)
        enemy\yv = Rand(-2,2)
        
        
    Default ;if there is a major error
        Print "ERROR, Enemy unleashed in a nonexistant place!"
End Select
 
enemy\hits = level
End Function
        
 
 
;;;;;;;;;;;;;;;;;;;
;DrawShips()
;Draw Players and enemies
;;;;;;;;;;;;;;;;;;;
Function DrawShips()
 
;Draw each ship, enemy and player
;For each enemy
For i.ship = Each ship   
    DrawImage(enemyImage, i\x, i\y, i\frame)
Next
;For each player
For j.user = Each user 
    ;if user should be drawn
    If j\draw = 1
        DrawImage(playerImage, j\x, j\y, j\frame)
    EndIf
Next
 
End Function 
 
 
;;;;;;;;;;;;;;;;;;;
;EnemyAI()
;Update the enemies' stats and determine their movements
;;;;;;;;;;;;;;;;;;;
Function EnemyAI()
 
 
;Check every enemy ship. Determine if they should change their velocities, make sure they dont hit any walls, and fire their bullets
For i.ship = Each ship 
 
    ;if the directiontime timer has gone through, change the velocity of the ship
        If directiontime <= MilliSecs() - CHANGEENEMYDIRECTION 
        i\xv = i\xv+Rand(-2,2)   ;nudge the x velocity
        i\yv = i\yv+Rand(-2,2)   ;nude the y velocity
        
        ;Reset the direction reset timer after the later
        resetdirectiontime = 1 
    EndIf
    
    ;If x velocity is too large, lower it
    If ixv > 5 Then
       i\xv = i\xv - 2
    EndIf
    
    ;If y velocity is too large, lower it
    If i\yv > 5 Then
        i\yv = i\yv - 2
    EndIf
    
    ;If x velocity is too low, raise it
    If ixv < -5 Then
       i\xv = i\xv + 2
    EndIf
    
    ;If y velocity is too low, lower it
    If i\yv < -5 Then
        i\yv = i\yv +2
    EndIf
 
    ;Update ship's velocities
    i\x = i\x + i\xv 
    i\y = i\y + i\yv
    
    ;Check walls with the ship
    
    ;If ship hits left wall, reverse its velocity
    If i\x <= 0 
        i\x = 5    ;keep it on screen
        i\xv = -i\xv    ;fix velocity
        
    ;If ship hits right wall, reverse its velocity
    Else If i\x >=620
        i\x = 615    ;keep it on screen
        i\xv = -i\xv   ;fix its velocity
    
    ;If ship hits upper wall, reverse its velocity
    Else If i\y <= 0  
        i\y = 5    ;keep it on screen
        i\yv = -i\yv  ;fix its velocity
    
    ;If ship hits lower wall, reverse its velocity
    Else If i\y >= 410 
        i\y = 405   ;keep it on screen
        i\yv = -i\yv  ;fix its velocity
    End If
    
    ;If it is time for the enemy to fire another bullet, fire the bullet
    If MilliSecs() >= shotsfiredtime + TIMEBETWEENENEMYBULLETS
        
        ;Create the new bullet
        CreateBullet(i\x,i\y,2)
 
        ;reset the bullet fire timer
        resetshotstime = 1
    EndIf
    
    ;Update ship's frame
    i\frame = i\frame + 1
 
    ;make sure frame isnt too large
    If i\frame >= 9
        i\frame = 0
    EndIf
 
 
Next ;next ship
 
;If the directiontime counter should be reset, reset it
If resetdirectiontime Then 
    directiontime = MilliSecs() 
    resetdirectiontime = 0
EndIf
 
;If the shotstime counter should be reset, reset it
If resetshotstime Then
    shotsfiredtime = MilliSecs()
    resetshotstime = 0
EndIf
 
 
End Function
 
 
;;;;;;;;;;;;;;;;;;;
;DrawHUD()
;Draws the HUD - the displays, health, etc.
;;;;;;;;;;;;;;;;;;;
 
Function DrawHUD()
 
;increment health's frame
healthframe = healthframe + 1
 
;don't let health frame get too large
If healthframe >=10
    healthframe = 0
EndIf
 
;Draw as many hitpoints on the HUD as hitpoints the player has remaining
For i=1 To player\hits
 
    ;Draw healthimage in topleft
    DrawImage healthimage,i*50 - 35,10,healthframe
 
Next
 
;Display topright info
Text 510, 10, "Enemy Hits:  " + enemyhits 
Text 510, 30, "Shots Fired: " + shotsfired
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;CreateExplosions
;Creates an explosion. First parameter is x coordinate, second is y coord, and thrid is 1 if  the explosion is from a player, and 2 if from an enemy
;;;;;;;;;;;;;;;;;;;
 
Function CreateExplosion(x,y,from)
 
ex.explosion = New explosion
ex\x = x
ex\y = y
ex\from = from
ex\frame = 0
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;UpdateExposions()
;Updates all of the enemy explosions
;;;;;;;;;;;;;;;;;;;
 
Function UpdateExplosions()
 
 
For ex.explosion = Each explosion
;If explosion is from enemy, draw it and update it
 
 
    DrawImage enemyexplosionimage,ex\x,ex\y,ex\frame
 
 
    ;Update explosion
    ex\frame = ex\frame + 1
 
    ;if the enemy has exploded, delete the explosion
    ;Don't delete player explosions, we need it to detect when the player has dies
    If ex\from = 2
    If ex\frame>=7  
        Delete ex
    EndIf
    EndIf
Next
End Function
 
 
 
 
 
 
;;;;;;;;;;;;;;;;;;;
;GameOver()
;Deletes every object, quits game
;;;;;;;;;;;;;;;;;;;
 
Function GameOver()
 
 
 
 
Text 320,270, "Press Any Key To Quit.",True,True
Flip
 
;Delay for 2 seconds
Delay 2000
 
;Clear the key buffer
FlushKeys
 
;Wait for user to press something
WaitKey()
 
;Delete all the bullets
For i.bullet = Each bullet 
    Delete i
Next
 
;Delete all the enemy ships
For e.ship = Each ship 
    Delete e
Next
 
;Delete the player
For u.user = Each user ;Delete player
    Delete u
Next
 
;End the game
End
End Function
Вот у меня оригинал этой игры...Я просто изменил имя космического корабля и картинку космического корабля на dreadstrip. И пришлось поменять названия...
0
PB
11.12.2011, 21:51

Не по теме:

По моему, vikusya1298, не читает что написали выше.=-O:wall:

0
0 / 0 / 0
Регистрация: 09.06.2011
Сообщений: 64
13.12.2011, 03:08  [ТС]
Я проверяла работает оригинал а копия не работает может самой написать игру по оригиналу? Да я пишу на Blitz Basic 3D. Вот напишу игру и найду ошибку.

Добавлено через 6 часов 44 минуты
PureBasic
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
;Inasions and Capture of Strangers!!!
;Разработано Маниш Сети 7/22/02
;Аналог Space invaders
 
 
;Установка графического режима 640x480
Graphics 640,480 
 
;Установка Backbuffer и AutoMidHandle
SetBuffer BackBuffer() 
AutoMidHandle True
 
;Инициализация генератора случайных чисел
SeedRnd MilliSecs() 
 
;Изображения
;Изображения игрока
;Эти изображения относятся к игроку
Global dreadstripimage = LoadAnimImage("dreadstrip.bmp",35,32,0,13)   ;Вид игрока на экране
Global bulletdreadstripimage = LoadAnimImage("dreadstripbullet.bmp",40,19,0,10)    ;Пуля игрока
 
Global dreadstripexplosionimage = LoadAnimImage("dreadstriprexplosion.bmp",64,64,0,8)
 
;Изображения врагов
;Эти изображения относятся ко врагам
Global enemyimage = LoadAnimImage("enemy.bmp",68,38, 0, 10) ;Вид противника на экране
Global bulletenemyimage = LoadAnimImage("enemybullet.bmp",40,19,0,5) ;Пуля врага
Global enemyexplosionimage = LoadAnimImage("enemyexplosion.bmp",64,64,0,8)
 
;Прочие изображения
Global healthimage = LoadAnimImage("health.bmp",33,21,0,10)    ;изображение здоровья
Global backgroundimage = LoadImage("stars.bmp") ;фоновое изображение
splashscreenimage = LoadImage("splashscreen.bmp")   ;экран с пятнами
 
 
 
;Звуки/Музыка
;Звуки
Global explosionsound = LoadSound("explode.wav")
Global bulletsound = LoadSound("zing.wav")
 
;Воспроизведение фоновой музыки
backgroundmusic = PlayMusic ("Interim Nation - Human Update.mp3")
 
;Константы
 
;Коды клавиш
Const ESCKEY = 1, SPACEBAR = 57, LEFTKEY = 203, RIGHTKEY = 205 
 
;Количество миллисекунд между изменениями направлений движения кораблей противника
Const CHANGEENEMYDIRECTION = 700 
 
;Интервал времени между выстрелами противника
Const TIMEBETWEENENEMYBULLETS = 1200
 
;Глобальные переменные
;Создание глобальных переменных, используемых в программе
Global numofenemies  ;число врагов
 
Global directiontime ;счетчик между изменениями направлений движения противника
 
Global shotsfiredtime ;счетчик между выстрелами врага
 
Global enemyhits ;Количество попаданий игрока в корабль противника
 
Global shotsfired ;Количество выстрелов игрока
 
Global playerdamage ;Количество попаданий в корабль игрока
 
Global playerscore   ;Счет игрока
 
Global scrolly   ;переменная изменения фона
 
Global healthframe  ;переменная, отслеживающая здоровье
 
 
;Типы
 
;Тип ship: враги описываются этим типом
Type ship           
    Field x,y  ;Координаты x и y 
    Field hits  ;здоровье корабля
    Field xv,yv  ;скорости в направлениях  x и y
    Field frame ;фрейм изображения корабля
End Type
 
 
 
;Тип user: игрок описывается этим типом
Type user
    Field x,y   ;координаты игрока
    Field hits  ;здоровье игрока
    Field frame ;текущий фрейм игрока
    Field draw  ;1 если игрока надо перерисовать, иначе 0
End Type
 
;инициализация корабля игрока перед началом игры
Global dreadstrip.user = New user  ;создать новый корабль
dreadstrip\x = 640/2 ;игрок располагается в центре экрана
dreadstrip\y = 440  ;игрок  у нижнего края поля
dreadstrip\hits = 3
dreadstrip\draw = 1
 
 
;Тип bullet: описывает пули игрока и противника
Type bullet           
    Field x,y   ;координаты пули
    Field draw ;если значение 1, то пулю следует нарисовать, если 0, то удалить
    Field from  ;если значение 1, то пуля выпущена игроком, если 2, то врагом
    Field frame   ;фрейм изображения. У пули игрока 10 фреймов, а у пули врага - 5 
End Type
 
;Тип explosion: описывает взрывы игрока и врага
Type explosion
    Field x,y    ;координаты
    Field from   ;1 = игрок, 2 = враг
    Field frame  ;фрейм изображения
End Type
 
;Текущий уровень: начальное значение 1
level = 1 
 
;;;;;;;;;;;;;;;;;;;
;Основная программа (первая функция)
;Инициализирует игрока и вызывает другие функции (обеспечивает ввод)
;;;;;;;;;;;;;;;;;;;
;Сделать громкость звук выстрела ниже
;Он будет составлять 25% от максимальной громкости
SoundVolume bulletsound, .25
 
;Отобразить промежуточный экран на 7 секунд
DrawImage(splashscreenimage, 320,240)
Flip
Delay 7000
 
 
;Приравнять время между изменениями направления движения кораблей противника и выстрелами текущему времени
directiontime = shotsfiredtime = MilliSecs()
 
;Инициализация уровня
InitializeLevel(level)
 
 
;Главный цикл
 
While Not KeyDown(ESCKEY) 
 
    ;Нарисовать фон
    TileBlock backgroundImage,0,scrolly
    
    ;Немного сместить фон
    scrolly=scrolly + 1
    
    ;Если величина scrolly слишком велика, обнулить
    If scrolly=ImageHeight(backgroundImage) Then
        scrolly=0
    EndIf
 
    
    ;Если на экране больше нет врагов, то игрок прошел уровень. Поэтому нужно перейти на следующий уровень.
    If numofenemies = 0 Then
        
        ;Увеличить номер уровня
        level = level + 1
        
        ;Инициализировать новый уровень
        InitializeLevel(level)
    EndIf
    
    ;Если нажата клавиша Пробел
    If KeyHit(SPACEBAR) 
            
            ;Создать новую пулю в точке с координатами игрока ('1' означает, что пуля выпущена игроком)
            CreateBullet(dreadstrip\x,dreadstrip\y , 1) 
        
            ;Увеличить счетчик выстрелов
            shotsfired = shotsfired + 1
            ;воспроизвести звук пули
            PlaySound(bulletsound)
        EndIf
        
 
    ;Если нажата клавиша Влево, сместить игрока на 10 пикселей влево
    If KeyDown(LEFTKEY)
        
        dreadstrip\x =dreadstrip\x - 10
        
        
        ;Если игрок вышел за границы экрана, вернуть его на экран
        If dreadstrip\x <= 0
            dreadstrip\x = 10
        EndIf
 
        ;наклонить корабль игрока влево
        dreadstrip\frame =dreadstrip\frame - 1
        
        ;номер фрейма не должен быть меньше нуля
        If dreadstrip\frame <= 0
            dreadstrip\frame = 0
        EndIf
    EndIf
    
    ;Если нажата клавиша Вправо, переместить игрока на 10 пикселей вправо
    If KeyDown(RIGHTKEY)
        dreadstrip\x =dreadstrip\x + 10
    
        ;Если игрок вышел за границы экрана, вернуть его на экран
        If dreadstrip\x >= 610
            dreadstrip\x = 610
        EndIf
        
        
        ;наклонить игрока вправо
        dreadstrip\frame =dreadstrip\frame + 1
        
        ;нельзя допустить, чтобы номер фрейма стал очень большим
        If dreadstrip\frame >= 12
            dreadstrip\frame = 12
        EndIf
    EndIf
    
    ;Начать изменение фрейма корабля игрока
    If (Not KeyDown(RIGHTKEY)) And (Not KeyDown(LEFTKEY))
        If dreadstrip\frame < 7
            dreadstrip\frame = dreadstrip\frame + 1
        ElseIf dreadstrip\frame > 7
            dreadstrip\frame = dreadstrip\frame - 1
        EndIf
    EndIf 
    ;Вызов нужных функций
    ;Отображение информации об игроке
    DrawHUD()
    ;Рисование всех кораблей противника и игрока
    DrawShips()
    ;Обновление движений противника и выстрелов
    EnemyAI()
    ;Перемещение всех пуль и удаление ненужных
    UpdateBullets() 
    ;удаление всех существующих взрывов
    UpdateExplosions()
 
    Flip
    
    ;подождать долю секунды
    Delay 25
Wend ;Конец цикла While 
 
GameOver()
;;;;;;;;;;;;;;;;;;;
;Конец основной программы
;
;;;;;;;;;;;;;;;;;;;
 
 
;;;;;;;;;;;;;;;;;;;
;CreateBullet(x,y)
;Эта функция создает пулю в точке с координатами x и y
;;;;;;;;;;;;;;;;;;;
Function CreateBullet(x,y, from)
 
 
    ;Создать новую пулю
    bullets.bullet = New bullet 
    
    ;Установить координаты точки, в которой находится корабль, произведший выстрел
    bullets\x = x
    bullets\y = y  
    
    ;Пулю следует нарисовать
    bullets\draw = 1 
    
    ;Кто произвел выстрел
    bullets\from = from 
 
 
 
End Function ;Конец CreateBullet
 
 
;;;;;;;;;;;;;;;;;;;
;UpdateBullets()
;Обновляет положение пуль, и удаляет ненужные
;;;;;;;;;;;;;;;;;;;
 
Function UpdateBullets()
 
 
;Проверка всех пуль. В зависимости от того, кто выстрелил, переместить  пулю в нужном направлении. После чего нарисовать пулю. 
;И, наконец, проверить, в какой корабль попала пуля
For i.bullet = Each bullet ;Проверка всех пуль
    
    ;Если выстрелил игрок, то переместить вверх
    If i\from = 1 
        i\y = i\y - 10 
    
    ;Иначе вниз
    Else 
        i\y = i\y + 10 
    EndIf
            
    ;Если пулю следует нарисовать, то сделать это нужным цветом
    If i\draw = 1 
        
        ;Если пуля игрока, то нарисовать пулю игрока
        If i\from = 1
            DrawImage (bulletdreadstripImage, i\x, i\y, i\frame) 
        
        ;Если пуля противника, то нарисовать пулю противника
        Else
            DrawImage (bulletEnemyImage, i\x, i\y, i\frame) 
        EndIf
    EndIf
    
    
    
    
    ;Проверка, попала ли пуля в какой-нибудь корабль
    
    ;Проверка, попала ли пуля игрока в корабль противника
    If i\from = 1 
    
    ;Для всех врагов, если было попадание, то уменьшить здоровье
    For e.ship = Each ship ;проверка врагов
        
        ;Если пуля попала в корабль врага, то уменьшить здоровье
        If ImagesCollide(bulletdreadstripimage, i\x,i\y,0, enemyimage, e\x, e\y, 0) 
            
            e\hits = e\hits - 1 
        
        
            ;увеличить счетчик попаданий игрока в корабли противника
            enemyhits = enemyhits + 1
            
            ;если здоровье корабля противника кончилось, то удалить корабль
            If e\hits <= 0
            
                numofenemies = numofenemies - 1
                ;создать взрыв в точке с координатами корабля противника. "2" означает, что взорван корабль противника, а не игрока.
                CreateExplosion(e\x,e\y,2)
            
                ;уничтожить корабль противника
                Delete e 
                ;воспроизвести звук взрыва
                PlaySound(explosionsound)
                
 
            EndIf 
        
        ;Убедиться, что пуля не отображается (в следующем фрейме она будет уничтожена)
        i\draw = 0
        EndIf 
        
        
    Next   ;проверка следующего корабля противника
    
    EndIf 
    
    ;проверка попадания пули противника в корабль игрока
    ;не проверять, если корабль игрока уже взорван
    If i\from = 2 And dreadstripexplosion = 0
        ;Если пуля попала в корабль игрока, то уменьшить здоровье и добавить повреждения
        If ImagesCollide(bulletenemyimage,i\x, i\y, 0, dreadstripimage,dreadstrip\x, dreadstrip\y, 0)
            
            ;уменьшить здоровье
            dreadstrip\hits = dreadstrip\hits - 1
        
 
            ;Если у корабля игрока закончилось здоровье, вызвать функцию gameover()
            If dreadstrip\hits <= 0 
                ;воспроизвести звук взрыва
                PlaySound(explosionsound)
                CreateExplosion(dreadstrip\x,dreadstrip\y,1)
                ;больше не рисовать корабль игрока
                dreadstrip\draw = 0
            EndIf
        ;Убедиться, что пуля больше не будет рисоваться
        i\draw = 0
        
        EndIf 
        
    EndIf
    
        
        ;Если корабль игрока подбит, то нарисовать взрыв
    If dreadstrip\hits <= 0
    
        For ex.explosion = Each explosion
            If ex\from = 1 And ex\frame >= 7
    
                GameOver()
    
            EndIf
        Next    
    EndIf
 
 
    ;увеличить номер фрейма
    i\frame = i\frame + 1
    ;Если корабль игрока, то 10 фреймов,
    If i\from = 1 And i\frame >= 10
        i\frame = 0
    ;Если корабль противника, то 5 фреймов
    ElseIf i\from = 2 And i\frame >=5
        i\frame = 0
    EndIf
        
    ;Если пуля вышла за видимую область экрана, удалить ее
    If i\y < 0 Or i\draw = 0
        Delete i 
    EndIf 
 
    
 
Next ;перейти к следующей пуле
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;InitializeLevel(level)
;Установка параметров текущего уровня
;;;;;;;;;;;;;;;;;;;
 
Function InitializeLevel(level)
 
 
;Удалить все пули
For i.bullet = Each bullet
    Delete i
Next
 
 
;Показать вводный текст
Text 230,240,"NOW ENTERING Level " + level
Flip
 
;Задержка на несколько секунд
Delay 2000
 
 
;Установить здоровье игрока
dreadstrip\hits = 3
 
;установить номер фрейма игрока
dreadstrip\frame = 7   ;(7 – это средний фрейм)
 
;Установить число кораблей противника от 3 до 5 + текущий уровень
numofenemies = level + Rand(3 , 5)    ;На 1 уровне от 4 до 6 противников, на 2 уровне - 5-7 и т.д.
 
;инициализировать индикатор здоровья
healthframe = 0
 
 
;создать нужное число врагов
For e=1 To numofenemies
 
    CreateNewEnemy(level) 
Next
    
    
End Function 
;;;;;;;;;;;;;;;;;;;
;CreateNewEnemy(level)
;Создать нового врага
;;;;;;;;;;;;;;;;;;;
 
Function CreateNewEnemy(level)
 
;Создать новый корабль врага
enemy.ship = New ship
 
;переменная releasepoint определяет, где будет стартовать корабль противника (в верхней, левой или правой части экрана)
releasepoint = Rand(1,4) 
 
;25% кораблей противника будут запущены с левой и правой сторон экрана, 50% - с верхней
Select releasepoint
 
    Case 1   ;если враг стартует в левой части экрана
        
        ;установить координаты корабля противника
        enemy\x = 5
        enemy\y = Rand(0 , 420)   ;Корабль противника появляется  в произвольной точке в левой части экрана
        
        ;инициализировать скорости
        enemy\xv = Rand(1 , 2)
        enemy\yv = Rand(-2,2)
        
    Case 2   ;корабль противника стартует в верхней части экрана
        ;установить координаты корабля противника
        enemy\x = Rand(0,640)    ;Корабль противника появляется в произвольной точке верхней части экрана
        enemy\y = 5
        
        ;инициализировать скорости
        enemy\xv = Rand(-2, 2)
        enemy\yv = Rand(1,2)
        
    Case 3 ;корабль противника стартует в верхней части экрана
        ;set up enemy coordinates
        enemy\x = Rand(0,640)   ;Корабль противника появляется в произвольной точке верхней части экрана
        enemy\y = 5
        
        ;инициализировать скорости
        enemy\xv = Rand(-2, 2)
        enemy\yv = Rand(1,2)
        
        
    Case 4 ;корабль противника стартует в правой части экрана
        ;установить координаты корабля противника
        enemy\x = 620
        enemy\y = Rand(0 , 420) ;Корабль противника появляется в произвольной точке правой части экрана
        
        ;инициализировать скорости 
        enemy\xv = Rand(-2, -1)
        enemy\yv = Rand(-2,2)
        
        
    Default ;если возникла ошибка
        Print "ERROR, Enemy unleashed in a nonexistant place!"
End Select
 
enemy\hits = level
End Function
        
 
 
;;;;;;;;;;;;;;;;;;;
;DrawShips()
;Рисует корабли игрока и противника
;;;;;;;;;;;;;;;;;;;
Function DrawShips()
 
;Нарисовать все корабли
;Для каждого корабля противника
For i.ship = Each ship   
    DrawImage(enemyImage, i\x, i\y, i\frame)
Next
;Для каждого корабля игрока
For j.user = Each user 
    ;если корабль игрока нужно нарисовать
    If j\draw = 1
        DrawImage(dreadstripImage, j\x, j\y, j\frame)
    EndIf
Next
 
End Function 
 
 
;;;;;;;;;;;;;;;;;;;
;EnemyAI()
;Обновление статуса кораблей противника и вычисление их движений
;;;;;;;;;;;;;;;;;;;
Function EnemyAI()
 
 
;Проверить каждый корабль противника. Определить, следует ли изменить их скорости, убедиться, что они не выходят за видимую область экрана, и стреляют
For i.ship = Each ship 
 
    ;Если пришло время изменить скорость корабля, то сделать это
        If directiontime <= MilliSecs() - CHANGEENEMYDIRECTION 
        i\xv = i\xv+Rand(-2,2)   ;изменение скорости x 
        i\yv = i\yv+Rand(-2,2)   ;изменение скорости y 
        
        resetdirectiontime = 1 
    EndIf
    
    ;Если скорость x очень велика, то уменьшить ее
    If ixv > 5 Then
       i\xv = i\xv - 2
    EndIf
    
    ;Если скорость y очень велика, то уменьшить ее
    If i\yv > 5 Then
        i\yv = i\yv - 2
    EndIf
    
    ;Если скорость x очень низкая, то увеличить ее
    If ixv < -5 Then
       i\xv = i\xv + 2
    EndIf
    
    ;Если скорость y слишком мала, то увеличить ее
    If i\yv < -5 Then
        i\yv = i\yv +2
    EndIf
 
    ;Обновить координаты корабля
    i\x = i\x + i\xv 
    i\y = i\y + i\yv
    
    ;Проверить положение кораблей
    
    ;Если корабль входит за левую границу экрана, то изменить знак его скорости
    If i\x <= 0 
        i\x = 5    ;оставить на экране
        i\xv = -i\xv    ;изменить скорость
        
    ; Если корабль входит за правую границу экрана, то изменить знак его скорости
    Else If i\x >=620
        i\x = 615    ;оставить на экране
        i\xv = -i\xv   ;изменить скорость
    
    ; Если корабль входит за верхнюю границу экрана, то изменить знак его скорости
    Else If i\y <= 0  
        i\y = 5    ;оставить на экране
        i\yv = -i\yv  ;изменить скорость
    
    ; Если корабль входит за нижнюю границу экрана, то изменить знак его скорости
    Else If i\y >= 410 
        i\y = 405   ;оставить на экране
        i\yv = -i\yv  ;изменить скорость
    End If
    
    ;Если пора выполнять следующий выстрел, то сделать это
    If MilliSecs() >= shotsfiredtime + TIMEBETWEENENEMYBULLETS
        
        ;Создать новую пулю
        CreateBullet(i\x,i\y,2)
 
        ;сбросить счетчик времени выстрела
        resetshotstime = 1
    EndIf
    
    ;Обновить фрейм корабля
    i\frame = i\frame + 1
 
    ;удостовериться, что номер фрейма не слишком велик 
    If i\frame >= 9
        i\frame = 0
    EndIf
 
 
Next ;следующий корабль
 
;Если счетчик directiontime нужно сбросить, то сделать это
If resetdirectiontime Then 
    directiontime = MilliSecs() 
    resetdirectiontime = 0
EndIf
 
;Если счетчик shotstime нужно сбросить, то сделать это
If resetshotstime Then
    shotsfiredtime = MilliSecs()
    resetshotstime = 0
EndIf
 
 
End Function
 
 
;;;;;;;;;;;;;;;;;;;
;DrawHUD()
;Рисует HUD – отображает всю необходимую информацию.
;;;;;;;;;;;;;;;;;;;
 
Function DrawHUD()
 
;увеличить фрейм индикатора здоровья
healthframe = healthframe + 1
 
;проверить, что номер фрейма индикатора здоровья не слишком велик
If healthframe >=10
    healthframe = 0
EndIf
 
;Рисует здоровье, оставшееся у корабля игрока
For i=1 To dreadstrip\hits
 
    ;Рисует healthimage в верхнем левом углу
    DrawImage healthimage,i*50 - 35,10,healthframe
 
Next
 
;Отображение информации в верхнем правом углу
Text 510, 10, "Enemy Hits:  " + enemyhits 
Text 510, 30, "Shots Fired: " + shotsfired
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;Создание взрывов
;Создаются взрывы. Первый параметр – координата x, второй – координата  y, а третий 1, если взрывается корабль игрока, и 2, если взрывается корабль противника. 
;;;;;;;;;;;;;;;;;;;
 
Function CreateExplosion(x,y,from)
 
ex.explosion = New explosion
ex\x = x
ex\y = y
ex\from = from
ex\frame = 0
 
End Function
 
;;;;;;;;;;;;;;;;;;;
;UpdateExposions()
;Обновляет взрывы кораблей противника
;;;;;;;;;;;;;;;;;;;
 
Function UpdateExplosions()
 
 
For ex.explosion = Each explosion
;Если взрывается корабль противника, нарисовать взрыв и обновить изображение
 
 
    DrawImage enemyexplosionimage,ex\x,ex\y,ex\frame
 
 
    ;Обновить фрейм взрыва
    ex\frame = ex\frame + 1
 
    ;Если корабль противника взорван, удалить взрыв
    ;Не удалять взрыв корабля игрока, необходимо определить, когда он был подбит
    If ex\from = 2
    If ex\frame>=7  
        Delete ex
    EndIf
    EndIf
Next
End Function
 
 
 
 
 
 
;;;;;;;;;;;;;;;;;;;
;GameOver()
;Удаляет все объекты, осуществляет выход из игры
;;;;;;;;;;;;;;;;;;;
 
Function GameOver()
 
 
 
 
Text 320,270, "Press Any Key To Quit.",True,True
Flip
 
;Задержка на 2 секунды
Delay 2000
 
;Очистка буфера нажатых клавиш
FlushKeys
 
;Подождать, пока пользователь нажмет какую-нибудь клавишу
WaitKey()
 
;Удалить все пули
For i.bullet = Each bullet 
    Delete i
Next
 
;Удалить все корабли противника
For e.ship = Each ship 
    Delete e
Next
 
;Удалить корабль игрока
For u.user = Each user ;Удалить игрока
    Delete u
Next
 
;Завершить игру
End
End Function
Я всё переделала, у меня получилась копия!!!!!!!!!!
0
Кормпилятор
 Аватар для Quiet Snow
5044 / 1718 / 409
Регистрация: 25.04.2010
Сообщений: 4,827
Записей в блоге: 2
13.12.2011, 15:37
Могу вам только рассказать как такие проги пишутся и отлаживаются.
Извините, нет желания перелопачивать 700 строк ЧУЖОГО кода.

Как правило в какой-либо игре существует множество этапов, которые можно разделить
между собой, тобишь разбить всю программу на процедуры.
Чаще бывает так:
  1. Инициализация программы(уст. экрана, загрузка графики, моделей, скриптов, анимации и т.д.,
    всевозможные прекалькуляции)
    ЦИКЛ
  2. Основной движок игры (собирается из модулей\процедур, работает в цикле):
    • Опрос устройств ввода
    • Игровые вычисения (всё что касается непосредственно игры)
    • Вычисления для графич вывода ( всё что требуется вычислить для вывода графики после
      обсчёта игровых вычислений)
  3. Отрисовка(интерфейс пользователя + игровое поле)
    КОНЕЦ ЦИКЛА
  4. Деинициализация программы (освобождение памяти, устройств и ресурсов, выход из программы)

Каждая задача может быть разбита на несколько модулей, но в конечном итоге все эти модули
запускаются в основном цикле.
Каждый модуль проверяется на работоспособность, фиксируются имена переменных и уровень
доступа(чтобы не пересекались друг с другом, из-за этого появляются очень неприятные баги).
Отладка идёт по частям, пока каждый модуль не будет работать, программисты, которые
"знают что делают" как правило отлаживают прямо в программе, после написания модуля
визуализации, который намертво привязан к структуре программы.
В конечном итоге всё собирается, производится компиляция и прога отдаётся тестеру, либо
тестируется самостоятельно. Вылавливаются все закономерные баги, незакономерные можно
попытаться отсечь методом гипотез и исключений: анализируется из-за чего они возникают,
правится наиболее вероятное место в коде\тщательно тестируется, если не помогло делается
откат изменений, процесс повторяется с учётом полученной информации.
0
0 / 0 / 0
Регистрация: 09.06.2011
Сообщений: 64
13.12.2011, 15:48  [ТС]
Да я понимаю я же всё правильно сделала и у меня вышло. Игра работает на отлично!!!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
13.12.2011, 15:48
Помогаю со студенческими работами здесь

Найти ошибки в коде и исправить эти ошибки - C++
Судя по вываливающейся ошибки, идет двойное освобождение памяти. У самого не получается отловить откуда. A.h #pragma once ...

Найти ошибки в коде и исправить эти ошибки
Есть у меня вот такой код: #include &lt;iostream&gt; using namespace std; class A{ private: int* a; size_t size_; ...

Найти ошибки в коде
Помогите найти ошибки! program one; var a:array of integer; a,n:integer; begin writeln('Vvedite n='); readln(n); ...

Найти ошибки в коде
Не получается вывести результаты в конце,подскажите,пожалуйста,как сделать так чтоб эти значения выводились. Ещё в программе...

Найти ошибки в коде
Почему не работает прога #include&lt;stdio.h&gt; #include &lt;stdlib.h&gt; void main () { int A; int B; int C; int i,j,k; ...


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

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит: токи, напряжения и их 1 и 2 производные при t = 0;. . .
Восстановить юзерскрипты 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
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru