Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Snake-like game for the microbit."""
- from microbit import *
- from random import randint
- from math import floor
- # constants (feel free to toy around with them)
- SCREEN_SIZE = 5
- SPEED = 250
- PLAYER_BRIGHTNESS = 5
- def render(player):
- """Creates a new Image containing the player.
- Args:
- player (tuple): The players position
- Returns:
- An Image object that can be drawn to the LED Matrix
- """
- # your code for exercise (a)
- image = Image("00000:00000:00000:00000:00000")
- image.set_pixel(player[0], player[1], PLAYER_BRIGHTNESS)
- return image
- def update(player, direction):
- """Moves the player from its current position one step in the specified
- direction. Returns the players new position.
- Args:
- player (tuple): The player position
- direction (str): Either 'N', 'S', 'W', or 'E' representing the four
- cardinal directions
- Returns:
- The new player position (tuple)
- """
- # your code for exercise (b)
- # liste wird verwendet, da tupel nicht bearbeitet werden koennen
- pliste = list(player)
- if direction == "N":
- if pliste[1] < 4:
- pliste[1] += 1
- if direction == "E":
- if pliste[0] < 4:
- pliste[0] +=1
- if direction == "S":
- if pliste[1] > 0:
- pliste[1] -= 1
- if direction == "W":
- if pliste[0] > 0:
- pliste[0] -= 1
- return tuple(pliste)
- def process_input(direction):
- """Computes direction changes based on user input. A press of button `B`
- changes the direction 90 degrees clockwise, while button `A` changes it 90
- degrees anti clockwise.
- Args:
- direction ('N', 'S', 'W', or 'E'): The current player direction
- Returns:
- The new player direction ('N', 'S', 'W', or 'E')
- """
- # your code for exercise (c)
- # gegen den uhrzeigersinn
- if button_a.was_pressed() == True:
- if direction == 'N':
- return 'W'
- if direction == 'W':
- return 'S'
- if direction == 'S':
- return 'E'
- if direction == 'E':
- return 'N'
- # im uhrzeigersinn
- elif button_b.was_pressed() == True:
- if direction == 'N':
- return 'E'
- if direction == 'E':
- return 'S'
- if direction == 'S':
- return 'W'
- if direction == 'W':
- return 'N'
- return direction
- if __name__ == "__main__":
- # initialize player position and direction
- player = (2, 4)
- direction = 'N'
- # game loop
- while True:
- direction = process_input(direction)
- player = update(player, direction)
- display.show(render(player))
- sleep(SPEED)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement