示例#1
0
 def __intialize(self):
     self.getch = Get()
     self.win = Window()
     self.x_collisions = collision_x.Collision_horizontal()
     self.y_collisions = collision_y.Collision_vertical()
     self.boxes1 = []
     self.boxes2 = []
     self.pipes = []
     self.set_tort = []
     self.coins = []
     for brick in self.characters.boxes1:
         self.boxes1.append(Box(*brick, self.win))
     for brick in self.characters.boxes2:
         if len(self.boxes2) != 1:
             self.boxes2.append(Box(*brick, self.win))
         else:
             self.boxes2.append(Spring(*brick, self.win))
     self.boxes = [self.boxes1, self.boxes2]
     for pipe in self.characters.pipes:
         self.pipes.append(Pipe(pipe, self.win))
     for tort in self.characters.tortise:
         self.set_tort.append(Tort(*tort, self.win))
     for coins in self.characters.coins:
         self.coins.append(Coins(*coins, self.win))
     self.mario = Mario_reddy((*self.characters.mario), self.win)
     os.system("aplay -q ../assets/smb_new.wav &")
     os.system("clear")
     self.win.update_frame(self.mario, self.lives, 0, 1)
    def _loopGame(self):
        paddleobj = []
        ballobj = []
        brickobj = []
        powerupobj = []
        bulletobj = []
        cannonobj = []
        flag = 0
        while (self.status()):
            if self.leveling(brickobj, paddleobj) == 0:
                self.levels -= 1
                num = 3 - self.levels
                paddleobj, ballobj, brickobj, powerupobj, cannonobj, bulletobj = self.fillthescreen(
                    paddleobj, ballobj, brickobj, powerupobj, cannonobj,
                    bulletobj, num)

            getch = Get()
            ch = input_to(getch, 0.1)
            if ch == 'e':
                flag = 1
                break
            # if ch=='k':
            #     bulletobj.append(Bullet(FRAMEHEIGHT-4,int(FRAMEWIDTH/2),1,1,-1,0))
            if (ch == 'f'):
                for i in ballobj:
                    i.isCollidedWithPaddle = False
            print("\033[0;0H")

            self._update(ballobj, paddleobj, ch, brickobj, powerupobj,
                         bulletobj, cannonobj)
            self.checkBricks(brickobj, powerupobj)
            self.checkBall(ballobj, paddleobj)
            self.checkPowerupIsCollided(powerupobj)
            self.checkBullets(bulletobj, cannonobj, paddleobj)
            self._scores(paddleobj)
            self._printGame()
            if ch == 's':
                self.levels -= 1
                num = 3 - self.levels
                paddleobj, ballobj, brickobj, powerupobj, cannonobj, bulletobj = self.fillthescreen(
                    paddleobj, ballobj, brickobj, powerupobj, cannonobj,
                    bulletobj, num)
                print(f'Skipped level{3-self.levels-1}')
            if self.levels == -1:
                flag = 2
                break
        if flag:
            print("You Exited")
            print(f"With Score {paddleobj[0].get_score()}")
        if flag == 2:
            print("You completed all levels")
            print(f"With Score {paddleobj[0].get_score()}")
        else:
            if (self.lives == 0):
                os.system('aplay -q ./sounds/lost.wav&')
                print("You Lost")
                print(f"With Score {paddleobj[0].get_score()}")
            else:
                print("You Won")
                print(f"With Score {paddleobj[0].get_score()}")
示例#3
0
    def gravity(self, boardA, en=None):
        """Bring Mario down if the ground is empty below him"""
        try:
            while (not (self.ground_check(boardA))):

                self._x += 1

                for wi in range(self._dim[1]):
                    boardA.change(self._x - 1, self._y + wi, '.')

                getch = Get()
                chbuff = input_to(getch)

                if (chbuff):
                    self.move(chbuff, boardA)

                if (en):
                    for e in en:
                        e.graze(boardA)
                        e.render(boardA)

                self.render(boardA)
                os.system('clear')

                print(boardA.printBoard())
                print(boardA.count())

            self._jump_flag = 0

        except:
            self.deadf()
            return
    def run(self):
        '''Function to run the main game loop
        '''
        getch = Get()
        while True:
            input = input_to(getch)

            if input is not None:
                if input is 'd':
                    self.right()
                elif input is 'a':
                    self.left()
                elif input is 'w':
                    self.up()
                elif input is 's':
                    self.down()
                elif input is 'q':
                    self.quit()
                elif input is ' ':
                    self.space()
            else:
                if self.__screen.x_cross > 1245 or self.__magnetpresent:
                    self.degravity()
                else:
                    self.gravity()
            # os.system('clear')
            self.update()
            self.render()
            time.sleep(0.02)
示例#5
0
    def user_input(self):
        '''
        Getting input from the user for paddle movement
        '''
        ch = Get()
        ch1 = input_to(ch, self.ball.skip_iteration_tp)

        if ch1 == 'a' or ch1 == 'A':
            self.paddle.move_left()
            self.ball.move_with_paddle()
        elif ch1 == 'd' or ch1 == 'D':
            self.paddle.move_right()
            self.ball.move_with_paddle()
        elif ch1 == 'q' or ch1 == 'Q':
            quit()
        elif ch1 == 'p' or ch1 == 'P':
            self.ball.next_shape()
        elif ch1 == 'i' or ch1 == 'I':
            self.ball.speedx == 2
            self.ball.speedy == 2
        elif ch1 == 'k' or ch1 == 'K':
            self.ball.speedx == 1
            self.ball.speedy == 1
        elif ch1 == 'c' or ch1 == 'C':
            self.ball.expand_paddle_effect()
        elif ch1 == 'v' or ch1 == 'V':
            self.ball.shrink_paddle_effect()
        elif ch1 == 'b' or ch1 == 'B':
            self.ball.default_paddle_effect()
        elif ch1 == ' ':
            self.ball.flip_stick(False)
示例#6
0
    def handle_keyboard_interrupt(self):
        get = Get()
        ch = input_to(get.__call__)
        if ch in KEYS:
            self._paddle.move(ch)
            # if(self._level==2):
            #     self._ufo.move(ch)
            # fixed
            for ball in self._balls:
                ball.move_with_paddle(ch)

        elif (ch == 'q'):
            sys.exit()

        elif (ch == 's'):
            for ball in self._balls:
                ball.start()

        elif (ch == 'r'):
            self._paddle = Paddle([int(self._width / 2) - 4, self._height - 1],
                                  [13, 1], [0, 0], [self._width, self._height])
            self._balls = []
            self._balls.append(
                Ball([int(self._width / 2), self._height - 2], [1, 1], [0, 0],
                     [self._width, self._height], True))

        elif (ch == 'l'):
            self.level_up()
示例#7
0
 def __init__(self):
     self.getch = Get()
     self.player = Player(3, 6, 'player')
     self.player.setNewPosition(0, 0)
     self.board = Board()
     self.tort1 = Tort(1, 1, "tortoise", 1)
     self.tort1.setNewPosition(24, 0)
     self.bossE = BossE(3, 4, "bossE", 1)
     self.bossE.setNewPosition(204, 0)
