Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- BLACK = [0, 0, 0]
- WHITE = [255, 255, 255]
- W, H = 800, 600
- HH = int(H / 2)
- pygame.init()
- DS = pygame.display.set_mode((W, H))
- # player starting position
- playerY = HH
- playerX = 5
- playerSize = 25
- # bullet list and speed
- bullets = []
- bulletSpeed = 20
- # fire button pressed toggle
- fireButtonPressed = False
- # main program loop
- while True:
- e = pygame.event.get() # read events but do nothing
- DS.fill(BLACK)
- pygame.draw.rect(DS, WHITE, [playerX, playerY, playerSize, playerSize]) # draw a rectangle as the player
- # press escape to quit, window controls don't work
- k = pygame.key.get_pressed()
- if k[pygame.K_ESCAPE]: break
- # use the arrow keys UP and DOWN
- if k[pygame.K_UP]:
- playerY -= 10
- elif k[pygame.K_DOWN]:
- playerY += 10
- # space bar fires bullets
- # add player x, y to bullet list
- if k[pygame.K_SPACE] and not fireButtonPressed:
- fireButtonPressed = True
- bullets.append([playerX + int(playerSize / 2), playerY + int(playerSize / 2)]) # add new bullet to the list
- elif not k[pygame.K_SPACE] and fireButtonPressed:
- fireButtonPressed = False
- deleteBullets = [] # you shouldn't delete bullets as you're cycling through a list. delete afterwards
- # cycle through the active bullets
- for b in bullets:
- pygame.draw.circle(DS, WHITE, b, 10) # draw the bullet as a circle
- b[0] += bulletSpeed # add bullet speed to the bullets x position
- if b[0] > W: # if bullet exits the right side of the screen
- deleteBullets.append(b) # add to bullet delete list
- # delete all the "dead" bullets
- for db in deleteBullets:
- bullets.remove(db) # remove it from the bullet list
- pygame.display.update() # update the display
- pygame.time.Clock().tick(27) # limit the frame rate to 27 fps
- pygame.quit()
Add Comment
Please, Sign In to add comment