Category:

Python

Title:

Random Target Game with Python

In previous article, we mentioned in the algorithm and the construction of the game with the random target. In this article, we will also play the same game with Python and share the source pictures in the bottom. Our aim here is to adjust the adaptation in the transition from block encoding to textual encoding. If you are approaching this in a concrete way, we show it.

Python application must be installed and the Arcade library needs to be installed before starting the application. 

To download the contents of the program and the source files CLICK HERE. Afteryou have downloaded the content, extract the folder and copy to your Eclipse projects folder and define it as a Python project in Eclipse. Or you can add resources to your own Python project.

Now lets code random target game in Python.

Step 1: Creating a Python project in Eclips

When creating a Python project, we can write a faster and more organized program using the programs we call IDE. For Python, IDE options such as PyCharm, Visual Studio, Atom are available. Eclipse IDE was preferred in here because of the fact that it was free of charge and used in many programming languages. You can use what you want. Probably there will no problem.

First, open a new PyDev project as shown in the screenshot below.

Then we give our project a name like in the following screenshot.


This project was done with Python 3. So please make sure that the interpreter option here is 3.7. Once this is done, our project will be visible in Pydev Package Explorer.


Step 2: Creating folder structure and coding

Here we will create a PyDev Module to write the folder and program for the pictures we will use in the program first. You can do this by right-clicking on the "Random-Target-Shotting-Game" that is written in the name of the project. After you create the folder structure of the program, it will look like this:


The screenshot of the game is as follows:


The source code of the program (main.py) and explanations are as follows:


import arcade   # We include the arcade library to use  object properties
import random    # For Enemy characters random positinon
import os      # To define folder path
import threading   # For enemy characters movement
import time

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768
SPRITE_SCALING_ENEMY = 0.4       # Enemy characters image scale
SPRITE_SCALING_ENEMY_SHOT = 0.2  # Enemy shot image scale
SPRITE_SCALING_TARGET = 0.5      # Target pointer image scale

