Refactored for object
Completion requirements
# pip install pygameimport pygameimport os # needed to get paths to imagesimport math#get path to our gamemyPath = os.path.dirname( os.path.realpath( __file__ ) )screen = pygame.display.set_mode( (800, 600) )# Titlepygame.display.set_caption("Space Invaders")#backgroundbackground = pygame.image.load( os.path.join( myPath, "images\\background.png") )# playerplayerImg = pygame.image.load( os.path.join( myPath, "images\\player.png" ) )playerX = 368playerY = 480playerX_change = 0 # how far to move the playerscore = 0# Enemyclass Enemy:def __init__(self, x, y):self.Img = pygame.image.load( os.path.join( myPath, "images\\enemy.png" ) )self.X = xself.Y = yself.X_change = 2 # how far to move the enemyself.Y_change = 40e1 = Enemy(368, 30)e2 = Enemy(400, 30)# BulletbulletImg = pygame.image.load( os.path.join( myPath, "images\\bullet.png" ) )bulletX = 0bulletY = 0bulletY_change = -3bullet_state = "ready"def draw_sprite( sprite, x, y ):x = int(x)y = int(y)screen.blit( sprite, ( x, y ) ) # blit basically means drawdef fire_bullet( x, y ):global bullet_state, bulletX, bulletYbullet_state = "fire"bulletX = xbulletY = ydef isCollision(x1, y1, x2, y2):hypotenuse = math.sqrt( math.pow(x1 - x2, 2 ) + math.pow(y1 - y2, 2) ) # pythagoras theorumif hypotenuse < 64 :return Trueelse:return False# game looprunning = Truewhile running:for event in pygame.event.get(): # get all python events and loop through themif event.type == pygame.QUIT:running = Falseif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:playerX_change = -2if event.key == pygame.K_RIGHT:playerX_change = 2if event.key == pygame.K_SPACE:if bullet_state == "ready":fire_bullet( playerX + 64 / 2 - 32 / 2, playerY )if event.type == pygame.KEYUP:if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:playerX_change = 0playerX += playerX_changeif playerX <= 0: # if player tries to move too far leftplayerX = 0if playerX >= 800 - 64: # if the player moves too far rightplayerX = 800 - 64e1.X += e1.X_changeif e1.X <= 0: # if player tries to move too far lefte1.X_change = 1e1.Y += e1.Y_changeif e1.X >= 800 - 64: # if the player moves too far righte1.X_change = -1e1.Y += e1.Y_change#bullet movementif bullet_state == "fire":bulletY += bulletY_changeif bulletY <= 0:bullet_state = "ready"#test collisionscollision = isCollision(e1.X + 64 / 2, e1.Y + 64 / 2, bulletX + 32 / 2, bulletY + 32 /2 )if collision and bullet_state == "fire":bullet_state = "ready"score += 1print( score )e1.X = 368e1.Y = 30screen.fill((0,0,0))screen.blit( background, (0,0) )draw_sprite(playerImg, playerX, playerY) # draw the playerdraw_sprite(e1.Img, e1.X, e1.Y)if bullet_state == "fire":draw_sprite(bulletImg, bulletX, bulletY)pygame.display.update() # needed to apply the change
Last modified: Tāite, 26 Noema 2020, 2:58 PM