示例#8
0
文件: main.py 项目: Sumaid/supermario
    def key_checker(self):
        getch = Get()
        start = 0
        while True:
            key_input = input_to(getch)
            if key_input == 'q':
                show_cursor()
                os.system('killall aplay')
                os.system('clear')
                sys.exit()

            if key_input == 'd':
                if time.time() - start > 0.1:
                    start = time.time()
                    next_input = input_to(getch)
                    if next_input == 'w':
                        os.system('aplay -q sound/small_jump.wav &')
                        os.system('clear')
                        cur = self.player.get_position()
                        if cur['x'] < 37:
                            self.player.jumpscene(1)
                        else:
                            self.player.jumpscene()
                    else:
                        self.player.move(2)

            elif key_input == 'a':
                if time.time() - start > 0.1:
                    start = time.time()
                    next_input = input_to(getch)
                    if next_input == 'w':
                        os.system('aplay -q sound/small_jump.wav &')
                        os.system('clear')
                        self.player.jumpscene(-1)
                    else:
                        self.player.move(-2)

            elif key_input == 'w':
                os.system('aplay -q sound/small_jump.wav  &')
                os.system('clear')
                if time.time() - start > 0.1:
                    start = time.time()
                    next_input = input_to(getch)
                    if next_input == 'd':
                        cur = self.player.get_position()
                        if cur['x'] < 37:
                            self.player.jumpscene(1)
                        else:
                            self.player.jumpscene()
                    elif next_input == 'a':
                        self.player.jumpscene(-1)
                    else:
                        self.player.vertical_jump(4)

            self.render()
    def run(self):
        '''Function to run the main game loop
        '''
        playsound('resources/main_theme.wav')
        getch = Get()
        while True:
            self.FRAMES += 1
            input = input_to(getch)

            if input is not None:
                if input is 'd':

                    if self.mario.x + self.mario.width < self.screen.x_cross + 108 / 2:
                        clear_sprite(self.mario, self.screen)
                        if not self.mario.check_right_collision_with_map(
                                self.screen):
                            self.mario.x += self.mario.dx
                    elif self.screen.x_cross >= 864:
                        clear_sprite(self.mario, self.screen)
                        if not self.mario.check_right_collision_with_map(
                                self.screen):
                            self.mario.x += self.mario.dx
                    else:
                        if not self.mario.check_right_collision_with_map(
                                self.screen):
                            self.screen.x_cross += self.mario.dx
                            clear_sprite(self.mario, self.screen)
                            self.mario.x += self.mario.dx
                elif input is 'a':
                    clear_sprite(self.mario, self.screen)
                    if not self.mario.check_left_collision_with_map(
                            self.screen):
                        self.mario.x -= self.mario.dx
                elif input is 'w':
                    playsound('resources/jump.wav')
                    if self.mario.check_bottom_collision_with_map(self.screen):
                        clear_sprite(self.mario, self.screen)
                        self.mario.y -= 3
                        self.mario.mario_jump()

                elif input is 'q':
                    self.quit()

            if self.mario.check_hit_flagpole(self.flagpole):
                self.cue_end_animation()

            if self.mario.lives <= 0:
                self.cue_lost_card()

            os.system('clear')
            self.update()
            self.render(self.MOVE_BG)
            time.sleep(0.02)
示例#10
0
def welcome():
    '''
    Clear the screen and show instruction
    '''
    sys.stdout.flush()
    sys.stdin.flush()
    os.system('tput reset')
    print_art(BRICKBREAKER2, Fore.YELLOW)
    print_art(MYNAME, Fore.YELLOW)
    print_art(INSTRUCTION, Fore.GREEN)
    print_art(GAMEINSTRUCTION, Fore.GREEN)
    ch = Get()
    while True:
        ch1 = input_to(ch, 1000)
        if ch1 == 'g' or ch1 == 'G':
            break
        elif ch1 == 'q' or ch1 == 'Q':
            quit()
示例#11
0
文件: main.py 项目: aishna11/Jetpack
def input_handler():
    '''
    Handles user input and moves the character accordingly
    '''
    getch = Get()
    chbuff = input_to(getch)
    if chbuff:
        if chbuff =='q':
            defs.livesleft = -2
            time.sleep(0.2)
            print("\033[2J",end="")
            exit(0)
        elif chbuff in ['w','a','s','d']:
            defs.main_rider.move(chbuff)
            if chbuff=='w': defs.down=1
            else: defs.down=1
        elif chbuff == 'j':
            bullet.Bullet(defs.main_rider.xpos_left+defs.board_start+len(defs.main_rider.rider[0]),\
                defs.main_rider.ypos_top,2*int(defs.columns))
        elif chbuff == ' ':
            defs.main_rider.sheild() 
    elif not defs.main_rider._isSheilded:
        defs.main_rider.change_rider(0)
示例#12
0
    def user_input(self):
        '''
        Getting input from the user for paddle movement
        '''
        ch = Get()
        ch1 = input_to(ch, self.ball.skip_iteration_tp)

        if ch1 == 'a' or ch1 == 'A':
            self.paddle.move_left()
            self.ball.move_with_paddle()
            if self.game_status.get_stage() == MAXSTAGE:
                self.ufo.move_with_paddle()
        elif ch1 == 'd' or ch1 == 'D':
            self.paddle.move_right()
            self.ball.move_with_paddle()
            if self.game_status.get_stage() == MAXSTAGE:
                self.ufo.move_with_paddle()
        elif ch1 == 'q' or ch1 == 'Q':
            quit()
        elif ch1 == 'p' or ch1 == 'P':
            self.ball.next_shape()
        # elif ch1 == 'i' or ch1 =='I':
        #     self.ball.speedx ==2
        #     self.ball.speedy ==2
        # elif ch1 == 'k' or ch1 =='K':
        #     self.ball.speedx ==1
        # self.ball.speedy ==1
        # elif ch1 == 'c' or ch1=='C':
        #     self.ball.expand_paddle_effect()
        # elif ch1 == 'v' or ch1=='V':
        #     self.ball.shrink_paddle_effect()
        # elif ch1 == 'b' or ch1=='B':
        #     self.ball.default_paddle_effect()
        elif ch1 == ' ':
            self.ball.flip_stick(False)
        elif ch1 == '\\':
            self.game_status.stage_up()
示例#13
0
 def __init__(self):
     defs.board = self.create_board()
     defs.board_check = copy.deepcopy(self.create_check())
     defs.board_start = 0
     stats.Stats.create_board()
     defs.speed = defs.def_speed
     self.__main_riderf.ypos_top = int(defs.rows) - 4
     thread1 = threading.Thread(target=self.gameplay, daemon=True)
     thread1.start()
     while defs.dragonlivesleft >= 0 and defs.livesleft >= 0:
         getch = Get()
         chbuff = input_to(getch)
         if chbuff:
             if chbuff == 'q':
                 exit(0)
             elif chbuff in ['w', 's']:
                 self.__main_riderf.move(chbuff)
                 self.__main_dragon.move(chbuff)
                 if chbuff == 'w':
                     defs.down = 0
             elif chbuff in ['a', 'd']:
                 self.__main_riderf.move(chbuff)
             elif chbuff == 'j':
                 bullet.Bullet(self.__main_riderf.xpos_left+len(self.__main_riderf.rider[0]),\
                     self.__main_riderf.ypos_top,int(defs.columns))
             elif chbuff == ' ':
                 self.__main_riderf.sheild()
         elif not self.__main_riderf._isSheilded:
             self.__main_riderf.change_rider(0)
         self.__main_riderf.check_pos()
     if defs.livesleft >= 0:
         inp.pr_result(1)
     else:
         inp.pr_result(2)
     print('\033[' + defs.rows + ';' + defs.columns + 'f' +
           defs.reset_color)
