Let’s see how to make a tiled based game. Instead of just creating node children with a while loop, I will use a list that will be iterated to show the tiles, so that the item of the list will correspond to the tiles and we can manage the interactions with the player and the movement of the sprite in the map. Have fun.
That’s all. This is the code added to make the tile list. To each 1 correspond a tile. Nothing can stop us from covering all the screen with different tiles using lists. For the moment we will keep it simple.
def add_earth(self): ''' draw the tiles for under the player ''' x = 0 tiles = [1,1,1,1,1,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1] for t in tiles: if t == 1: tile = SpriteNode('plf:Ground_Grass', position=(x, 0)) self.ground.add_child(tile) x += 64
The whole code is this:
from scene import * import numpy class Game(Scene): def setup(self): self.add_ground() self.add_background() self.add_earth() self.add_player() def add_ground(self): ''' the root node. the window object, the main surface ''' self.ground=Node(parent=self) def add_background(self): ''' the color of the background ''' self.background_color = '#20106e' def add_earth(self): ''' draw the tiles for under the player ''' x = 0 tiles = [1,1,1,1,1,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1] for t in tiles: if t == 1: tile = SpriteNode('plf:Ground_Grass', position=(x, 0)) self.ground.add_child(tile) x += 64 def add_player(self): self.player = SpriteNode('plf:AlienBeige_front') self.player.anchor_point=(0.5, 0) self.player.position = (self.size.w//2, 32) self.add_child(self.player) def touch_began(self, touch): x, y = touch.location px, py = self.player.position self.move_action = Action.move_to(x, 32, 0.7, TIMING_SINODIAL) self.player.run_action(self.move_action, 'move_action_key') def touch_ended(self, touch): self.player.remove_action("move_action_key") run(Game(), LANDSCAPE, show_fps=True)
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame