def _PositionWidgets(self): # Retrieve the screen. screen = GetScreen() screenDimensions = GetDimensions(screen) # Calculate the positions of texts and buttons. titleDimensions = self._titleLabel.GetDimensions() messageDimensions = self._messageLabel.GetDimensions() continueButtonDimensions = self._continueButton.GetDimensions() titleAndMessageBundleHeight = titleDimensions.Y + messageDimensions.Y self._titleLabel.SetPosition(Vector( (screenDimensions.X - titleDimensions.X) / 2, (screenDimensions.Y - Parameters.Margin - continueButtonDimensions.Y - titleAndMessageBundleHeight) / 2, )) self._messageLabel.SetPosition(Vector( (screenDimensions.X - messageDimensions.X) / 2, self._titleLabel.GetPosition().Y + titleDimensions.Y, )) self._continueButton.SetPosition(Vector( (screenDimensions.X - continueButtonDimensions.X) / 2, screenDimensions.Y - Parameters.Margin - continueButtonDimensions.Y, ))
def __init__(self, scene, verticalOffset, row, direction): # Initialize the node. super().__init__(scene, "Saucer", 500, dropsBonus=True) self._collisionClasses = {"Participants"} self._collisionExceptions = {"BulletFromEnemy"} # Set up the position and the movement. self._position = Vector( GetScreenDimensions().X - 1, verticalOffset + row * (self._dimensions.Y + Parameters.Margin)) self._movement.Set(Parameters.EnemySpeed, [ Vector( GetScreenDimensions().X - Parameters.Margin - self._dimensions.X, self._position.Y), Vector(Parameters.Margin, self._position.Y) ]) # Initialize new member variables. self.AppendTimer("Shot") self.DestroyedByPlayer = False
def _GenerateSurface(self): # Create the surface. self._surface = Surface(self._targetDimensions, SRCALPHA) # Draw the bar. if not self._interpolateColors: currentColor = self._colorOnFull if ( 100 == self._progress) else self._color else: currentColor = InterpolateBetweenColors(self._color, self._colorOnFull, self._progress / 100.0) area = Vector(self._targetDimensions.X * (self._progress / 100), self._targetDimensions.Y) if self._rounded: RenderRoundedRectangle(self._surface, tuple(Vector()), tuple(area), currentColor, 1.0) else: draw.rect(self._surface, currentColor, Rect((0, 0), tuple(area))) # Set the surface as the current surface. self.SetSurface(self._surface)
def _GenerateSprites(self): # Render the text itself. textSurface = RenderText(self._text, self._font, self._textColor) textSurfaceDimensions = GetDimensions(textSurface) # Create both surfaces. surfaceDimensions = textSurfaceDimensions + (Padding * 2) if self._minimumWidth: surfaceDimensions.X = max(self._minimumWidth, surfaceDimensions.X) self._activeSurface = Surface(tuple(surfaceDimensions), SRCALPHA) self._inactiveSurface = self._activeSurface.copy() RenderRoundedRectangle(self._activeSurface, Vector(), surfaceDimensions, (50, 50, 255, 255)) RenderRoundedRectangle(self._inactiveSurface, Vector(), surfaceDimensions, (50, 50, 255, 32)) # Draw text on both surfaces. textPosition = Vector( (surfaceDimensions.X - textSurfaceDimensions.X) / 2, Padding.Y) Blit(self._activeSurface, textSurface, textPosition) Blit(self._inactiveSurface, textSurface, textPosition) # Set the inactive surface as the current surface. self.SetSurface(self._inactiveSurface)
def SpreadHorizontally(destinationSurface, widgets, verticalPosition, margin=None): destinationDimensions = GetDimensions(destinationSurface) if margin: destinationDimensions.X -= 2 * margin widgetDimensions = [x.GetDimensions() for x in widgets] totalWidth = sum([x.X for x in widgetDimensions]) spaceCount = len(widgets) - 1 spaceWidth = (destinationDimensions.X - totalWidth) / spaceCount sumOfWidths = 0 numberOfSpaces = 0 for index in range(len(widgets)): currentPosition = (0 if not margin else margin) + sumOfWidths + numberOfSpaces * spaceWidth position = Vector(currentPosition, verticalPosition) widgets[index].SetPosition(position) sumOfWidths += widgetDimensions[index].X numberOfSpaces += 1
def RenderOverlay(self): if self._cursor: mouseCursorPosition = mouse.get_pos() self._cursor.Blit( GetScreen(), Vector(mouseCursorPosition[0], mouseCursorPosition[1]))
def __init__(self, scene): super().__init__(scene, "Bullet (Red).png")#, movementVector = Vector(0, Parameters.BulletSpeed)) self._collisionClasses = {"Participants"} self._collisionExceptions = {"BulletFromEnemy", "Enemy"} self._movement = Movement(Parameters.BulletSpeed, Vector(0, 1)) Resources().GetSound("Bullet").Play()
def Render(self): super().Render() smallShieldSprite = Resources().GetSprite("Shield", dimensions=Vector(80, 80)) smallShieldSprite.Blit( 0, GetScreen(), AtSameCenter(self.GetPosition(), self.GetDimensions(), smallShieldSprite.GetDimensions()), )
def __init__(self, scene, verticalOffset, row, direction): # Initialize the node. super().__init__(scene, "Enemy", dropsBonus = True) self._collisionClasses = {"Participants"} self._collisionExceptions = {"BulletFromEnemy"} # Set up the position and the movement. self._position = Vector( -(self._dimensions.X - 1) if Direction.Right == direction else (GetScreenDimensions().X - 1), verticalOffset + row * (self._dimensions.Y + Parameters.Margin), ) self._movement.Set(Parameters.EnemySpeed, Vector(direction, 0)) # Initialize new member variables. self.AppendTimer("Shot")
def __init__(self, scene): super().__init__( scene, "Bomb") #, movementVector = Vector(0, -Parameters.BombSpeed)) self._collisionClasses = {"Participants"} self._collisionExceptions = {"Bomb"} self._movement = Movement(Parameters.BombSpeed, Vector(0, -1)) Resources().GetSound("Bomb").Play()
def UpdateBonusDescriptionText(self): bonusManager = self.Player.GetBonusManager() if bonusManager.IsAnyBonusActive(): description = f"{bonusManager.GetActiveBonusName()} bonus is now active [{bonusManager.GetActiveBonusTime()} s left]" else: description = "No bonus is currently active" if self._bonusLabel.SetText(description): self._bonusLabel.SetPosition( Vector( GetScreenDimensions().X - Parameters.Margin - self._bonusLabel.GetDimensions().X, Parameters.Margin))
def __init__(self, scene, sprite, health=1, dropsBonus=True): # Initialize the node. super().__init__(scene, sprite, zIndex=1) # Initialize new member variables. self._maximumHealth = health self._currentHealth = self._maximumHealth self._dropsBonus = dropsBonus self._isDestroyed = False self._healthBar = Bar( self._scene, SetAlpha(Color.Red, HealthBarAlpha), SetAlpha(Color.Green, HealthBarAlpha), Vector(self._dimensions.X, Parameters.HealthBarHeight), interpolateColors=True, rounded=True, )
def _PositionWidgets(self): # Retrieve the screen and its dimensions. screen = GetScreen() screenDimensions = GetDimensions(screen) # Position the top labels. labels = [self._creator, self._version] SpreadHorizontally(screen, labels, Parameters.Margin, Parameters.Margin) # Position the buttons. buttons = [self._newGameButton, self._quitButton] SpreadHorizontally(screen, buttons, 0, Parameters.Margin) MoveToTheBottom(screen, buttons, Parameters.Margin) # Position the title. labelsPartHeight = Parameters.Margin + max( [x.GetDimensions().Y for x in labels]) buttonsPartHeight = Parameters.Margin + max( [x.GetDimensions().Y for x in buttons]) titleDimensions = self._title.GetDimensions() self._title.SetPosition( Vector( (screenDimensions - titleDimensions).X / 2, labelsPartHeight + (screenDimensions.Y - titleDimensions.Y - labelsPartHeight - buttonsPartHeight) / 2, ))
def OnCollision(self, node): self._scene.Append( Effect(self._scene, "Explosion", self, dimensions=Vector(15, 15))) self.Terminate()
def Blit(destination, source, position=Vector()): destination.blit(source, tuple(position))
def GetDimensions(surface): if not surface: return None return Vector(surface.get_width(), surface.get_height())
def __init__(self): self._surface = None self._position = Vector() self._dimensions = Vector()
# Globals. # ## Parameters = SimpleNamespace(Name="Star Battles", Version="1.3", Creator="Beny Synakiewicz", MaximumFrameRate=120, ScreenshotFilePath=Path("Screenshot.png"), HighscoreFilePath=Path("Highscore.txt"), SmallMargin=4, MediumMargin=8, Margin=12, HugeMargin=12 * 12, BarHeight=4, ShadowDistance=Vector(3, 3), HealthBarHeight=6, PlayerSpeed=8, BulletSpeed=0.300, BombSpeed=0.250, EnemySpeed=0.200, BonusSpeed=0.400, CargoSpeed=0.400, EnemyValue=10, SaucerValue=100, SmallTrajectoryDeviation=0.03, BigTrajectoryDeviation=0.06, TripleShotBonusProbability=0.030, TwoBombsBonusProbability=0.060, QuickerShieldBonusProbability=0.020, ShootAroundBonusProbability=0.010,
def Update(self, currentPosition, milisecondsPassed): if not self.Exists(): return # # Prepare the updated position. # updatedPosition = Vector(currentPosition.X, currentPosition.Y) # # If we're dealing with waypoints... # if RouteType.Waypoints == self._routeType: # Retrieve relevant waypoints. currentWaypoint = self._route[self._currentWaypointIndex] nextWaypointIndex = self._currentWaypointIndex + 1 if nextWaypointIndex == len(self._route): nextWaypointIndex = 0 nextWaypoint = self._route[nextWaypointIndex] # Calculate and update current position. currentVectorToNextWaypoint = nextWaypoint - currentPosition currentDirectionVector = currentVectorToNextWaypoint.GetNormalized( ) futurePosition = currentPosition + currentDirectionVector * ( self._speed * milisecondsPassed) futureVectorToNextWaypoint = nextWaypoint - futurePosition currentDistanceToNextWaypoint = currentVectorToNextWaypoint.GetLength( ) futureDistanceToNextWaypoint = futureVectorToNextWaypoint.GetLength( ) if futureDistanceToNextWaypoint >= currentDistanceToNextWaypoint: self._currentWaypointIndex = nextWaypointIndex updatedPosition = self._route[self._currentWaypointIndex] return self.Update(updatedPosition, milisecondsPassed) updatedPosition = futurePosition # # If we're dealing with direction... # else: updatedPosition = currentPosition + self._route * ( self._speed * milisecondsPassed) # # Return the updated position. # return updatedPosition
from Engine.Core.Resources import Resources from Engine.Utilities.Color import Color from Engine.Utilities.General import Blit, GetDimensions, RenderText from Engine.Utilities.Rendering import RenderRoundedRectangle from Engine.Utilities.Vector import Vector from Engine.World.Concepts.Widget import Widget from pygame import Surface, SRCALPHA ## # # Globals. # ## Padding = Vector(15, 5) ## # # The main class. # ## class Button(Widget): # The constructor. def __init__(self, scene, text,
def __init__(self): super().__init__("Background") # Initialize texts. self._scoreLabel = Label( self, "No score is currently tracked", Resources().GetFont("Exo 2", Parameters.SmallTextHeight)) self._scoreLabel.SetPosition( Vector(Parameters.Margin, Parameters.Margin)) self._bonusLabel = Label( self, "No bonus is currently active", Resources().GetFont("Exo 2", Parameters.SmallTextHeight)) self._bonusLabel.SetPosition( Vector( GetScreenDimensions().X - Parameters.Margin - self._bonusLabel.GetDimensions().X, Parameters.Margin)) self.Append([self._scoreLabel, self._bonusLabel]) # Initialize widgets. energyBarDimensions = Vector(GetScreenDimensions().X / 3, Parameters.BarHeight) energyBarVerticalPosition = GetScreenDimensions( ).Y - energyBarDimensions.Y self._bulletEnergyBar = Bar(self, Color.Black, Color.Green, energyBarDimensions) self._bombEnergyBar = Bar(self, Color.Black, Color.Red, energyBarDimensions) self._shieldEnergyBar = Bar(self, Color.Blue, Color.Blue, energyBarDimensions) self._bulletEnergyBar.SetPosition( Vector(0 * energyBarDimensions.X, energyBarVerticalPosition)) self._bombEnergyBar.SetPosition( Vector(1 * energyBarDimensions.X, energyBarVerticalPosition)) self._shieldEnergyBar.SetPosition( Vector(2 * energyBarDimensions.X, energyBarVerticalPosition)) self.Append([ self._bulletEnergyBar, self._bombEnergyBar, self._shieldEnergyBar ]) # Initialize the player. self.Player = Player(self) screenDimensions = GetScreenDimensions() topRightCornerPosition = screenDimensions - self.Player.GetDimensions() self.Player._position = Vector( topRightCornerPosition.X / 2, topRightCornerPosition.Y - 2 * Parameters.Margin - Parameters.BarHeight, ) self.Append(self.Player) # Initialize the battle manager. self._battleManager = BattleManager( self, 2 * Parameters.Margin + self._scoreLabel.GetDimensions().Y)
from Engine.Core.Parameters import Parameters from Engine.Core.Resources import Resources from Engine.Core.State import State from Engine.World.Nodes.AbstractParticipant import AbstractParticipant from Engine.World.Utilities.Positioners import AtBottom from Engine.Utilities.Direction import Direction from Engine.Utilities.General import GetDecision, GetScreenDimensions from Engine.Utilities.Vector import Vector ## # # Globals. # ## ExplosionDimensions = Vector(200, 200) ShootingProbabilityDivisor = 800000 ## # # The main class. # ## class Saucer(AbstractParticipant): # The constructor. def __init__(self, scene, verticalOffset, row, direction):
from Engine.Core.Parameters import Parameters from Engine.Core.Resources import Resources from Engine.Core.State import State from Engine.Utilities.Direction import Direction from Engine.Utilities.General import GetDecision, GetScreenDimensions from Engine.Utilities.Vector import Vector from Engine.World.Nodes.AbstractParticipant import AbstractParticipant from Engine.World.Utilities.Positioners import AtBottom ## # # Globals. # ## ExplosionDimensions = Vector(125, 125) ShootingProbabilityDivisor = 200000 ## # # The main class. # ## class Enemy(AbstractParticipant): # The constructor. def __init__(self, scene, verticalOffset, row, direction): # Initialize the node.