示例#14
0
 def _loopGame(self):
     paddleobj= []
     paddleobj.append(Paddle(FRAMEHEIGHT-2,int(FRAMEWIDTH/2),1,7,0,0))
     ballobj=[]
     ballobj.append(Ball(FRAMEHEIGHT-3,paddleobj[0]._y+int(paddleobj[0]._ylength/2),1,1,-2,2))
     brickobj=[]
     powerupobj=[]
     brickobj,powerupobj=self.fillBricks()
     flag=0
     while (self.status(brickobj,paddleobj)):
         getch=Get()
         ch=input_to(getch,0.1)
         if ch=='e':
             flag=1
             break
         if(ch=='f'):
             for i in ballobj:
                 i.isCollidedWithPaddle=False
         print("\033[0;0H")
         
         self._update(ballobj,paddleobj,ch,brickobj,powerupobj)
         self.checkBricks(brickobj,powerupobj)
         self.checkBall(ballobj,paddleobj)
         self.checkPowerupIsCollided(powerupobj)
         self.scores(paddleobj)
         self._printGame()
     if flag:
         print("You Exited")
         print(f"With Score {paddleobj[0].score}")
     else:
         if(self.lives==0):
             print("You Lost")
             print(f"With Score {paddleobj[0].score}")
         else:
             print("You Won")
             print(f"With Score {paddleobj[0].score}")
def make_move():
    c = input_to(Get())

    if c == 'a':
        glob.paddle.move_relative(glob.board.matrix, -1)

    if c == 'd':
        glob.paddle.move_relative(glob.board.matrix, 1)

    if c == 'e':
        glob.paddle.release_ball()

    if c == 'y':
        glob.level += 1
        if glob.level == 4:
            os.system('clear')
            print('Game over')
            print('Max score is ', glob.max_points)
            quit()
        glob.init()

    if c == 'q':
        print('game aborted')
        quit()
示例#16
0
ene=enemy(900,3,3,3)
grid.copy_on_board(ene)

######### MAKING SPEED BOOSTER   #########
for i in range(0,10):
	y_position=random.randrange(8,32,1)
	x_position=random.randrange(20,750)

	new=[x_position,y_position,1]  ##1 is the flag that booster is not taken
	booster_list.append(new)

	boo1=booster(x_position,y_position,3,7)
	store_booster.append(boo1)
	grid.copy_on_board(boo1)

getch=Get()
cnt=0
speed_counter=0
old_time=time.time()
waste=0
wait_time=0.1
shield_available=0
shield_last_disabled=old_time
shield_activated_at=old_time
flag=0 ### if flag is 0 check mando-lazer collision
m_dead=0
e_dead=0
l=0
vel=0
game_start_time=int(time.time())
finish_game=0
示例#17
0
print("\033[2J")
while True:
    curr_time = time.time()
    c_ball_time = time.time()

    if(curr_time - prev_time >= 0.05):
        print("\033[0;0H")
        paddle.setTimetaken(int(curr_time-start_time))
        screen.printScreen(ball, paddle)
        prev_time = curr_time

    if(ball.getfree() == 1 and c_ball_time - p_ball_time >= ball.getSpeed()):
        ball.movement(screen, paddle, bricks)
        p_ball_time = c_ball_time
        
    inp = input_to(Get())
    if(inp == None):
        inp = ""
    if (inp == ' ' or inp == ' '):
        if(ball.getfree() == 0):
            ball.release(screen,paddle)
    if (inp == 'a' or inp == 'A' or inp == 'd' or inp == 'D'):
        if(paddle.getStartpaddle() > 0 and paddle.getStartpaddle() + paddle.getLength() < screen.getGamewidth()):
            if(ball.getfree() == 0):
                ball.initializeBall(screen,inp)
        paddle.movement(screen, inp)
    if(inp == 'x' or inp == 'X'):
        exit()

    x += 1
