def create_pole(settings, screen, poles): pole = Pole(screen, settings.pole_positions[settings.current_level]) pole.x = pole.pos[0] pole.y = pole.pos[1] # print(pole.pos) poles.add(pole)
def __init__(self, port='/dev/ttyACM0', baud=9600, byte_length=3): """ Initate balancer Keyword Arguments: port {str} -- serial port used for the arduino (default: {'/dev/ttyACM0'}) baud {number} -- serial port number used for the arduino (default: {9600}) byte_length {number} -- Length of messages to the arduino (default: {3}) """ # Length of messages to the arduino self.byte_length = byte_length # Serial object self.ard = serial.Serial(port, baud) # Pole object self.pole = Pole(self) # Pole object self.stepper_motor = StepperMotor(self) self._obtained_state = None # Private variables self._running = False
def __init__(self): self.__pole = Pole() self.__player = Player() self.__word = '' self.__wrongGuesses = 0 self.__rightGuesses = 0 self.__characterNum = 0 self.__lettersGuessed = [] self.__gameOver = False self.__categoryChoice = 0
class Table: def __init__(self, width): self.width = width self.tablePhysics = TablePhysics(self.width) self.height = self.tablePhysics.height self.balls = Balls(self.width, self.height) self.pole = Pole(self.balls) #add assets self.tableImg = pygame.image.load('assets/table2.jpg') self.tableImg = self.tableImg.convert() self.tableImg = pygame.transform.scale(self.tableImg, (self.width, int(self.height))) self.preRender() def update(self): self.balls.update() self.pole.update() #gets all the balls that might be intersecting with a wall. Gets mirrorVektors if there is an impact with a wall self.tablePhysics.intersectingLines = [] for ball in self.balls.getMaybeIntersectingBalls( self.tablePhysics.horSpacing, self.tablePhysics.verSpacing): mirrorVectors, inHole = self.tablePhysics.getMirrorVektor( ball.pos, ball.RADIUS) #if ball is in the Hole, remove it from the balls if inHole: self.balls.removeBall(ball) #if there is a mirrorvektor, mirror Ball on this vektor for mirrorVector in mirrorVectors: ball.mirror(mirrorVector[0], mirrorVector[1]) def preRender(self): self.surface = pygame.Surface((self.width, self.height)) self.surface.blit(self.tableImg, (0, 0)) #pygame.draw.rect(self.surface, (55, 236, 85), pygame.Rect(0, 0, self.width, self.height)) #renders all different parts of the table def render(self, screen, x, y): tableSurf = pygame.Surface((self.width, self.height)) tableSurf.blit(self.surface, (0, 0)) self.balls.render(tableSurf) screen.blit(tableSurf, (x, y)) self.pole.render(screen, x, y)
class Hanoi(object): def __init__(self, n=3, start="A", workspace="B", destination="C"): self.startp = Pole(start, 0, 0) self.workspacep = Pole(workspace, 150, 0) self.destinationp = Pole(destination, 300, 0) self.startp.showpole() self.workspacep.showpole() self.destinationp.showpole() for i in range(n): self.startp.pushdisk( Disk("d" + str(i), 0, i * 150, 20, (n - i) * 30)) def move_disk(self, start, destination): disk = start.popdisk() destination.pushdisk(disk) def move_tower(self, n, s, d, w): if n == 1: self.move_disk(s, d) else: self.move_tower(n - 1, s, w, d) self.move_disk(s, d) self.move_tower(n - 1, w, d, s) def solve(self): self.move_tower(3, self.startp, self.destinationp, self.workspacep)
def __init__(self, width): self.width = width self.tablePhysics = TablePhysics(self.width) self.height = self.tablePhysics.height self.balls = Balls(self.width, self.height) self.pole = Pole(self.balls) #add assets self.tableImg = pygame.image.load('assets/table2.jpg') self.tableImg = self.tableImg.convert() self.tableImg = pygame.transform.scale(self.tableImg, (self.width, int(self.height))) self.preRender()
def __init__(self, width, height): self.gravity = 10 self.speed_pole_moving = 1 self.discount_factor_points = 100 self.speed_poles_appearing = 500 self.birds = [Bird()] self.poles = [Pole(width, height)] self.cont = 1
def __init__(self, n=3, start="A", workspace="B", destination="C"): self.startp = Pole(start, 0, 0) self.workspacep = Pole(workspace, 150, 0) self.destinationp = Pole(destination, 300, 0) self.startp.showpole() self.workspacep.showpole() self.destinationp.showpole() for i in range(n): self.startp.pushdisk( Disk("d" + str(i), 0, i * 150, 20, (n - i) * 30))
def __init__(self, level): """Constructor""" self.board = [[' ' for j in range(10 * BOARD_WIDTH)] for i in range(BOARD_HEIGHT)] self.bricks = [] self.pipes = [] self.fire = [] self.left = 0 self.score = 0 self.level = level self.right = BOARD_WIDTH self.game_over = 0 self.boss = Boss(6 * BOARD_WIDTH, BOARD_HEIGHT - 3 - BOSS_HEIGHT - 1, BOSS_HEIGHT, BOSS_WIDTH) self.pipes.append(Pipe(5, BOARD_HEIGHT - 3 - 4, 3, 4)) self.pole = Pole(7 * BOARD_WIDTH, BOARD_HEIGHT - 3 - 12, 12) if self.level == 1: for x_x in range(0, 9 * BOARD_WIDTH, 60): for i in range(len(cloud)): for j in range(len(cloud[i])): self.board[15 + i][x_x + j] = cloud[i][j] else: for x_x in range(4, 9 * BOARD_WIDTH, 3): self.bricks.append(Brick(x_x, 15)) for i in range(20): t_x = randint(0, 5 * BOARD_WIDTH - 5) t_y = BRICK_LEVEL_1 leng = randint(1, 5) for j in range(leng): obj = Brick(t_x + j, t_y) flag = 0 for k in self.bricks: if(k.x_coord <= obj.x_coord and obj.x_coord <= k.x_coord + 2 \ and k.y_coord <= obj.y_coord and obj.y_coord <= k.y_coord + 3) \ or (k.x_coord <= obj.x_coord + 2 and obj.x_coord + 2 <= k.x_coord + 2 \ and k.y_coord <= obj.y_coord and obj.y_coord <= k.y_coord + 2): flag = 1 break if flag == 0: self.bricks.append(obj) cnt = 0 fll = 0 for i in range(0, 10 * BOARD_WIDTH, 3): if cnt == randint(10, 20) or fll == 1: cnt = 0 if self.level == 2: fll = 1 - fll continue if cnt > 20: cnt = 0 continue t_x = i t_y = BOARD_HEIGHT - 3 self.bricks.append(Brick(t_x, t_y)) cnt = cnt + 1 cnt = 0 self.draw_bricks() while cnt < 10: t_x = randint(4, 5 * BOARD_WIDTH - 5) t_h = randint(3, 5) t_y = BOARD_HEIGHT - 3 - t_h fl2 = 0 for pipe in self.pipes: if (pipe.x_coord <= t_x and t_x <= pipe.x_coord + 3) \ or (pipe.x_coord <= t_x + 3 and t_x + 3 <= pipe.x_coord + 3): fl2 = 1 break if fl2 == 0 and self.check_base(t_x, t_y, 3, t_h): self.pipes.append(Pipe(t_x, t_y, 3, t_h)) cnt = cnt + 1 cnt = 0 self.enemies = [] while cnt < 10: if self.create_enemy(randint(12, 5 * BOARD_WIDTH - 5)) is True: cnt = cnt + 1 cnt = 0 self.coins = [] while cnt < 15 * self.level: x_x = randint(0, 6 * BOARD_WIDTH) y_y = BRICK_LEVEL_2 f_l = 1 for coin in self.coins: if coin.x_coord == x_x and coin.y_coord == y_y: f_l = 0 inv = 0 for brick in self.bricks: if brick.y_coord == BRICK_LEVEL_1 \ and (abs(brick.x_coord - x_x) <= 3 or abs(x_x - brick.x_coord + 2) <= 3): inv = 1 break if f_l == 1 and inv == 1: self.coins.append(Coin(x_x, y_y)) cnt = cnt + 1 #self.__BOARD_HEIGHT = BOARD_HEIGHT #self.__BOARD_WIDTH = BOARD_WIDTH self.level_up = 0
class Balancer(): """ balancer class This class containing all the parts of the balancer and performs the actions needed to keep everything running smoothly """ def __init__(self, port='/dev/ttyACM0', baud=9600, byte_length=3): """ Initate balancer Keyword Arguments: port {str} -- serial port used for the arduino (default: {'/dev/ttyACM0'}) baud {number} -- serial port number used for the arduino (default: {9600}) byte_length {number} -- Length of messages to the arduino (default: {3}) """ # Length of messages to the arduino self.byte_length = byte_length # Serial object self.ard = serial.Serial(port, baud) # Pole object self.pole = Pole(self) # Pole object self.stepper_motor = StepperMotor(self) self._obtained_state = None # Private variables self._running = False def run(self): """ Run the balancer object while loop Run all the processes to keep the balancer alive and well """ # While the balancer is still running while self._running: self.single_run() def single_run(self): """ Perform one round of all the balancer processes """ self._read_all() def start(self): """ Start the balancer Initiate and run all the balancer processes Raises: RuntimeError -- [description] """ # Check if the balancer is already running if self._running is True: raise RuntimeError('Balancer already running') # Set the balancer to running self._running = True # Create and start the running loop thread self.thread = threading.Thread(target=self.run) self.thread.start() def stop(self): """ Stop the balancer """ self._running = False def write(self, text): """ Send text message to the arduino Send a message with the correct length to the arduino. Shorter messages Will be elongaded until they reached the correct length. Arguments: text {[type]} -- [description] """ # Make sure the text has the correct length while len(text) < self.byte_length: text += ' ' # Check if the message is too long if len(text) > self.byte_length: raise ValueError("Length of text is too long") # Send message to the Arduino self.ard.write(text.encode('utf-8')) def onstate(self, state): print(state) def get_state(self): self.write("sa") while self._obtained_state is None: time.sleep(0.001) state = self._obtained_state self.state = None return state def _read_all(self): """ Wait for incomming message and handle them propperly""" # Translate the message raw = self.ard.readline() if not raw: raise RuntimeError("something") try: # Convert the message msg = json.loads(raw.decode().replace('\r\n', '')) # Handle the message pole_agle = msg[0] # print(msg) # self.onstate(msg) self._obtained_state = msg # print(msg) except: print('not done', raw) return # Set pole anlge self.pole.set_angle(pole_agle)
class Game(object): def __init__(self): self.__pole = Pole() self.__player = Player() self.__word = '' self.__wrongGuesses = 0 self.__rightGuesses = 0 self.__characterNum = 0 self.__lettersGuessed = [] self.__gameOver = False self.__categoryChoice = 0 def main(self): """ Main event loop for store. :return: None """ command = 'help' parameter = None while command != 'quit': if command == 'help': self.help('help.txt') self.start_game() elif command == 'newGame': self.start_game() elif command == 'guess': self.take_guess() elif self.__gameOver == True: again = toolbox.get_boolean( 'Would you like to play a new game?') if again == True: self.start_game() command, parameter = self.get_command() print('goodbye') def get_command(self): """ Get a valid command from the user. :return: command, parameter """ commands = { 'h': 'help', '?': 'help', 'q': 'quit', 'n': 'newGame', 'g': 'guess' } validCommands = commands.keys() userInput = '&' parameter = None while userInput[0].lower() not in validCommands: userInput = input() if userInput == '': userInput = 'n' parameter = 1 command = commands[userInput[0].lower()] if len(userInput) > 1: parameter = userInput[1:].strip() return command, parameter def help(self, filename, prompt=None): """ Displays instructions. :param filename: The string of helping instructions. :param prompt: :return: None """ with open(filename, 'r') as file: help = file.read() print(help, end='') if prompt: input('\n' + prompt) hi = input("\n\npress <return> to continue") def show_pole(self): if self.__wrongGuesses == 0: string = self.__pole.get_manPrint() elif self.__wrongGuesses == 1: string = self.__pole.onlyHead() elif self.__wrongGuesses == 2: string = self.__pole.headBody() elif self.__wrongGuesses == 3: string = self.__pole.rightArm() elif self.__wrongGuesses == 4: string = self.__pole.leftArm() elif self.__wrongGuesses == 5: string = self.__pole.rightLeg() else: string = self.__pole.fullBody() string += '\n\n****** You got hanged!!! ******' self.__gameOver = True again = toolbox.get_boolean('Would you like to play a new game?') if again == True: self.start_game() return string def show_word(self): string = '' regString = '' currentLetter = '' for letter in self.__word: if letter in self.__lettersGuessed: currentLetter = f' {letter} ' regString += letter else: currentLetter = ' ' string += currentLetter string += '\n' for character in self.__word: string += ' ___ ' if regString == self.__word: print(string) print() string += f'\n\n******* You Guesses It!!! *******' self.__gameOver = True again = toolbox.get_boolean('Would you like to play a new game?') if again == True: self.start_game() return string def status(self): string = f'\nguessed letters: {self.__lettersGuessed} \n' string += f'word: {self.__word} \n' string += f'wrong guesses: {self.__wrongGuesses} \n' string += f'right guesses: {self.__rightGuesses} \n' return string def start_game(self): self.__word = '' self.__wrongGuesses = 0 self.__rightGuesses = 0 self.__characterNum = 0 self.__lettersGuessed = [] self.__word = random.choice(self.get_category()) self.__characterNum = len(self.__word) print(self.show_pole() + '\n' + self.show_word()) print('Your word is chosen.') def get_category(self): print("\nHere are your categories of words to choose from:") print("1. Animals 2. Foods 3. Sports") self.__categoryChoice = toolbox.get_integer_between( 1, 3, 'Which category do you want to use? ') if self.__categoryChoice == 1: self.__categoryChoice = wordList1 elif self.__categoryChoice == 2: self.__categoryChoice = wordList2 else: self.__categoryChoice = wordList3 return self.__categoryChoice def take_guess(self): currentGuess = self.__player.guess() readyForPrint = False while readyForPrint == False: for letter in self.__lettersGuessed: while currentGuess in self.__lettersGuessed: print(f'You have already guessed {currentGuess}.') currentGuess = self.__player.guess() self.__lettersGuessed.append(currentGuess) rightGuess = False for letter in list(self.__word): if letter == currentGuess: self.__rightGuesses += 1 rightGuess = True if rightGuess == False: self.__wrongGuesses += 1 readyForPrint = True print(self.show_pole() + '\n' + self.show_word() + '\n' + self.status()) def get_lettersGuesses(self): return self.__lettersGuessed
def run_game(): radio = pygame.mixer radio.init() pygame.init() settings = Settings() screen = pygame.display.set_mode( (settings.screen_width, settings.screen_height)) pygame.display.set_caption("Mario") clips = [ radio.Sound('sounds/bg_music.wav'), radio.Sound('sounds/block_bump.wav'), radio.Sound('sounds/brick_break.wav'), radio.Sound('sounds/coin.wav'), radio.Sound('sounds/death.wav'), radio.Sound('sounds/extra_life.wav'), radio.Sound('sounds/fireball.wav'), radio.Sound('sounds/jump.wav'), radio.Sound('sounds/kill.wav'), radio.Sound('sounds/pipe.wav'), radio.Sound('sounds/power_spawn.wav'), radio.Sound('sounds/powerup.wav'), radio.Sound('sounds/stage_clear.wav'), radio.Sound('sounds/star.wav') ] pipes = Group() secret_pipes = Group() bricks = Group() secret_bricks = Group() upgrades = Group() enemies = Group() poles = Group() fireballs = Group() flags = Group() ground = Group() # + stats = Stats() for i in range(6, 8): pipe = Pipe(screen, settings, i) secret_pipes.add(pipe) # Create and initialize flag and pole before storing in group flag = Flag(screen, settings, stats) flags.add(flag) pole = Pole(screen, settings) poles.add(pole) mario = Mario(screen, settings, pipes, bricks, upgrades, stats, enemies, poles, radio, clips, fireballs, secret_bricks, secret_pipes, ground) lvl_map = None level = Level(screen, settings, pipes, lvl_map, bricks, upgrades, enemies, flags, poles) display = Display(screen, stats) clips[0].play(-1) while True: # Checks if Mario is in the main level and sets the map, generate the bricks, pipes, flags, and pole # Does this only once if stats.activate_main_lvl: lvl_map = Map(screen, settings, bricks, pipes, mario, enemies, ground, upgrades, stats, secret_bricks) lvl_map.build_brick() # generate pipes and flag/pole for i in range(0, 6): pipe = Pipe(screen, settings, i) pipes.add(pipe) flag = Flag(screen, settings, stats) flags.add(flag) pole = Pole(screen, settings) poles.add(pole) stats.activate_main_lvl = False # Checks if Mario has activated the secret level and sets the map, clears all of the main level # Does this only once if stats.activate_secret: # Clears everything belonging to main level to prevent lag pipes.empty() bricks.empty() enemies.empty() poles.empty() flags.empty() lvl_map = Map(screen, settings, bricks, pipes, mario, enemies, ground, upgrades, stats, secret_bricks) lvl_map.build_brick() stats.activate_secret = False stats.main_level = False if stats.game_active: gf.check_events(mario, stats, clips, fireballs) # If the player gets near the right side, shift the world left (-x) if mario.rect.right >= 600 and stats.main_level: diff = mario.rect.right - 600 mario.rect.right = 600 level.shifting_world(-diff) # If the player gets near the left side, shift the world right (+x) # if mario.rect.left <= 100: # diff = 100 - mario.rect.left # mario.rect.left = 100 # level.shifting_world(diff) gf.update_screen(screen, mario, settings, level, pipes, display, stats, bricks, upgrades, enemies, flags, poles, radio, clips, fireballs, secret_bricks, secret_pipes) pygame.display.flip()
def create_poles(self, width, height): """Create a new pole. Poles are generated during a process coded in class UI""" self.poles.append(Pole(width, height))