class ArcadeGame(arcade.Window):   # Game object developed with Arcade Library
 
    def __init__(self, width, height):    # We define game variables and definitions here

        super().__init__(width, height)    # Screen sizes
        file_path = os.path.dirname(os.path.abspath(__file__))   # Path of images and other sources
        os.chdir(file_path) # Setting the sources path
        self.enemy_list = None  # Define enemy_list variable for enemy character sprite list
        self.target_list = None # Define target_list variable for target pointer sprite list
        self.shot_list = None  #  Define shot_list variable for enemy shot sprite list
        self.is_enemy_shot = 0  # For check if we sho the enemy. If we can shot value will be 1.
        self.hit_time = 0 # For our shotting  (mouse click) time
        self.hit_elapsed_time = 0 # For time delay after mouse clicked
        self.enemy_delay = 1 # Using for enemy characters appearing process
        self.score = 0 
        self.health = 10 # First health will be 10
        arcade.set_background_color(arcade.color.APRICOT) # Background color definition. Instead of APRICOT, you can give other values
    def setup(self): # Adjustments for variables and characters in the game are done here
        
        
        self.target_list = arcade.SpriteList()   # Sprite list for target pointer    
        self.target_pointer = arcade.Sprite("images/char/target-pointer.png", SPRITE_SCALING_TARGET) # Normal view
        self.target_pointer_fired = arcade.Sprite("images/char/target-pointer-fired.png", SPRITE_SCALING_TARGET) # Shot view
        self.target_list.append(self.target_pointer) # First set normal view for target_list. If mouse clicked, shot view will be appear
             
        
        self.enemy_list = arcade.SpriteList()    # Sprite list for enemy
        self.enemy_sprite = arcade.Sprite("images/char/enemy-cowboy.png", SPRITE_SCALING_ENEMY) # Normal view
        self.enemy_died_sprite = arcade.Sprite("images/char/enemy-cowboy-died.png", SPRITE_SCALING_ENEMY)  # Shotted view
        self.enemy_sprite.center_x = 0  # First x position for enemy
        self.enemy_sprite.center_y = 250  # First y position for enemy
        self.enemy_list.append(self.enemy_sprite)  

        
        self.shot_list = arcade.SpriteList() # Sprite list for enemy fire
        self.shot_effect = arcade.Sprite("images/effects/shot_image.png", SPRITE_SCALING_ENEMY_SHOT) # Enemy fire image
        self.shot_effect.center_x = 0 # Enemy fire x position
        self.shot_effect.center_y = 250 # Enemy fire y position
        self.shot_list.append(self.shot_effect) # Appending enemy fire image to shot list


    def enemy_shot(self):  # Function for enemy fire
        
        if self.is_enemy_shot == 0: # If we can not hit enemy, it will be shot us
            # Settin enemy fire animation position. Above enemys hand
            self.shot_effect.center_x = self.enemy_sprite.center_x + 38 
            self.shot_effect.center_y = self.enemy_sprite.center_y - 58 
            self.shot_list.append(self.shot_effect)                    
            self.health = self.health - 1  # If it shot us, our health will be decrease
     
        
    def on_mouse_press(self, x: float, y: float, button, modifiers): # Our shots events


        self.hit_time = time.time() # For timing shotting animation
        
        #For becomes sma position normal target view and shotted view
        self.target_pointer_fired.center_x = self.target_pointer.center_x
        self.target_pointer_fired.center_y = self.target_pointer.center_y
        

        self.target_list.append(self.target_pointer_fired)
        
        # If target pointer and enemy sprite have same position and mouse clicked we will shot enemy
        if self.target_pointer.center_x > self.enemy_sprite.center_x - 50  and self.target_pointer.center_x < self.enemy_sprite.center_x + 50 and self.target_pointer.center_y > self.enemy_sprite.center_y - 80 and self.target_pointer.center_y < self.enemy_sprite.center_y + 80:
            self.score += 1
            self.is_enemy_shot = 1 #If enemy is shotted, our health will not decrease
            self.enemy_died_sprite.center_x= self.enemy_sprite.center_x
            self.enemy_died_sprite.center_y= self.enemy_sprite.center_y
            self.enemy_list.append(self.enemy_died_sprite)
  
               
    def enemy_move(self): # Function that allows the enemy to appear at certain intervals and fire at us
         
        if self.health > 0:                 
            enemy_timer = threading.Timer(2, self.enemy_move) # We use the yarn to ensure the movement of the enemy every 2 seconds
            enemy_timer.start()
            if self.enemy_died_sprite in self.enemy_list: # If the enemy has been shot and reappeared, we remove the shot view
                self.enemy_list.remove(self.enemy_died_sprite)                     
            self.enemy_delay = 1 # We use the enemy to be seen from a different location if its screen time is over
            enemy_shot_timer= threading.Timer (1.2, self.enemy_shot) # We call enemy_shot funtion 1.2 seconds after enemy appears
            enemy_shot_timer.start() 
            self.is_enemy_shot = 0  # We set enemy not shot 
        
        if self.enemy_delay == 1: # Enables the enemy to appear again in a different place when the specified time (2 seconds) is elapsed
            self.enemy_sprite.center_x = random.randrange(SCREEN_WIDTH)
            self.enemy_sprite.center_y = random.randrange(100, SCREEN_HEIGHT)
            self.enemy_delay = 0 
            self.shot_effect.kill() # We remove the enemy fire effect in reappearing.
             
    
       
    def on_draw(self):
        
        
        arcade.start_render() # We must use this for all drawings start

        # All sprites drawing
        self.enemy_list.draw()
        self.target_list.draw()
        self.shot_list.draw()
        
                # Score and health situation and variables are shown
        output = f"Score: {self.score}"
        health_info = f"Health: {self.health}"
        arcade.draw_text(output, 10, 20, arcade.color.ANTIQUE_RUBY, 14)
        arcade.draw_text(health_info, 10, 40, arcade.color.ALABAMA_CRIMSON, 14)
        
        
        if self.health <= 0: # If health is over writes GAME OVER
            arcade.draw_text("GAME
 OVER", 410, 384, arcade.color.BISTRE_BROWN, 50)
                
    
    def on_mouse_motion(self, x:float, y:float, dx:float, dy:float): # defined for the target pointer to follow the mouse
        
        
        self.target_pointer.center_x = x
        self.target_pointer.center_y = y
        
        self.target_pointer_fired.center_x = x
        self.target_pointer_fired.center_y = y
        
        
    
    def update(self,delta_time): # Instant update and the structure of the game flow is being created here.        
       
        self.enemy_list.update()
        self.shot_list.update()
        self.target_list.update()
        
        
        self.hit_elapsed_time = time.time()-self.hit_time # Defined for the duration of the fire animation in the target pointer when we fired

        if self.hit_elapsed_time > 0.1: # Fire animations duration is 0.1 second
            self.target_pointer_fired.kill()
          
              
        if self.enemy_delay == 1: 
            self.enemy_move()
          
          
        if self.health <= 0: # If health variable become 0 all sprites will be killed
            self.health = 0  # For health variable no to be sub zero
            self.enemy_sprite.kill()
            self.shot_effect.kill()
            self.target_pointer.kill()
                   

def main():
    game = ArcadeGame(SCREEN_WIDTH, SCREEN_HEIGHT)
    game.setup()
    arcade.run()

if __name__ == "__main__":
    main()
738 views
COMMENTS