示例#18
0
class Game:
    '''This is the Class of the New Game\n\n
    Functions:\n
    user_input: Takes user input\n
    move_all : Moves all objects\n
    '''
    my_arjun = Game_object(
        35, 5, 75, 6, 0, 0, arjun,
        np.full((6, 75), Fore.RED + Back.BLACK + Style.BRIGHT))
    my_brickbreaker = Game_object(
        10, 13, 123, 6, 0, 0, brickbreaker,
        np.full((6, 123), Fore.WHITE + Back.CYAN + Style.BRIGHT))
    my_press = Game_object(50, 28, 49, 1, 0, 0, presstoplay,
                           np.full((1, 49), Fore.WHITE + Style.BRIGHT))
    game_over = Game_object(20, 3, 106, 7, 0, 0, gameover,
                            np.full((7, 106), Fore.RED + Style.BRIGHT))
    my_continue = Game_object(65, 28, 19, 1, 0, 0, on_continue,
                              np.full((1, 19), Fore.WHITE + Style.BRIGHT))
    my_win = Game_object(45, 3, 58, 6, 0, 0, on_won,
                         np.full(on_won.shape, Fore.WHITE + Style.BRIGHT))
    getch = Get()
    power_up_type = [
        np.array([["P", "P"], ["P", "P"]]),
        np.array([["E", "E"], ["E", "E"]]),
        np.array([["S", "S"], ["S", "S"]]),
        np.array([["G", "G"], ["G", "G"]]),
        np.array([["X", "X"], ["X", "X"]]),
        np.array([[">", ">"], [">", ">"]]),
        np.array([["!", "!"], ["!", "!"]]),
        np.array([["F", "F"], ["F", "F"]]),
    ]
    level = 1
    last_move = 0
    skip_level = False
    level_start = datetime.now()
    over = False
    fireball = False

    def print_meta(self):
        print_string = f"\33[2K Level:%d Lives Left:%d  Score:%d  Time Spend:%d" % (
            self.level, self.lives, self.score, self.time_elapsed())
        if self.level == 3:
            add_me = " "
            for i in range(0, self.ufo.health):
                add_me += "|| "
            print_string += "  UFO health:  " + add_me
        if (self.pass_through):
            print_string += f" P left: %d" % (
                TIME_PASS_THROUGH - self.get_change_in_secs(self.pass_through))
        if (self.paddle.get_powerup_time()):
            print_string += f" S left: %d" % (
                TIME_PADDLE_POWER_UP -
                self.get_change_in_secs(self.paddle.get_powerup_time()))
        if (self.paddle.get_shoot_time()):
            print_string += f" O left: %d" % (
                SHOOT_TIME -
                self.get_change_in_secs(self.paddle.get_shoot_time()))
        if (self.fast_ball):
            print_string += f" F left: %d" % (
                TIME_FAST_BALL - self.get_change_in_secs(self.fast_ball))
        if (self.grab_ball):
            print_string += f" G left: %d" % (
                TIME_GRAB - self.get_change_in_secs(self.grab_ball))
        print(print_string)
        print(
            'a- LEFT. d - right. r - release ball. l - skip level. s - shoot bullet . PRESS p to pause. q to quit.'
        )

    def get_change_in_secs(self, value):
        time_delta = datetime.now() - value
        total_seconds = time_delta.total_seconds()
        return int(total_seconds)

    def check_powerup_times(self):
        if (self.paddle.get_powerup_time()):
            if (self.get_change_in_secs(self.paddle.get_powerup_time()) >
                    TIME_PADDLE_POWER_UP):
                self.paddle.times_up()
        if (self.paddle.get_shoot_time()):
            if (self.get_change_in_secs(self.paddle.get_shoot_time()) >
                    SHOOT_TIME):
                self.paddle.times_up_shoot()
        if (self.pass_through):
            if (self.get_change_in_secs(self.pass_through) >
                    TIME_PASS_THROUGH):
                self.pass_through = 0
        if (self.fast_ball):
            if (self.get_change_in_secs(self.fast_ball) > TIME_FAST_BALL):
                self.fast_ball = 0
                for ball in self.balls:
                    new_xv = 0
                    new_yv = 0
                    if (ball.get_xv()):
                        new_xy = ball.get_xv() - 2 * abs(
                            ball.get_xv()) // ball.get_xv()
                    if (ball.get_yv()):
                        new_yv = ball.get_yv() - 2 * abs(
                            ball.get_yv()) // ball.get_yv()
                    ball.set_xv(new_xv)
                    ball.set_yv(new_yv)
        if (self.grab_ball):
            if (self.get_change_in_secs(self.grab_ball) > TIME_GRAB):
                self.grab_ball = 0
                self.paddle.set_grab()

    def reset(self):
        self.start_time = datetime.now()
        self.level_start = datetime.now()
        self.pass_through = 0
        self.fast_ball = 0
        self.grab_ball = 0
        self.score = 0
        self.win = False
        self.pause_time = 0
        self.lives = LIVES
        self.balls = []
        self.paddle = Paddle(65, 29, 8, 0)
        self.bricks = []
        self.powerups = []
        self.bullets = []
        self.ufo = UFO(65, 1, 8, 0)
        self.bombs = []
        self.level = 1
        self.ufo_count = 0
        self.balls.append(Ball(69, 28, -1, -1))
        self.screen.reset_screen()
        self.update_screen()
        self.screen.print_game_screen()
        self.check_powerup_times()
        self.print_meta()

    def put_bricks(self):
        self.last_move = 0

        if self.level == 1:
            brick_pos = [26, 34, 42, 50, 58, 66, 74, 82, 90, 98, 106, 114]
            self.bricks.clear()
            for y in range(3, 10, 1):
                for x in brick_pos:
                    if ((y == 6 or y == 9) and x == 74):
                        self.bricks.append(
                            chain_brick(x, y, np.random.choice([1, 2, 3, 4,
                                                                5])))
                    elif ((y == 7 or y == 8) and (x >= 58 and x <= 82)):
                        self.bricks.append(
                            chain_brick(x, y, np.random.choice([1, 2, 3, 4,
                                                                5])))
                    else:
                        p = np.random.uniform(0, 1)
                        if (p <= 1 / 4):
                            self.bricks.append(Unbreakable(x, y))
                        else:
                            p = np.random.uniform(0, 1)
                            if p <= 1 / 4:
                                self.bricks.append(
                                    rainbow_brick(
                                        x, y, np.random.choice([1, 2, 3, 4,
                                                                5])))
                            else:
                                self.bricks.append(
                                    Brick(x, y,
                                          np.random.choice([1, 2, 3, 4, 5])))

        if self.level == 2:
            brick_pos = [
                2, 10, 18, 26, 34, 42, 50, 58, 66, 74, 82, 90, 98, 106, 114,
                122, 130, 138
            ]
            self.bricks.clear()
            for y in range(3, 10, 1):
                for x in brick_pos:
                    if ((y == 6 or y == 9) and x == 74):
                        self.bricks.append(
                            chain_brick(x, y, np.random.choice([1, 2, 3, 4,
                                                                5])))
                    elif ((y == 7 or y == 8) and (x >= 58 and x <= 82)):
                        self.bricks.append(
                            chain_brick(x, y, np.random.choice([1, 2, 3, 4,
                                                                5])))
                    else:
                        p = np.random.uniform(0, 1)
                        if (p <= 1 / 4):
                            self.bricks.append(Unbreakable(x, y))
                        else:
                            self.bricks.append(
                                Brick(x, y, np.random.choice([1, 2, 3, 4, 5])))
        if self.level == 3:
            brick_pos = [
                2, 10, 18, 26, 34, 42, 50, 58, 66, 74, 82, 90, 98, 106, 114,
                122, 130, 138
            ]
            self.bricks.clear()
            for y in range(4, 10, 2):
                for x in brick_pos:
                    p = np.random.uniform()
                    if (p <= 1 / 10):
                        self.bricks.append(Unbreakable(x, y))

    def main_screen(self):
        os.system("clear")
        os.system('aplay -q ./sounds/main.wav&')
        self.screen.reset_screen()
        self.screen.add_to_game_screen(self.my_arjun)
        self.screen.add_to_game_screen(self.my_brickbreaker)
        self.screen.add_to_game_screen(self.my_press)
        self.screen.print_game_screen()
        while True:
            self.screen.reset_screen()
            self.screen.add_to_game_screen(self.my_arjun)
            self.screen.add_to_game_screen(self.my_brickbreaker)
            self.screen.add_to_game_screen(self.my_press)
            self.screen.print_game_screen()

            c = input_to(self.getch)
            if (c == "q"):
                os.system("clear")
                quit()
            if (c == 'x'):
                break

            if (c == "i"):
                self.instructions()
                os.system("clear")

    def instructions(self):
        os.system("clear")
        text_string = f"Read README and PDFs for rules and instructions."
        body = np.array([list(text_string)])
        obj = Game_object(50, 20, body[0].size, 1, 0, 0, body,
                          np.full(body.shape, Fore.WHITE + Style.BRIGHT))
        self.screen.reset_screen()
        self.screen.add_to_game_screen(obj)
        self.screen.add_to_game_screen(self.my_continue)
        self.screen.print_game_screen()
        while True:
            c = input_to(self.getch)
            if (c == 'c'):
                break

    def pause_screen(self):
        os.system("clear")
        text_string = f"The game is paused."
        body = np.array([list(text_string)])
        obj = Game_object(65, 20, body[0].size, 1, 0, 0, body,
                          np.full(body.shape, Fore.WHITE + Style.BRIGHT))
        self.screen.reset_screen()
        self.screen.add_to_game_screen(obj)
        self.screen.add_to_game_screen(self.my_continue)
        self.screen.print_game_screen()
        start_time = datetime.now()
        while True:
            c = input_to(self.getch)
            if (c == 'c'):
                end_time = datetime.now()
                time_delta = end_time - start_time
                total_seconds = time_delta.total_seconds()
                self.pause_time += round(total_seconds) // 60
                break

    def time_elapsed(self):
        time_delta = datetime.now() - self.start_time
        total_seconds = time_delta.total_seconds()
        minutes = round(total_seconds) // 60
        return minutes - self.pause_time

    def small_reset(self):
        self.pass_through = 0
        self.grab_ball = 0
        self.fast_ball = 0
        self.balls = []
        self.paddle = Paddle(65, 29, 8, 0)
        self.powerups = []
        self.bullets = []
        self.ufo = UFO(65, 1, 8, 0)
        self.bombs = []
        self.balls.append(Ball(69, 28, -1, -1))
        self.screen.reset_screen()
        self.update_screen()
        self.screen.print_game_screen()
        self.check_powerup_times()
        self.print_meta()

    def __init__(self, screen):
        self.start_time = datetime.now()
        self.pass_through = 0
        self.grab_ball = 0
        self.fast_ball = 0
        self.score = 0
        self.lives = LIVES
        self.win = False
        self.pause_time = 0
        self.balls = []
        self.ufo = UFO(65, 1, 8, 0)
        self.bombs = []
        self.ufo_bricks = []
        self.ufo_count = 0
        self.paddle = Paddle(65, 29, 8, 0)
        self.bricks = []
        self.powerups = []
        self.bullets = []
        self.balls.append(Ball(69, 28, -1, -1))
        self.screen = screen
        self.screen.print_game_screen()
        self.check_powerup_times()
        self.print_meta()

    def user_input(self):
        c = input_to(self.getch, 0.1)
        if (c == "a"):
            self.paddle.move(self.paddle.get_x() - self.paddle.get_xv())
            if self.level == 3:
                self.ufo.move(self.paddle.get_x() - self.paddle.get_xv())
            for ball in self.balls:
                if not ball.should_move():
                    ball.move(ball.get_x() - self.paddle.get_xv(),
                              ball.get_y())
        if (c == "d"):
            self.paddle.move(self.paddle.get_x() + self.paddle.get_xv())
            if self.level == 3:
                self.ufo.move(self.paddle.get_x() + self.paddle.get_xv())
            for ball in self.balls:
                if not ball.should_move():
                    ball.move(ball.get_x() + self.paddle.get_xv(),
                              ball.get_y())
        if (c == "r"):
            for ball in self.balls:
                if not ball.should_move():
                    ball.flip_move()
        if (c == "p"):
            self.pause_screen()
        if (c == "q"):
            os.system("clear")
            quit()
        if (c == "l"):
            self.skip_level = True
        if (c == "s"):
            if (self.paddle.get_shoot_time() and self.paddle.last_shoot >= 8):
                self.paddle.last_shoot = 0
                self.bullets.append(
                    Bullet(self.paddle.get_x(),
                           self.paddle.get_y() - 1))

    def move_all(self):
        for brick in self.bricks:
            if isinstance(brick, rainbow_brick) and brick.is_active():
                brick.change_strength()

        self.paddle.last_shoot += 1
        self.last_move += 1
        if self.level == 3:
            self.ufo.last_shoot += 1
            if self.ufo.last_shoot >= 30:
                self.ufo.last_shoot = 0
                self.bombs.append(Bomb(self.ufo.get_x(), self.ufo.get_y() + 1))
            for bomb in self.bombs:
                if bomb.is_active():
                    bomb.move()
        for bullet in self.bullets:
            bullet.move()
            if (bullet.is_active()):
                for brick in self.bricks:
                    if brick.is_active() and bullet.did_collide(brick):
                        bullet.set_inactive()
                        if isinstance(brick, chain_brick):
                            os.system('aplay -q ./sounds/break.wav&')
                            curr = brick.hit(self.bricks)
                            if (curr == 0):
                                self.powerups.append(
                                    Power_up(
                                        brick.get_x(), brick.get_y(), 0, 1,
                                        self.power_up_type[np.random.choice(
                                            [0, 1, 2, 3, 4, 5, 6, 7])]))
                        else:
                            os.system('aplay -q ./sounds/break.wav&')
                            curr = brick.hit()
                            if (curr == 0):
                                self.powerups.append(
                                    Power_up(
                                        brick.get_x(), brick.get_y(), 0, 1,
                                        self.power_up_type[np.random.choice(
                                            [0, 1, 2, 3, 4, 5, 6, 7])]))
                        if not isinstance(brick, Unbreakable):
                            self.score += 1

        for powerup in self.powerups:
            if (powerup.is_active()):
                powerup.incr += 1
                if powerup.incr >= 5:
                    powerup.incr = 0
                    powerup.set_yv(powerup.get_yv() + 1)
                points = powerup.trajectory()
                for p in points:
                    flag = False
                    flag = powerup.move(p[0], p[1])
                    col = powerup.did_collide(self.paddle)
                    if (col[0]):
                        self.execute_powerup(col[1])
                        powerup.set_inactive()
                    if flag == True:
                        break
        if self.get_change_in_secs(
                self.level_start) >= MOVE_BRICK and self.last_move >= 30:
            self.last_move = 0
            for brick in self.bricks:
                if not self.over:
                    self.over = brick.move()
                else:
                    brick.move()
        for brick in self.bricks:
            if isinstance(brick, rainbow_brick):
                brick.change_strength()

    def execute_powerup(self, type):
        if np.array_equal(np.array([["P", "P"], ["P", "P"]]), type):
            self.pass_through = datetime.now()
        if np.array_equal(np.array([["E", "E"], ["E", "E"]]), type):
            self.paddle.make_enlarged()
        if np.array_equal(np.array([["S", "S"], ["S", "S"]]), type):
            self.paddle.make_shrink()
        if np.array_equal(np.array([["X", "X"], ["X", "X"]]), type):
            new_balls = []
            for ball in self.balls:
                new_ball = Ball(ball.x, ball.y, np.random.choice([1, -1]),
                                np.random.choice([1, -1]))
                new_ball.flip_move()
                new_balls.append(new_ball)
            self.balls.extend(new_balls)
        if np.array_equal(np.array([[">", ">"], [">", ">"]]), type):
            self.fast_ball = datetime.now()
            for ball in self.balls:
                new_xv = 0
                new_yv = 0
                if (ball.get_xv()):
                    new_xy = ball.get_xv() + 2 * abs(
                        ball.get_xv()) // ball.get_xv()
                if (ball.get_yv()):
                    new_yv = ball.get_yv() + 2 * abs(
                        ball.get_yv()) // ball.get_yv()
                ball.set_xv(new_xv)
                ball.set_yv(new_yv)
        if np.array_equal(np.array([["G", "G"], ["G", "G"]]), type):
            self.paddle.set_grab()
            self.grab_ball = datetime.now()
        if np.array_equal(np.array([["!", "!"], ["!", "!"]]), type):
            self.paddle.shoot_time = datetime.now()
        if np.array_equal(np.array([["F", "F"], ["F", "F"]]), type):
            self.fireball = True

    def collissions(self):
        if self.level == 3:
            for bomb in self.bombs:
                if bomb.is_active() and bomb.did_collide(self.paddle):
                    bomb.set_inactive()
                    self.lives -= 1
                    os.system('aplay -q ./sounds/lost.wav&')
            for brick in self.bricks:
                if brick.is_active() and not isinstance(brick, Unbreakable):
                    break
            else:
                if self.ufo_count < 3 and self.ufo.health <= 8:
                    self.ufo_count += 1
                    brick_pos = [
                        2, 10, 18, 26, 34, 42, 50, 58, 66, 74, 82, 90, 98, 106,
                        114, 122, 130, 138
                    ]

                    for x in brick_pos:
                        self.bricks.append(
                            Brick(x, 2, np.random.choice([1, 2, 3, 4, 5])))

        for ball in self.balls:
            if ball.is_active() and ball.should_move():

                points = ball.trajectory()
                for p in points:
                    flag = False
                    flag = ball.move(p[0], p[1])
                    if self.level == 3:
                        a = self.ufo.did_collide(ball)
                        if a != 0:
                            ball.set_xv(ball.get_xv() + a)
                            ball.set_yv(ball.get_yv() * -1)
                            self.ufo.hit()
                            os.system('aplay -q ./sounds/ufo.wav&')
                        if self.ufo.health == 0:
                            self.win = True
                    a = self.paddle.did_collide(ball)
                    if a != 0:
                        ball.set_xv(ball.get_xv() + a)
                        ball.set_yv(ball.get_yv() * -1)
                        flag = True
                        if self.paddle.get_grab():
                            ball.flip_move()
                        break

                    for brick in self.bricks:
                        if self.pass_through and brick.is_active(
                        ) and brick.pass_through_collide(ball):
                            brick.set_inactive()
                            if self.fireball == True:
                                for other_brick in self.bricks:
                                    if (other_brick.x == brick.x
                                            or other_brick.x == brick.x -
                                            brick.xlength or other_brick.x
                                            == brick.x + brick.xlength) and (
                                                other_brick.y == brick.y or
                                                other_brick.y == brick.y - 1 or
                                                other_brick.y == brick.y + 1):
                                        other_brick.set_inactive()
                                        self.score += 5
                                self.fireball = False
                            self.score += 5
                            flag = True
                        elif brick.is_active() and brick.did_collide(ball):
                            flag = True
                            if self.fireball == True:
                                for other_brick in self.bricks:
                                    if (other_brick.x == brick.x
                                            or other_brick.x == brick.x -
                                            brick.xlength or other_brick.x
                                            == brick.x + brick.xlength) and (
                                                other_brick.y == brick.y or
                                                other_brick.y == brick.y - 1 or
                                                other_brick.y == brick.y + 1):
                                        other_brick.set_inactive()
                                        self.score += 5
                                self.fireball = False
                            if isinstance(brick, chain_brick):
                                curr = brick.hit(self.bricks)
                                os.system('aplay -q ./sounds/break.wav&')
                                if (curr == 0):
                                    if self.level != 3:
                                        self.powerups.append(
                                            Power_up(
                                                brick.get_x(), brick.get_y(),
                                                ball.get_xv(), ball.get_yv(),
                                                self.power_up_type[
                                                    np.random.choice(
                                                        [0, 1, 2, 3, 4, 5,
                                                         6])]))
                            else:
                                curr = brick.hit()
                                os.system('aplay -q ./sounds/break.wav&')
                                if (curr == 0):
                                    if self.level != 3:
                                        self.powerups.append(
                                            Power_up(
                                                brick.get_x(), brick.get_y(),
                                                ball.get_xv(), ball.get_yv(),
                                                self.power_up_type[
                                                    np.random.choice(
                                                        [0, 1, 2, 3, 4, 5,
                                                         6])]))
                            if not isinstance(brick, Unbreakable):
                                self.score += 1
                    if (flag):
                        break

    def update_screen(self):
        self.screen.add_to_game_screen(self.paddle)
        if self.level == 3:
            self.screen.add_to_game_screen(self.ufo)
            for bomb in self.bombs:
                if bomb.is_active():
                    self.screen.add_to_game_screen(bomb)
        for powerup in self.powerups:
            if (powerup.is_active()):
                self.screen.add_to_game_screen(powerup)
        for bullet in self.bullets:
            if bullet.is_active():
                self.screen.add_to_game_screen(bullet)
        for brick in self.bricks:
            if (brick.is_active()):
                self.screen.add_to_game_screen(brick)
        for ball in self.balls:
            if (ball.is_active()):
                self.screen.add_to_game_screen(ball)

    def lost(self):
        score_string = f"SCORE: %d" % (self.score)
        body = np.array([list(score_string)])
        obj = Game_object(70, 20, body[0].size, 1, 0, 0, body,
                          np.full(body.shape, Fore.WHITE + Style.BRIGHT))
        self.reset()
        os.system("clear")
        self.screen.reset_screen()
        self.screen.add_to_game_screen(self.game_over)
        self.screen.add_to_game_screen(obj)
        self.screen.add_to_game_screen(self.my_continue)
        self.screen.print_game_screen()

        while True:
            c = input_to(self.getch)
            if (c == 'c'):
                break

    def winpage(self):
        os.system("clear")
        os.system('aplay -q ./sounds/win.wav&')
        self.win = False
        score_string = f"SCORE: %d" % (self.score)
        body = np.array([list(score_string)])
        obj = Game_object(70, 20, body[0].size, 1, 0, 0, body,
                          np.full(body.shape, Fore.WHITE + Style.BRIGHT))
        self.reset()
        os.system("clear")
        self.screen.reset_screen()
        self.screen.add_to_game_screen(self.my_win)
        self.screen.add_to_game_screen(obj)
        self.screen.add_to_game_screen(self.my_continue)
        self.screen.print_game_screen()
        while True:
            c = input_to(self.getch)
            if (c == 'c'):
                break

    def new_game(self):
        while True:
            self.main_screen()
            self.reset()
            os.system("clear")
            self.put_bricks()
            while self.level <= 3 and self.lives > 0:
                self.user_input()
                if self.skip_level == True and self.level == 3:
                    self.level = 1
                    self.skip_level = False
                    self.over = True
                    break
                self.move_all()
                if self.over == True:
                    break

                self.collissions()
                self.screen.reset_screen()
                self.update_screen()
                self.screen.print_game_screen()
                self.check_powerup_times()
                self.print_meta()
                for ball in self.balls:
                    if ball.is_active():
                        break
                else:
                    self.lives -= 1
                    os.system('aplay -q ./sounds/lost.wav&')
                    self.small_reset()
                if self.level == 3 and self.win:
                    break
                for brick in self.bricks:
                    if not isinstance(brick, Unbreakable):
                        if brick.is_active():
                            break
                else:

                    if self.level == 3:
                        if not self.win:
                            continue
                        else:
                            break
                    self.level += 1
                    self.level_start = datetime.now()
                    self.small_reset()
                    self.put_bricks()

                if self.skip_level == True:
                    self.skip_level = False
                    self.level += 1
                    self.level_start = datetime.now()
                    self.small_reset()
                    self.put_bricks()
                    if self.level == 4:
                        self.level = 1
                        break
            if self.win:
                self.winpage()
            elif self.lives == 0 or self.over:
                self.over = False
                os.system('aplay -q ./sounds/lost.wav&')
                self.lost()
示例#19
0
    def start(self):
        if config.HEIGHT < 38 or config.WIDTH < 168:
            print("Please play on full screen")
            quit()
        print("\033[?25l\033[2J", end='')
        self._screen = Screen()
        self._paddle = Paddle(
            np.array([config.HEIGHT - 3, config.WIDTH / 2 - 7]),
            np.array([1, 16]))
        self._ball = []
        self._ball.append(
            Ball(np.array([config.HEIGHT - 4, config.WIDTH / 2]),
                 np.array([-1, 0]), True))
        self._lives = 5
        self._balls = 1
        self._score = 0
        self._level = 1
        self._start_time = time.time()
        self._printscore = 0
        self._move = False
        self._laser = False
        self._lasertime = self._start_time
        self._ufo = None
        self._isUfo = False
        get = Get()
        self.bricks_pos_l2 = np.array([
            [18, 66, 2, 2, 0],
            [18, 75, 3, 1, 1],
            [18, 84, 1, 3, 2],
            [16, 70, 2, 4, 3],
            [16, 79, 2, 5, 4],
            [16, 88, 3, 6, 5],
            [16, 61, 3, 2, 6],
            [14, 75, -1, 0, 0],
            [14, 84, -1, 0, 0],
            [14, 66, -1, 0, 0],
            [14, 93, -1, 0, 0],
            [14, 57, -1, 0, 0],
            [14, 48, -1, 0, 0],
            [14, 102, -1, 0, 0],
            [12, 79, 1, 1, 7],
            [12, 70, 1, 3, 8],
            [12, 88, 0, 2, 9],
            [12, 61, 0, 6, 10],
            [10, 75, 1, 4, 11],
            [10, 66, 2, 5, 12],
            [10, 84, 3, 6, 13],
        ])
        self.bricks_pos_l1 = np.array([
            [8, 14, 0, 0, 0],
            [8, 23, 1, 1, 0],
            [8, 32, 0, 0, 0],
            [6, 23, 2, 4, 1],
            [4, 14, 0, 0, 0],
            [4, 23, 1, 2, 2],
            [4, 32, 0, 0, 0],
            [8, 127, 0, 0, 0],
            [8, 136, 1, 3, 3],
            [8, 145, 0, 0, 0],
            [6, 136, 2, 5, 4],
            [4, 127, 0, 0, 0],
            [4, 136, 1, 6, 5],
            [4, 145, 0, 0, 0],
            [14, 75, 4, 7, 6],
            [14, 84, 4, 8, 7],
            [12, 75, 4, 0, 0],
            [12, 84, 4, 0, 0],
            [10, 75, 4, 0, 0],
            [10, 84, 4, 0, 0],
        ])
        self.bricks_pos_l3 = np.array([[15, 5, 0, 0, 0], [15, 150, 0, 0, 0]])
        self.ufo_layer1 = np.array([[15, 5, 0, 0, 0], [15, 150, 0, 0, 0],
                                    [10, 3, 1, 0, 0], [10, 12, 2, 0, 0],
                                    [10, 21, 3, 0, 0], [10, 30, 2, 0, 0],
                                    [10, 39, 1, 0, 0], [10, 48, 2, 0, 0],
                                    [10, 57, 3, 0, 0], [10, 66, 2, 0, 0],
                                    [10, 75, 1, 0, 0], [10, 84, 2, 0, 0],
                                    [10, 93, 3, 0, 0], [10, 102, 2, 0, 0],
                                    [10, 111, 1, 0, 0], [10, 120, 2, 0, 0],
                                    [10, 129, 3, 0, 0], [10, 138, 2, 0, 0],
                                    [10, 147, 1, 0, 0], [10, 156, 2, 0, 0]])
        self.ufo_layer2 = np.array([[15, 5, 0, 0, 0], [15, 150, 0, 0, 0],
                                    [10, 3, 1, 0, 0], [10, 12, 2, 0, 0],
                                    [10, 21, 3, 0, 0], [10, 30, 2, 0, 0],
                                    [10, 39, 1, 0, 0], [10, 48, 2, 0, 0],
                                    [10, 57, 3, 0, 0], [10, 66, 2, 0, 0],
                                    [10, 75, 1, 0, 0], [10, 84, 2, 0, 0],
                                    [10, 93, 3, 0, 0], [10, 102, 2, 0, 0],
                                    [10, 111, 1, 0, 0], [10, 120, 2, 0, 0],
                                    [10, 129, 3, 0, 0], [10, 138, 2, 0, 0],
                                    [10, 147, 1, 0, 0], [10, 156, 2, 0, 0],
                                    [13, 3, 1, 0, 0], [13, 12, 2, 0, 0],
                                    [13, 21, 3, 0, 0], [13, 30, 2, 0, 0],
                                    [13, 39, 1, 0, 0], [13, 48, 2, 0, 0],
                                    [13, 57, 3, 0, 0], [13, 66, 2, 0, 0],
                                    [13, 75, 1, 0, 0], [13, 84, 2, 0, 0],
                                    [13, 93, 3, 0, 0], [13, 102, 2, 0, 0],
                                    [13, 111, 1, 0, 0], [13, 120, 2, 0, 0],
                                    [13, 129, 3, 0, 0], [13, 138, 2, 0, 0],
                                    [13, 147, 1, 0, 0], [13, 156, 2, 0, 0]])
        self.bricks_pos = self.bricks_pos_l1
        self.powerup = []
        self._len = self.bricks_pos.shape[0]
        self.createBricks()
        self.laserbeams = []
        self.lastlaser = self._start_time
        self.bombtime = self._start_time
        self._bombs = []
        self._spawn1 = False
        self._spawn2 = False

        self.lastMove = self._start_time
        while True:
            self._screen.clear()
            self._screen.drawBackGround()
            inchar = input_to(get.__call__)
            self.handleInput(inchar)
            self.createLaser()
            self.moveBalls()
            self._screen.drawObject(self._paddle)
            self.spawnBricks()
            self.drawBricks()
            self.handleCollisionBallPaddle()
            self.handleCollisionBallBrick()
            self.drawUfo()
            self.drawBalls()
            self._screen.printScreen()
            time_temp = int(time.time() - self._start_time)
            self._printscore = int(self._score +
                                   max(0, (1000 - time_temp) / 100))
            print("\r Lives ", self._lives, "   Score ", self._printscore,
                  "   Time ", time_temp, "   Level ", self._level, "    ")
            if (self._laser):
                print("Remaining Time ", -int(time.time() - self._lasertime))
            elif self._isUfo:
                print("Boss Strenth: ", end="")
                strength = self._ufo.getStrength()
                for i in range(0, strength):
                    print('o', end="")
                for i in range(strength, 20):
                    print(' ', end="")
                print()
            else:
                for i in range(0, 30):
                    print(' ', end="")
                print()
from screen import Screen
from player import Hero, Enemy
from obstacle import Firebeam, Coin, Magnet
from initialisations import initialiseFirebeams, initialiseCoins, initialiseMagnets
from input import Get, input_to

total_time = 100
refresh_time = 0.05
screen = Screen(1000)
mandalorian = Hero(screen, screen.getScreenwidth() / 4, screen.getScreenheight() - 1, refresh_time)
firebeams = initialiseFirebeams(screen)
coins = initialiseCoins(screen)
magnets = initialiseMagnets(screen)
boss = Enemy(screen, screen.getGamewidth() - 2, screen.getScreenheight() - 1)
bullets = []
get = Get()
input_taken = 0
start_time = time.time()
previous_time = start_time
while True:
	current_time = time.time()
	time_remaining = total_time - time.time() + start_time
	if time_remaining < 0:
		mandalorian.gameOver(mandalorian)
	if current_time - previous_time >= refresh_time:
		print( "\033[0;0H" )
		screen.printScreen(mandalorian, time_remaining)
		previous_time = time.time()
		input_taken = 0
	input = input_to(get, refresh_time)
	if input == None:
示例#21
0
    def move(self, chbuff, boardA, en=None, br=None):
        checker_l = self.col_check(boardA)
        if chbuff == 'd' and self._y < 500 - self._dim[1]:
            """Right"""
            if len(checker_l):
                for checker in checker_l:
                    if (checker[1] == self._y + self._dim[1]):
                        return

            self._y += 1
            for i in range(self._dim[0]):
                boardA.change(self._x + i, self._y - 1, '.')

            if (self._y >= boardA.start_getter() + 40 and self._y < 460
                    and self._typ != "Enemy"):
                boardA.start_setter(boardA.start_getter() + 1)

            self.render(boardA)

        elif chbuff == 'a' and self._y:
            """Left"""
            if len(checker_l):
                for checker in checker_l:
                    if (checker[1] == self._y - 1):
                        return

            if (self._y > 0):
                self._y -= 1

                for i in range(self._dim[0]):
                    boardA.change(self._x + i, self._y + self._dim[1], '.')

                if (self._y < boardA.start_getter() and self._typ != "Enemy"):
                    boardA.start_setter(boardA.start_getter() - 1)

                self.render(boardA)

            else:
                pass

        elif chbuff == 'w' and self._jump_flag == 0:
            """Jump up"""
            temp = self._x
            self._jump_flag = 1

            for checker in checker_l:
                if (checker[0] == self._x - 1):
                    self.render(boardA)
                    return

            while (self._x and self._x >= temp - self._jump_dist):

                if len(checker_l):
                    for checker in checker_l:
                        if (checker[0] == self._x - 1):
                            return
                self._x -= 1

                for wi in range(self._dim[1]):
                    boardA.change(self._x + self._dim[0], self._y + wi, '.')
                self.render(boardA)
                checker_l = self.col_check(boardA)

                getch = Get()
                chbuff = input_to(getch)

                if (chbuff):
                    self.move(chbuff, boardA)

                if (en):
                    for e in en:
                        e.graze(boardA)
                        e.render(boardA)

                self.render(boardA)
                os.system('clear')
                print(boardA.printBoard())
                print(boardA.count())
        self.render(boardA)
示例#22
0
    random_board_builder()
    print(Fore.BLUE)
    print("___  ___           _        ______             ")  
    print("|   /  |          (_)       | ___ |             ")
    print("| .  . | __ _ _ __ _  ___   | |_/ /_ __ ___ ___ ")
    print("| |VV| |/ _` | '__| |/ _ V  | ___ | '__/ _ V__|")
    print("| |  | | (_| | |  | | (_)|  |_/ / | |   (_)|__ -")
    print("|_|  |_/V__,_|_|  |_|V___/  V____/|_|  |___/|___/")
    print('\nDEVELOPER: VIJAYRAJ SHANMUGARAJ\n\n')
    print("Press any key to get started (D for developer mode/No enemies)")                                     
    print(Style.RESET_ALL)     

    mP.BigMario()                                 
    while(1):
        
        getstart = Get()
        chstart = input_to(getstart)
        
        if(chstart == 'D'):
            enList = []
            break

        if(chstart):
            break
    
    boss1 = Boss(13, 475, mP)
    while mP.getLive() and b1.count():
        getch = Get()
        chbuff = input_to(getch)

        for b in brickList:
示例#23
0
def main():

    music = subprocess.Popen(["aplay", "-q", "./main.wav"])
    level = gameMap()
    display = Board(32, 96, level.levelmap)
    mario = Mario(26, 10, display)
    enemy = []
    enemy.append(EnemyShroom(26, 30, display, level.levelmap, -1))
    enemy.append(EnemyShroom(26, 140, display, level.levelmap, -1))

    enemy.append(EnemyShroom(26, 300, display, level.levelmap, 1))
    enemy.append(EnemyShroom(26, 305, display, level.levelmap, -1))

    coins = []
    coins.append(Coin(17, 30, display))
    coins.append(Coin(17, 34, display))
    coins.append(Coin(17, 38, display))
    coins.append(Coin(17, 42, display))
    coins.append(Coin(17, 140, display))
    coins.append(Coin(17, 142, display))
    coins.append(Coin(17, 144, display))
    coins.append(Coin(17, 146, display))
    coins.append(Coin(14, 200, display))
    coins.append(Coin(17, 210, display))
    coins.append(Coin(17, 300, display))
    coins.append(Coin(17, 305, display))
    getch = Get()

    gameloop = True
    os.system('clear')
    print(display.getString())

    while gameloop == True:

        mario.death(coins, display, music)
        cam = mario.playercamera(display, level)
        if cam == 1:
            mario.score += 5
        if coins:
            for coin in coins:
                if (display.y + 95 > coin.y and coin.spawn == 0):
                    coin.y = coin.y - display.y
                    display.drawonBoard(coin, coin.x, coin.y)
                    coin.spawn = 1

                elif (coin.spawn == 1):
                    if cam == 1:
                        coin.y -= 1
                        display.drawonBoard(coin, coin.x, coin.y)

                    if (coin.y == 0):
                        coin.sprite = [[' ']]
                        display.drawonBoard(coin, coin.x, coin.y)
                        coins.remove(coin)
        if enemy:
            for monster in enemy:
                if (display.y + 95 > monster.y + monster.width
                        and monster.spawn == 0):
                    monster.y = monster.y - display.y
                    display.drawonBoard(monster, monster.x, monster.y)
                    monster.spawn = 1

                elif (monster.spawn == 1):
                    if cam == 1:
                        monster.y -= 1
                    monster.movement(display, level.levelmap, mario, coins,
                                     music)
                    if (monster.y == 0):
                        monster.life = 0
                        monster.death(display)
                        enemy.remove(monster)

        inp = input_to(getch)
        os.system('clear')

        if mario.gravityon == -1 or mario.gravityon == 1:
            fallstate, pos = mario.Descend(display, level.levelmap)

            if (fallstate == 1):
                mario.gravityon = 1

            elif (fallstate == 2):
                min = 0
                minval = pos + 10
                if enemy:
                    for monster in enemy:
                        if (monster.y + 1 < minval):
                            minval = monster.y + 1
                            min = monster
                    subprocess.Popen(["aplay", "-q", "./kill.wav"])
                    min.life -= 1
                    if (min.life <= 0):
                        min.death(display)
                        mario.score += 200
                        enemy.remove(min)
                        mario.gravityon = 0
                        mario.jump_height = 7

            elif (fallstate == 5):
                if coins:
                    for coin in coins:
                        if (coin.y == pos):
                            subprocess.Popen(["aplay", "-q", "./coin.wav"])
                            mario.score += 100
                            coin.sprite = [[' ']]
                            display.drawonBoard(coin, coin.x, coin.y)
                            coins.remove(coin)
            elif (fallstate == 4):
                music.kill()
                subprocess.Popen(["aplay", "-q", "./win.wav"])
                mario.score += 2000
                print("Stage Clear!")
                print("Score: " + str(mario.score))
                sys.exit()

        elif mario.gravityon == 0:
            if mario.jump_height < 12:
                mario.jump_height += 1
                fallstate, pos = mario.Ascend(display, level.levelmap)
                if (fallstate == 1):
                    mario.gravityon = -1
                elif (fallstate == 5):
                    if coins:
                        for coin in coins:
                            if coin.y == pos:
                                subprocess.Popen(["aplay", "-q", "./coin.wav"])
                                mario.score += 100
                                coin.sprite = [[' ']]
                                display.drawonBoard(coin, coin.x, coin.y)
                                coins.remove(coin)

            if mario.jump_height == 12:
                mario.jump_height = 0
                mario.gravityon = -1

        print(Fore.GREEN + Style.BRIGHT + display.getString())
        print("Score: " + str(mario.score))
        if inp == 'q':
            os.system('clear')
            music.kill()
            sys.exit()

        if inp is not None:
            mario.movement(inp, display, level.levelmap, coins, music)