Example #1
0
 def handle_event(self, event):
     if event.type == pygame.QUIT:
         self._running = False
     if event.type == pygame.MOUSEBUTTONDOWN:
         ball = Ball(self.screen.get_width()/2,self.screen.get_height()/2,20,20,self)
         ball.setSpeed(random.random()*14-7, random.random()*14-7)
         self.balls.append(ball)
Example #2
0
class Game():
	def __init__(self):
		self.window = curses.initscr()
		self.window.nodelay(True)
		self.window.keypad(True)
		curses.cbreak()

		SCRH, SCRW = self.window.getmaxyx()

		self.ball = Ball(2, 2)
		self.paddle1 = Paddle(0, 0, 5, [curses.KEY_LEFT, curses.KEY_RIGHT])
		self.paddle2 = Paddle(0, SCRH - 1, 5, [97, 100])

		self.scorex = 0
		self.scorey = 0
		self.score = Label(1, 1, "Score: 0:0")

	def loop(self):
		while True:
			key = self.window.getch()

			self.ball.update(self.window, [self.paddle1, self.paddle2])
			self.paddle1.update(self.window, key)
			self.paddle2.update(self.window, key)

			self.window.clear()
			draworder = sorted([self.ball, self.paddle1, self.paddle2, self.score], key=lambda o: o.x)
			for o in draworder:
				o.draw(self.window)
			self.window.refresh()

			curses.flushinp()

			curses.napms(1000 / TICKRATE)
Example #3
0
 def add_ball(self, release_instantly=False):
     ball = Ball(self.ball_image, (230+82, 625), Vector(-3,-5), self.is_time_distortion_field_active, attached=True, attach_pos=self.balls_on_paddle)
     self.balls.add(ball)
     self.balls_on_paddle += 1
     if release_instantly:
         ball.update(1, self.paddle, self.balls, self.blocks, self.invulnerable_blocks)
         self.release_a_ball()
Example #4
0
    def __init__(self, stage, pos_x, pos_y, circle_mass, radius, circle_elasticity, color):
        Ball.__init__(self, stage, pos_x, pos_y, circle_mass, radius, circle_elasticity, color)
        self.circle.collision_type = 1
        self.point_value = 0

        self.gun_bullet = pygame.image.load(self.stage.graphics_path + "gunbullet.png").convert_alpha()
        self.cannon_bullet = pygame.image.load(self.stage.graphics_path + "cannonbullet.png").convert_alpha()        
Example #5
0
class Game:
  '''
  Main game class
  '''
  
  def __init__ (self):
    pygame.init()
    pygame.key.set_repeat(10,10)
    res = ConfigManager.get("resolution")
    self.screen = pygame.display.set_mode(res, pygame.DOUBLEBUF)
    self.ball = Ball()
    self.space = Space(res)
  
  def catchUserInput(self):
    for e in pygame.event.get():
      if e.type == pygame.QUIT:
        pygame.quit()
        exit()
      elif e.type == pygame.KEYDOWN:
        if e.key == pygame.K_ESCAPE:
          pygame.quit()
          exit()
        elif e.key == pygame.K_DOWN:
          self.ball.decreaseSpeed()
        elif e.key == pygame.K_UP:
          self.ball.increaseSpeed()
        elif e.key == pygame.K_LEFT:
          self.ball.moveLeft()
        elif e.key == pygame.K_RIGHT:
          self.ball.moveRight()
          
  def updateGameState(self):
    self.ball.updateState() 
  
  def updateDisplay(self):
    self.screen.fill(BLACK)
    self.screen.blit(self.space, self.space.rect)
    self.screen.blit(self.ball.image, self.ball.rect)
    if __debug__:
      #print "Debug mode: Draw sprite's rects"
      pygame.draw.rect(self.screen, WHITE, self.ball.rect, 1)
      #print "Debug mode: Draw statistics"
      font = pygame.font.Font(None, 24)
      speedMsg = "Spaceship speed: " + str(self.ball.speed)
      posMsg = "Spaceship position: " + str(self.ball.rect)
      textS = font.render(speedMsg, 1, GREEN)
      textP = font.render(posMsg, 1, GREEN)
      self.screen.blit(textS, (10,10))
      self.screen.blit(textP, (10,25))
      
    pygame.display.flip()
    pygame.time.wait(1000 / 60)

  def run(self):
    while True:
      self.catchUserInput()
      self.updateGameState()
      self.updateDisplay()
Example #6
0
def checkball(img_list):
    """
        检测有没有球,若有返回 True
    """
    ball_checker = Ball(img_list)
    if ball_checker.getR() != 0:
        return True
    else:
        return False
Example #7
0
def main():
    """ Main function for the game. """
    pygame.init()

    # Set the width and height of the screen [width,height]
    size = [800, 600]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("CMSC 150 is cool")

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()


    theBall = Ball()
    theBall.x = 100
    theBall.y = 100
    theBall.change_x = 2
    theBall.change_y = 1
    theBall.color = [255,0,0]

    # -------- Main Program Loop -----------
    while not done:
        # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
        # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT

        # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT

        # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

        # First, clear the screen to white. Don't put other drawing commands
        # above this, or they will be erased with this command.

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        screen.fill(BLACK)
        theBall.move()
        theBall.draw(screen)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

        # Limit to 60 frames per second
        clock.tick(60)

    # Close the window and quit.
    # If you forget this line, the program will 'hang'
    # on exit if running from IDLE.
    pygame.quit()
Example #8
0
 def new_random_ball(self, canvas=None):
     while True:
         i1 = randint(0, CELLS - 1)
         j1 = randint(0, CELLS - 1)
         if not self.find(i1, j1):
             break
     new_ball = Ball(i1, j1, choice(colors))
     self.data.append(new_ball)
     if canvas:
         new_ball.draw(canvas)
Example #9
0
 def __init__(self, x = 0.0, y = 0.0):
     Ball.__init__(self, x, y)
     if Bar.image is None:
         # This is the first time loading the sprite,
         # so we need to load the image data
         Bar.image = pg.image.load(os.path.join("data","bar.png")).convert()
         Bar.image.set_colorkey(0)
     self.image = Bar.image
     (self.rect.w, self.rect.h) = (self.image.get_rect().w, self.image.get_rect().h)
     self.infiniteMass = True
     self.moveable = False
Example #10
0
class PongPlayers(NetworkSingletonActor):    
 
  def birth(self):
    self.players = []
    self.ball_location = -1
    self.ball = Ball()
    PictureInPictureManager().setball(self.ball)
    
  def add(self, player):
    self.players.append(player)
    if self.ball_location == -1:
      self.ball_location = 0
      player.incoming(self.ball) 
    self.playerchange()
      
  def leaving(self):
    if len(self.players) == 0:
      self.ball_location = -1
      self.ball.park_at(here())
      return
    self.ball_location = (self.ball_location + 1) % len(self.players)
    self.players[self.ball_location].incoming(self.ball)
    
  def current_player(self):
   if self.ball_location >= 0 and self.ball_location < len(self.players):
     return self.players[self.ball_location]
   return None
  
  def remove(self, actor):
    ball_on_dying_theatre = False
    if actor in self.players:
      if self.ball_location >= 0 and self.ball_location < len(self.players):
        ball_on_dying_theatre = self.players[self.ball_location] == actor
      self.players.remove(actor)
    if ball_on_dying_theatre:
      self.leaving()
    self.playerchange()
    
  def getall(self):
    return self.players
    
  def tellall(self, theatres):
    for player in self.players:
      player.availabletheatres(theatres)

  def actorlost(self, actor, message):
    self.remove(actor)
  
  def playerchange(self):
    PictureInPictureManager().players_are(self.players)
  
  def theatreclosing(self):
    migrate_or_die()
Example #11
0
def create_balls():
    magic_ball = Ball(BALL_POS, 50)
    magic_ball.speed = BALL_SPEED * random_vector()

    result = [magic_ball]
    for x in (-1, 0, 1):
        for y in (-1, 0, 1):
            if x == 0 and y == 0:
                continue
            result.append(Ball(BALL_POS + Vec2d(150 * x, 150 * y), random.randint(10, 40)))

    return result
Example #12
0
 def __init__(self, screen):
     self.balls = ScatteringsHandler()
     ball = Ball(50, screen.get_height()/2)
     ball.velocity = Vector(3.0, -1.0)
     self.balls.add(ball)
     bar = Bar(screen.get_width()/2, screen.get_height()/2)
     self.balls.add(bar)
     self.blobble1 = Blobble(screen.get_width()/2, screen.get_height()/2)
     self.balls.add(self.blobble1)
     self.screen = screen
     self.background = screen.copy()
     self.background.fill((0,0,0))
     self.lastTicks = pg.time.get_ticks()
Example #13
0
 def checkball(self, img_list):
     """
         检测有没有球,若有返回 True
     """
     # print 'len: ', len(img_list)
     # print 'len: ', len(img_list[0])
     # print type(img_list[0])
     # print img_list[0]
     ball_checker = Ball(img_list)
     if ball_checker.getR() != 0:
         return True
     else:
         return False
Example #14
0
def main():
    # Initialisation
    pygame.init()
    fps_clock = pygame.time.Clock()

    width, height = size = 700, 700
    black = 0, 0, 0
    screen = pygame.display.set_mode(size)

    ball = Ball()

    boxes = []
    rows = 5
    row = 0
    columns = 17
    column = 0
    while row < rows:
        row = row + 1
        while column < columns:
            column = column + 1
            boxes.append(Box(column,row))
        column = 0

    # Game Loop Start
    while 1:

        #Events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        #Logic
        ball.move()
        broken_box = ball.check_collision(size, boxes)
        if broken_box is not None:
            i = 0
            new_boxes = []
            for each in boxes:
                if broken_box != i:
                    new_boxes.append(each)
                i = i + 1
            boxes = new_boxes

        #Render
        for each in boxes:
            screen.blit(each.image, each.rect)
        screen.blit(ball.image, ball.rect)

        pygame.display.flip()
        screen.fill(black)
        fps_clock.tick(60)
Example #15
0
class Game(BaseLoop):
    def __init__(self, screen: pygame.Surface):
        super(Game, self).__init__(screen)
        self.FPSCLOCK = None
        self.racket_p1 = Racket(self.screen)
        self.racket_p2 = None
        self.ball = Ball(self.screen)

    def setup(self):
        super(Game, self).setup()
        pygame.key.set_repeat(100, 20)
        self.FPSCLOCK = pygame.time.Clock()
        self.racket_p1 = Racket(self.screen)
        self.ball = Ball(self.screen)
        self.racket_p2 = Racket(self.screen, mode='auto')

    def update_screen(self):
        super(Game, self).update_screen()
        pygame.draw.rect(self.screen, WHITE, ((self.screen.get_width() // 2) - 1, 0, 2,
                                              self.screen.get_height()))
        self.racket_p1.render()
        self.racket_p2.render()
        self.ball.render()

    def process_event(self, event: pygame.event):
        if event.type == KEYDOWN:
            if event.key == CONTROLS[UP]:
                self.racket_p1.move(UP)
            elif event.key == CONTROLS[DOWN]:
                self.racket_p1.move(DOWN)

        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
            self.LOOP_RUN = False
            print('Ending the game...')

    def start(self, game_type="one_player"):
        print('Starting the game...')
        self.game_type = game_type
        super(Game, self).start()

        while self.LOOP_RUN:
            for event in pygame.event.get():
                self.process_event(event)

            self.update_screen()
            self.ball.move(self.racket_p1, self.racket_p2)
            self.racket_p2.auto_move(self.ball)
            pygame.display.flip()
            self.FPSCLOCK.tick(FPS)
Example #16
0
 def __init__(self, x = 0.0, y = 0.0):
     Ball.__init__(self)
     if Blobble.image is None:
         # This is the first time loading the sprite,
         # so we need to load the image data
         Blobble.image = pg.image.load(os.path.join("data","blobble.png")).convert()
         Blobble.image.set_colorkey(0)
     self.image = Blobble.image
     self.rect = self.image.get_rect()
     #self.radius = self.rect.w / 2.0
     self._setPosition(Vector(x, y))
     self.infiniteMass = False
     self.moveable = True
     self.xAccel = 0.0
     self.doJump = False
Example #17
0
 def setup(self):
     super(Game, self).setup()
     pygame.key.set_repeat(100, 20)
     self.FPSCLOCK = pygame.time.Clock()
     self.racket_p1 = Racket(self.screen)
     self.ball = Ball(self.screen)
     self.racket_p2 = Racket(self.screen, mode='auto')
Example #18
0
	def __init__(self):
		super(GameLayer, self).__init__(randint(0, 255), randint(0, 255), randint(0, 255), 255)
		# 添加一个 板子
		self.paddle = Paddle('images/ban.png')
		self.add(self.paddle.sprite)
		self.ball = Ball('images/qiu.png')
		self.add(self.ball.sprite)
		self.level = 0
		# 添加一个 label 显示当前的游戏状态
		self.hud = Label('Score: 0',
						 color=(randint(0, 255), randint(0, 255), randint(0, 255), 255))
		self.hud.position = (0, 450)
		self.add(self.hud)
		self.hud2 = Label('Level: 1',
						  color=(randint(0, 255), randint(0, 255), randint(0, 255), 255))
		self.hud2.position = (100, 450)
		self.add(self.hud2)
		# 添加一个变量来记录金币
		self.score = 0
		# 设置 4 个按键状态
		self.key_pressed_left = False
		self.key_pressed_right = False
		self.key_pressed_up = False
		self.key_pressed_down = False

		self.blocks = []
		# 调用 reset 函数初始化状态
		self.gamestart()
		# 定期调用 self.update 函数
		# FPS frame per second 每秒帧数
		self.schedule(self.update)
Example #19
0
 def load_sprites(self):
     self.score = pyglet.text.Label('', font_size=15, x=settings.WINDOW_WIDTH/2, y=settings.WINDOW_HEIGHT - 15, anchor_x='center', anchor_y='center')
     self.racket_left = Racket(pyglet.resource.image(settings.RACKET_IMG)).center_anchor_y(settings.WINDOW_HEIGHT)
     self.racket_right = Racket(pyglet.resource.image(settings.RACKET_IMG)).center_anchor_y(settings.WINDOW_HEIGHT)
     self.ball = Ball(pyglet.resource.image(settings.BALL_IMG)).center_anchor_y(settings.WINDOW_HEIGHT).center_anchor_x(settings.WINDOW_WIDTH)
     self.racket_right.x = settings.WINDOW_WIDTH - self.racket_right.width
     self.racket_me = self.racket_left
    def __init__(self):
        super(GameLayer, self).__init__(246, 226, 76, 255)
        # 添加一个 板子
        self.paddle = Paddle('images/ban.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/qiu.png')
        self.add(self.ball.sprite)

        # 添加一个 label 显示当前的游戏状态
        self.hud = Label('金币: 0',
                         color=(0, 0, 0, 255))
        self.hud.position = (0, 450)
        self.add(self.hud)
        # 添加一个变量来记录金币
        self.gold = 0
        # 设置 4 个按键状态
        self.key_pressed_left   = False
        self.key_pressed_right  = False
        self.key_pressed_up     = False
        self.key_pressed_down   = False

        self.blocks = []
        # 调用 reset 函数初始化状态
        self.reset()
        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)
Example #21
0
    def on_init(self):
        Engine.on_init(self)

        self.winner_text = Text(self.width/4, 80, str(""), 30)
        self.add(self.winner_text)
        self.start_game_text = Text(self.width/3, 120, str("Press START"), 30)
        self.add(self.start_game_text)

        self.scoreP1_text = Text(self.width/4, 30, str(self.scoreP1), 50)
        self.scoreP2_text = Text(self.width - self.width/4, 30, str(self.scoreP2), 50)
        self.add(self.scoreP1_text)
        self.add(self.scoreP2_text)

        self.fps_text = Text(280, 220, "30")
        self.add(self.fps_text)
        self.ball = Ball(self.width/2, self.height/2, "ball.png")
        self.add(self.ball)
        self.playerOne = Paddle(20, self.height/2, "paddle.png")
        self.add(self.playerOne)
        self.playerTwo = Paddle(320 - 20, self.height/2, "paddle.png")
        self.add(self.playerTwo)

        self.sfx_padOne = soundEffect("blip1.wav")
        self.sfx_padTwo = soundEffect("blip2.wav")
        self.music_bg = musicPlayer("UGH1.wav", -1)
        self.music_bg.play()

        self.start_game(False)
Example #22
0
File: pong.py Project: piotut/Pong
    def __init__(self, file1=None, file2=None):
        pygame.mixer.pre_init(44100, -16, 2, 2048)
        pygame.init()
        self.fps = pygame.time.Clock()
        flag = DOUBLEBUF

        self.board = pygame.display.set_mode(screenRect, flag)
        pygame.display.set_caption('[ --- Pong --- ]')

        self.state = 1  # 1 - run, 0 - exit

        self.track = Tracking(file1, file2)

        self.sound = Sound()
        self.p1 = Paddle(self.board, (200,100,100),screenRect)
        self.p1.setInitialPostition(0,screenHeight/2)
        self.p2 = Paddle(self.board, (100,200,100),screenRect)
        self.p2.setInitialPostition(screenWidth-self.p2.get()['width'],screenHeight/2)
        self.ball = Ball(self.board, (50,50,250), screenRect, self.sound)
        self.ball.setInitialPostition(screenWidth/2,screenHeight/2)
        self.arena = Arena(self.board, screenRect)
        self.referee = Referee(self.ball, self.p1, self.p2, screenRect, self.sound)

        

        self.t = Thread(target=self.track.run)
        #self.track.run()
        self.t.start()

        self.p1_pos = 0
        self.p2_pos = 0

        self.loop()
Example #23
0
 def __init__ (self):
   pygame.init()
   pygame.key.set_repeat(10,10)
   res = ConfigManager.get("resolution")
   self.screen = pygame.display.set_mode(res, pygame.DOUBLEBUF)
   self.ball = Ball()
   self.space = Space(res)
Example #24
0
File: game.py Project: mshi/bricks
    def __init__(self):
        # initialize pygame stuff
        pygame.init()
        pygame.mixer.init()
        self.sound_player_collide = pygame.mixer.Sound(SOUND_PLAYER_COLLIDE)
        self.sound_brick_collide = pygame.mixer.Sound(SOUND_BRICK_COLLIDE)
        self.sound_start = pygame.mixer.Sound(SOUND_GAME_START)
        self.sound_gameover = pygame.mixer.Sound(SOUND_GAME_OVER)
        self.sound_win = pygame.mixer.Sound(SOUND_WIN)

        self.display = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        pygame.display.set_caption(NAME + " v" + VERSION)

        self.clock = pygame.time.Clock()

        # initialize objects
        self.player = Player(SCREEN_WIDTH/2)
        self.ball = Ball(self.player.posX(), self.player.posY())

        self.grid = [[None for i in xrange(GRID_WIDTH)] for j in xrange(GRID_HEIGHT)]
        self.running = False
        self.state = STATES["IDLE"]
        self.points = 0
        self.background = pygame.image.load(IMAGE_BACKGROUND).convert_alpha()
        self.font = pygame.font.Font(None, 36)
        self.smallFont = pygame.font.Font(None, 16)
        self.largeFont = pygame.font.Font(None, 64)
        self.mouseMode = False
Example #25
0
 def __init__(self, screen, draw_offset, control_set, player_color, finish_game):
     """
     Init with... way too many parameters
     :param screen: Main PyGame surface to draw the objects/UI on
     :param draw_offset: Drawing offset used in multiplayer
     :param control_set: Key-set used to control the Paddle
     :param player_color: Color of the player's Paddle
     :param finish_game: Function passed to the constructor, triggered on
     the game end
     :return:
     """
     self.screen = screen
     self.draw_offset = draw_offset
     self.control_set = control_set
     self.prev_input_x = 0
     self.level_number = 1
     self.block_count = 0
     self.player = Player("Derp")
     self.paddle = Paddle(LEVEL_WIDTH/2 - Paddle.WIDTH/2, LEVEL_HEIGHT - 40,
                          player_color, parent=self, owner=self.player)
     self.ball = Ball(self.paddle.rect.x + Paddle.WIDTH/2 - Ball.RADIUS,
                      self.paddle.rect.y - Ball.RADIUS * 2)
     self.items = None
     self.blocks = []
     self.blocks_surface = None
     self.blocks_surface_dirty = True
     self.entities = []
     self.font = Assets.font
     self.score_label = None
     self.lives_label = None
     self.level_label = None
     self.load_level(self.level_number)
     self.finish_game = finish_game
	def __init__(self):
		super(GameLayer, self).__init__()
		# 添加一个 板子
		self.paddle = Paddle('images/ash.png')
		self.add(self.paddle.sprite)
		self.ball = Ball('images/pokem.png')
		self.add(self.ball.sprite)

		# 添加一个 label 显示当前的游戏状态
		self.hud = Label('皮卡丘: 0')
		self.hud.position = (0, 450)
		self.add(self.hud)
		# 添加一个 label 显示当前游戏关卡
		self.level = Label('Level 1')
		self.level.position = (100, 450)
		self.add(self.level)
		# 添加一个变量来记录金币
		self.gold = 0
		# 设置 4 个按键状态
		self.key_pressed_left = False
		self.key_pressed_right = False
		self.key_pressed_up = False
		self.key_pressed_down = False

		self.blocks = []
		# 调用 reset 函数初始化状态
		self.reset()
		# 定期调用 self.update 函数
		# FPS frame per second 每秒帧数
		self.schedule(self.update)
Example #27
0
def main():
    pygame.init()

    FPS = 30
    FPS_CLOCK = pygame.time.Clock()

    # COLOR LIST
    WHITE = pygame.Color(255, 255, 255)

    # Code to create the initial window
    window_size = (500, 500)
    SCREEN = pygame.display.set_mode(window_size)

    # set the title of the window
    pygame.display.set_caption("Bouncing Ball Animation")

    # change the initial background color to white
    SCREEN.fill(WHITE)

    b1 = Ball(0, 0, 4, 5)

    b1.draw(SCREEN)

    while True:  # <--- main game loop
        for event in pygame.event.get():
            if event.type == QUIT:  # QUIT event to exit the game
                pygame.quit()
                sys.exit()

        SCREEN.fill(WHITE)
        b1.move(SCREEN)
        b1.draw(SCREEN)

        pygame.display.update()  # Update the display when all events have been processed
        FPS_CLOCK.tick(FPS)
Example #28
0
 def end(self, ball):
     if not g.SERVER:
         return
     b = Ball(Vector2(ball.position.x, ball.position.y))
     ball.position.y += 5
     # ball.netinfo["teleporting"] = True
     self.game.scene.add(b)
     t = min(ball.superIndex, len(ball.super))
     b.super = []  # ball.super[t:]
     b.velocity = ball.velocity.clone() + Vector2(0, 0)
     b.thrower = ball.thrower
     b.throwTeam = ball.throwTeam
     ball.velocity += Vector2(0, 0)
     b.zVelocity = 10  # ball.zVelocity
     b.z = ball.z
     b.throw()
     self.game.net.spawn(b, "ball")
Example #29
0
    def __init__(self, window, path="."):

        self.window = window
        self.h, self.w = window.getmaxyx()

        self.cells_x = self.w // Block.WIDTH
        self.cells_y = self.h // Block.HEIGHT
        self.field = [[None] * self.cells_x  for i in range(self.cells_y)]

        self._gen_blocks(path)
        self.ball = Ball(self.h-2, self.w//2)

        self.paddle = Paddle(self.h-1, self.w//2)
Example #30
0
	def __init__(self):
		self.window = curses.initscr()
		self.window.nodelay(True)
		self.window.keypad(True)
		curses.cbreak()

		SCRH, SCRW = self.window.getmaxyx()

		self.ball = Ball(2, 2)
		self.paddle1 = Paddle(0, 0, 5, [curses.KEY_LEFT, curses.KEY_RIGHT])
		self.paddle2 = Paddle(0, SCRH - 1, 5, [97, 100])

		self.scorex = 0
		self.scorey = 0
		self.score = Label(1, 1, "Score: 0:0")
Example #31
0
class Game:
    def __init__(self):
        self.player = Player(PLAYER_X, PLAYER_Y, PLAYER_WIDTH, PLAYER_HEIGHT, RED)
        self.ball = Ball(PLAYER_X, PLAYER_Y - 20, BALL_DIM, BALL_DIM, WHITE)
        self.enemies = [] 
        for y in range(4, 4 + E_ROWS):
            for x in range(SCREEN_WIDTH // E_WIDTH):
                tmp = Enemy(x*E_WIDTH, y*E_HEIGHT, E_WIDTH, E_HEIGHT, (y%250 + 50, x%250 + 50, (y*x)%250 + 50))
                self.enemies.append(tmp)

        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.ball_move_x = 3
        self.ball_move_y = 3
        self.move_right = False
        self.move_left = False
        self.running = True

    def get_random_color(self):
        return (random.randrange(10,256),
                random.randrange(10,256),
                random.randrange(10,256))

    def draw_player(self):
        pygame.draw.rect(self.screen, self.player.color, self.player.rect)

    def draw_ball(self):
        pygame.draw.rect(self.screen, self.ball.color, self.ball.rect)
    def draw_enemies(self):
        for e in self.enemies:
            pygame.draw.rect(self.screen, e.color, e.rect)

    def move_r(self):
        self.player.move(3)

    def move_l(self):
        self.player.move(-3)

    def move_ai(self):
        if self.ball.x > self.player.x + PLAYER_WIDTH // 2:
            self.move_r()
        else:
            self.move_l()
    def move_ball(self):
        self.ball.move(self.ball_move_x, self.ball_move_y)

    def test_collision(self):
        for e in self.enemies:
            if self.ball.rect.colliderect(e.rect):
                self.ball_move_y *= -1
                self.enemies.remove(e)

        if self.player.rect.colliderect(self.ball.rect):
            #if self.ball.x < self.player.x + PLAYER_WIDTH//2 and self.ball_move_x > 1:
                #self.ball_move_x *= -1
            #if self.ball.x > self.player.x + PLAYER_WIDTH//2 and self.ball_move_x < 0:
                #self.ball_move_x *= -1
            self.ball_move_y *= -1
        if self.ball.x <= 0:
            self.ball_move_x *= -1
        if self.ball.x >= SCREEN_WIDTH-BALL_DIM:
            self.ball_move_x *= -1
        if self.ball.y <= 0:
            self.ball_move_y *= -1
        if self.ball.y > SCREEN_HEIGHT:
            self.running = False

    def play(self):
        os.environ["SDL_VIDEO_CENTERED"] = "1"
        pygame.init()
        # Set up the display
        pygame.display.set_caption("FLAPPY-BIRD")

        clock = pygame.time.Clock()

        while self.running:
    
            if self.move_left:
                if self.player.x > 0:
                    self.move_l()
            elif self.move_right:
                if self.player.x < SCREEN_WIDTH-PLAYER_WIDTH:
                    self.move_r()

            self.screen.fill(BLACK)
            self.draw_player()
            self.draw_ball()
            self.draw_enemies()
            self.move_ball()
            self.test_collision()
            self.move_ai()
            pygame.display.flip()
            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    self.running = False
                if e.type == pygame.KEYDOWN:
                    if e.key == pygame.K_ESCAPE:
                        self.running = False
                    if e.key == pygame.K_LEFT:
                        self.move_left = True
                        self.move_right = False
                    if e.key == pygame.K_RIGHT:
                        self.move_right = True
                        self.move_left = False
                if e.type == pygame.KEYUP:
                    if e.key == pygame.K_LEFT:
                        self.move_right = False
                        self.move_left = False
                    if e.key == pygame.K_RIGHT:
                        self.move_right = False
                        self.move_left = False
Example #32
0
import time
import random
from ball import Ball
turtle.tracer(1,0)
turtle.hideturtle()



RUNNING=True
SLEEP=0.0077
SCREEN_WIDTH=turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT=turtle.getcanvas().winfo_height()/2



MY_BALL= Ball(12,12,10,15,23,"blue")

NUMBER_OF_BALLS=5
MINIMUM_BALL_RADIUS=10
MAXIMUM_BALL_RADIUS=100
MINIMUM_BALL_DX=-5
MAXIMUM_BALL_DX=5
MINIMUM_BALL_DY=-5
MAXIMUM_BALL_DY=5

BALLS=[]

for i in range(NUMBER_OF_BALLS):
	x=(-SCREEN_WIDTH+MAXIMUM_BALL_RADIUS,SCREEN_WIDTH-MAXIMUM_BALL_RADIUS)
	Y=(-SCREEN_HEIGHT+MAXIMUM_BALL_RADIUS,SCREEN_HEIGHT-MAXIMUM_BALL_RADIUS)
	dx=(MINIMUM_BALL_DX,MAXIMUM_BALL_DX)
Example #33
0
tim.color("white")
tim.pensize(3)
tim.hideturtle()
tim.penup()
tim.setposition(0, -300)
tim.left(90)
tim.pendown()
for _ in range(-300, 300, 10):
    tim.color("white")
    tim.forward(10)
    tim.color("black")
    tim.forward(10)

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
score = Scoreboard()

screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")

interval = 0.1
is_on = True
while is_on:
    time.sleep(interval)
    screen.update()
    ball.move()
Example #34
0
from turtle import Screen, Turtle
from paddle import Paddle
from ball import Ball
#  to slow ball down import time to pause
import time
# Create the screen
screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong")
screen.tracer(0)
# create r and l paddle from the turtle class, pass in tuple for location
r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
# create ball
ball = Ball()

screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")

game_is_on = True
while game_is_on:
    time.sleep(0.2)
    screen.update()
    ball.move()
    # if the ball reaches y value of 300or -300 change
    if ball.ycor() > 280 or ball.ycor() < -280:
        ball.bounce()
Example #35
0
from paddle import Paddle
from ball import Ball
from score import Scoreboard
import time

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("#8c0000")
screen.title("Carey's Pong Game")
screen.tracer(0)

#paddles
paddle_b = Paddle((350, 0))
paddle_a = Paddle((-350, 0))

ball = Ball()

#scoring
score = Scoreboard()

#move paddles
screen.listen()
screen.onkey(paddle_b.go_up, "Up")
screen.onkey(paddle_b.go_down, "Down")
screen.onkey(paddle_a.go_up, "w")
screen.onkey(paddle_a.go_down, "s")

game_on = True
while game_on:

    time.sleep(ball.move_speed)
Example #36
0
class Match(object):
    def get_state(self):
        return {
            "red_team": self.red_team,
            "blue_team": self.blue_team,
            "ball": self.ball,
        }

    def set_state(self, state):
        self.red_team = state["red_team"]
        self.blue_team = state["blue_team"]
        self.ball = state["ball"]

    def reset(self):
        print "RESET"
        self.red_team = [
            Player(-0.8, 0),
            Player(-0.2, 0),
            Player(random.uniform(-1, 0), random.uniform(-1, 1)),
        ]
        self.blue_team = [
            Player(random.uniform(0, 1), random.uniform(-1, 1)),
            Player(random.uniform(-1, 1), random.uniform(-1, 1)),
            Player(random.uniform(0, 1), random.uniform(-1, 1)),
        ]
        # self.ball = Ball(random.uniform(0, 1), random.uniform(-1, 1))
        self.ball = Ball(random.uniform(-0.8, 0.8), random.uniform(-0.8, 0.8))
        # while dist(self.blue_team[1].pos, self.ball.pos) > 0.2:
        #     self.blue_team[1] = Player(random.uniform(0, 1),
        #                                random.uniform(-1, 1))
        self.red_team = self.red_team[:self.red_players]
        self.blue_team = self.blue_team[:self.blue_players]
        self.ball_outfield = False

    def new_match(self):
        self.reset()
        self.blue_score = 0
        self.red_score = 0
        self.tic = 0

    def __init__(self,
                 red_players=3,
                 blue_players=3,
                 red_strategy=None,
                 blue_strategy=None):
        self.red_players = red_players
        self.blue_players = blue_players
        self.new_match()
        self.field = pygame.image.load("soccersim/soccer_field.png")
        self.red_strategy = red_strategy
        self.blue_strategy = blue_strategy
        self.last_blue_score = 0  # blue point earned on the last tic
        self.team_scored = None
        self.blue_kicked_at_tic = 0
        self.marcador = [0, 0]

    def draw_goals(self, screen):
        for goal in goals:
            pygame.draw.rect(screen, black, get_goal_rect(goal))

    def is_ball_in_goal(self):
        for i, goal in enumerate(goals):
            if get_goal_rect(goal).collidepoint(self.ball.pypos):
                return i

    def draw(self, screen, draw_to_img=False, fancy=True):
        if fancy:
            screen.blit(self.field, (0, 0))  # soccer field background
        else:
            screen.fill(Color("white"))  # white background
        for player in self.red_team:
            player.draw(screen, red)
        for player in self.blue_team:
            player.draw(screen, blue)
        font = pygame.font.Font(None, 30)
        if not draw_to_img:
            ren = font.render("Blue score: " + str(self.blue_score), 0, black,
                              white)
            screen.blit(ren, (10, 10))
        self.ball.draw(screen)
        self.draw_goals(screen)
        if draw_to_img:
            data = pygame.image.tostring(screen, "RGBA")
            image = Image.fromstring("RGBA", (settings.width, settings.height),
                                     data)
            if random.random() < 0.0001:
                image.save("borrame.jpg")
            return image
        else:
            pygame.display.flip()

    def calculate_blue_score(self):
        self.last_blue_score = 0
        for player in self.blue_team:
            if player.kicked:
                self.blue_kicked_at_tic = self.tic
                player.kicked = False
                self.last_blue_score = 0.1
        for player in self.red_team:
            if player.kicked:
                player.kicked = False
                self.last_blue_score = -0.1
        if self.team_scored == 1:
            self.last_blue_score = 1
        elif self.team_scored == 0:
            self.last_blue_score = -1
        elif self.outfield_penalty:
            self.last_blue_score = -0.5
        self.blue_score = self.blue_score + self.last_blue_score

    def check_ball_outfield(self):
        self.outfield_penalty = False
        if abs(self.ball.pos[0]) > 0.95:
            self.ball.pos[0] -= 0.1 * sign(self.ball.pos[0])
            self.outfield_penalty = True
        if abs(self.ball.pos[1]) > 0.95:
            self.ball.pos[1] -= 0.1 * sign(self.ball.pos[1])
            self.outfield_penalty = True

    def run(self):
        if self.tic == 5001:
            self.new_match()
        if self.team_scored is not None:
            self.team_scored = None
            self.reset()
        if self.red_strategy:
            self.red_strategy.run(self.red_team,
                                  self.blue_team,
                                  self.ball,
                                  side=0,
                                  tic=self.tic)
        if self.blue_strategy:
            self.blue_strategy.run(self.blue_team,
                                   self.red_team,
                                   self.ball,
                                   side=1,
                                   tic=self.tic)
        self.ball.update()

        # Check if someone scored
        # TODO: calculate_red_score()
        gol_to = self.is_ball_in_goal()
        if gol_to is not None:
            self.team_scored = not gol_to
            self.marcador[not gol_to] += 1
            print "GOL!!!!!!!!!!!", not gol_to

        self.check_ball_outfield()
        self.calculate_blue_score()
        self.tic += 1

    def is_finished(self):
        return self.tic == 5000

    def blue_gd(self):
        """Blue gol difference."""
        return self.marcador[1] - self.marcador[0]
Example #37
0
from ball import Ball
from scoreboard import Scoreboard
import time

# Defining Paddle Coordinates:
LEFT_PADDLE_COR = (-350, 0)
RIGHT_PADDLE_COR = (350, 0)

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)
pad_r = Paddle(RIGHT_PADDLE_COR)
pad_l = Paddle(LEFT_PADDLE_COR)
ball = Ball()
score = Scoreboard()

screen.listen()
screen.onkey(pad_r.move_up, "Up")
screen.onkey(pad_r.move_down, "Down")
screen.onkey(pad_l.move_up, "w")
screen.onkey(pad_l.move_down, "s")

game_is_on = True

while game_is_on:
    screen.update()
    if ball.ycor()>290 or ball.ycor()<-290:
        ball.bounce_y()
Example #38
0
def game_init():
    black = (0, 0, 0)

    pygame.init()
    run = True
    screen_width = 1500
    screen_height = 700
    screen = pygame.display.set_mode((screen_width, screen_height))

    all_sprites_list = pygame.sprite.Group()

    bricks_list = pygame.sprite.Group()
    for i in range(0, 12):
        for j in range(0, 5):
            bricks = Brick(100, 25)

            bricks.rect.x = (screen_width - 1300) + (i * 100)
            bricks.rect.y = (screen_height - 600) + (j * 50)

            bricks_list.add(bricks)
            all_sprites_list.add(bricks)

    paddle_list = pygame.sprite.Group()
    paddle = Paddle()
    paddle.rect.x = screen_width / 2
    paddle.rect.y = screen_height - 20
    paddle_list.add(paddle)
    all_sprites_list.add(paddle)

    ball = Ball(paddle.rect.x + paddle.paddle_width / 2, paddle.rect.y - (paddle.paddle_height + 10))
    ball.count = 4
    all_sprites_list.add(ball)

    clock = pygame.time.Clock()
    while run:
        screen.fill(black)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:

            paddle.moveLeft(5)

            if paddle.rect.x <= 0:
                paddle.rect.x = 0

        if keys[pygame.K_RIGHT]:

            paddle.moveRight(5)

            if paddle.rect.x >= screen_width - paddle.paddle_width:
                paddle.rect.x = screen_width - paddle.paddle_width

        # ball.update(paddle.rect.x, paddle.rect.y)

        if pygame.sprite.spritecollide(ball, bricks_list, True):

            if ball.speed > 0:
                ball.wall_bounce()

            if ball.speed < 0:
                ball.wall_bounce()

        if pygame.sprite.spritecollide(ball, paddle_list, False):

            if ball.speed > 0:
                if ball.rect.x + ball.ball_width / 2 < paddle.rect.x + paddle.paddle_width / 2:
                    ball.left_bounce()
                if ball.rect.x + ball.ball_width / 2 == paddle.rect.x + paddle.paddle_width / 2:
                    ball.wall_bounce()
                if ball.rect.x + ball.ball_width / 2 > paddle.rect.x + paddle.paddle_width / 2:
                    ball.wall_bounce()
            if ball.speed < 0:
                if ball.rect.x + ball.ball_width / 2 < paddle.rect.x + paddle.paddle_width / 2:
                    ball.wall_bounce()
                if ball.rect.x + ball.ball_width / 2 == paddle.rect.x + paddle.paddle_width / 2:
                    ball.wall_bounce()
                if ball.rect.x + ball.ball_width / 2 > paddle.rect.x + paddle.paddle_width / 2:
                    ball.right_bounce()
        if ball.count == 0:
            run = False
            gameover_screen()

        if not bricks_list:
            run = False
            gameover_screen()


        all_sprites_list.update(paddle.rect.x + paddle.paddle_width / 2, paddle.rect.y - (paddle.paddle_height + 10))
        all_sprites_list.draw(screen)
        text_to_screen(screen, "Balls left: " + str(ball.count-1), 10, 10)
        pygame.display.flip()
        clock.tick(120)
Example #39
0
#pong
import pygame
from ball import Ball
from paddle import Paddle

pygame.init()

size = [320, 240]
screen = pygame.display.set_mode(size)

mouse_y = 0

ball = Ball([0, 0], 5)
print(ball.radius, ball.position)

paddle1 = Paddle([0, 0], 10, 4)

paddle2 = Paddle([0, 0], 10, 4)

game_is_running = True

while game_is_running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_is_running = False

        mouse_y = pygame.mouse.get_pos()[1]
        print(mouse_y)
Example #40
0
from turtle import Screen, Turtle
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()

screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong The Game")
screen.tracer(0)

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")

game_is_on = True
while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()

    #detect wall
Example #41
0
def create_ball(screen):
    """Create an instance of Ball."""
    ball = Ball(10, 10, screen)
    position_ball(screen, ball)
    return ball
Example #42
0
from turtle import Screen
from new_player import Player
from score_board import Scoreboard
from ball import Ball
import time

screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong")
screen.tracer(0)  # delay update

player_one = Player((350, 0))
player_two = Player((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(player_one.up, "Up")
screen.onkey(player_one.down, "Down")

screen.onkey(player_two.up, "w")
screen.onkey(player_two.down, "s")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()
    ball.move()

    if ball.ycor() > 280 or ball.ycor() < -280:
Example #43
0
FOOD_VALUE = 3
FOOD_SIZE = 4

UNDER_SCORE = 20

NUMBER_OF_FOOD = 30

FUTURE_SEEING = 5
PREY_RADIUS = 40

LEADERS = 3
my_color = (random.random(), random.random(), random.random())

MY_BALL = Ball(0, 0, 0, 0,
               random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS - 5),
               my_color)
MY_SCORE = turtle.Turtle()

MY_SCORE.penup()
MY_SCORE.hideturtle()

BALLS = []
FOOD = []
SCORE = []

turtle.register_shape("gold.gif")
turtle.register_shape("silver.gif")
turtle.register_shape("bronze.gif")
'''
functin will set all the need parameters for staarting the game
Example #44
0
def start_game():

    f = open("leaderbord.txt", 'a')

    f.write('a')
    f = open("leaderbord.txt", 'r')

    if f.read(1) == 'a':
        f = open("leaderbord.txt", 'w')
        for i in range(LEADERS):
            f.write("0\n")
    f.close()

    bord = turtle.Turtle()
    bord.penup()
    bord.shapesize(5)

    f = open("leaderbord.txt", 'r')
    fflist = f.readlines()
    bord.shape("gold.gif")
    bord.goto(-SCREEN_WIDTH + 50, SCREEN_HEIGHT - 50)
    bord.write(fflist[0], font=("Ariel", 15, "bold"))
    bord.goto(-SCREEN_WIDTH + 20, SCREEN_HEIGHT - 25)
    bord.stamp()
    bord.shape("silver.gif")
    bord.goto(-SCREEN_WIDTH + 50, SCREEN_HEIGHT - 100)
    bord.write(fflist[1], font=("Ariel", 15, "bold"))
    bord.goto(-SCREEN_WIDTH + 20, SCREEN_HEIGHT - 75)
    bord.stamp()
    bord.shape("bronze.gif")
    bord.goto(-SCREEN_WIDTH + 50, SCREEN_HEIGHT - 150)
    bord.write(fflist[2], font=("Ariel", 15, "bold"))
    bord.goto(-SCREEN_WIDTH + 20, SCREEN_HEIGHT - 125)
    bord.stamp()

    #create all balls objects
    for i in range(NUMBER_OF_BALLS):
        ballx = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS,
                               SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
        bally = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS,
                               SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)

        dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
        dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)

        radius = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)

        color = (random.random(), random.random(), random.random())

        newBall = Ball(ballx, bally, dx, dy, radius, color)

        BALL = []

        BALLS.append(newBall)

    #create all food object
    for i in range(NUMBER_OF_FOOD):
        foodx = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS,
                               SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
        foody = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS,
                               SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)

        color = (random.random(), random.random(), random.random())

        newFood = Food(foodx, foody, color, FOOD_SIZE)

        FOOD.append(newFood)

    #create all score turtles
    for i in range(NUMBER_OF_BALLS):
        i = turtle.Turtle()
        i.hideturtle()
        i.penup()

        SCORE.append(i)
Example #45
0
WHITE = (255, 255, 255)
GREEN = (57, 200, 20)

size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")

paddleA = Paddle(GREEN, 10, 100)
paddleA.rect.x = 20
paddleA.rect.y = 200

paddleB = Paddle(GREEN, 10, 100)
paddleB.rect.x = 670
paddleB.rect.y = 200

ball = Ball(WHITE, 10, 10)
ball.rect.x = 345
ball.rect.y = 195

all_sprites_list = pygame.sprite.Group()

all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)
all_sprites_list.add(ball)

GameActive = True

clock = pygame.time.Clock()

scoreA = 0
scoreB = 0
Example #46
0
def main():
    pygame.init()

    # Definiamo colori e dimensioni
    # size = width, height = 1024, 800
    size = pygame.Rect(0, 0, 800, 600)
    black = (0, 0, 0)
    white = (255, 255, 255)

    # Definiamo la finestra
    screen = pygame.display.set_mode((size.width, size.height))
    pygame.display.set_caption("Pong")

    paddleA = Paddle(white, 10, 100)
    paddleA.rect.x = 20
    paddleA.rect.y = (size.height - 100) / 2

    paddleB = Paddle(white, 10, 100)
    paddleB.rect.x = size.width - 10 - 20
    paddleB.rect.y = (size.height - 100) / 2

    ball = Ball(white, 15)
    ball.rect.x = 345
    ball.rect.y = 195

    # Creazione di una lista che gestisce tutti gli sprite che creeremo nel gioco (i due paddle e la pallina)
    all_sprites_list = pygame.sprite.Group()
    all_sprites_list.add(paddleA)
    all_sprites_list.add(paddleB)
    all_sprites_list.add(ball)

    # Il loop va avanti finchè l'utente non esce dal gioco
    carryOn = True
    clock = pygame.time.Clock(
    )  # verrà usato per controllare quanto velocemente si aggiorna lo screen

    scoreA = 0
    scoreB = 0

    while carryOn:

        for event in pygame.event.get():
            # Qui viene gestito il clic sulla "X" che chiude la finestra
            if event.type == pygame.QUIT:
                quit_game()

            # se viene premuto uno dei tasti di movimento, si dice al paddle corretto di
            # cominciare a muoversi in quella direzione
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    paddleA.setMovementDir(Paddle.MOVE_UP)
                if event.key == pygame.K_s:
                    paddleA.setMovementDir(Paddle.MOVE_DOWN)

                if event.key == pygame.K_i:
                    paddleB.setMovementDir(Paddle.MOVE_UP)
                if event.key == pygame.K_k:
                    paddleB.setMovementDir(Paddle.MOVE_DOWN)

                # altro modo per chiudere
                if event.key == pygame.K_ESCAPE:
                    quit_game()

            # se viene rilasciato il tasto corrispondente alla direzione in cui il paddle si sta
            # muovendo al momento, gli si dice di smettere di muoversi
            if event.type == pygame.KEYUP:
                if (event.key == pygame.K_w and paddleA.mov_dir == Paddle.MOVE_UP) or \
                        (event.key == pygame.K_s and paddleA.mov_dir == Paddle.MOVE_DOWN):
                    paddleA.setMovementDir(0)

                if (event.key == pygame.K_i and paddleB.mov_dir == Paddle.MOVE_UP) or \
                        (event.key == pygame.K_k and paddleB.mov_dir == Paddle.MOVE_DOWN):
                    paddleB.setMovementDir(0)

        # viene chiamato il metodo update() di ogni sprite nel gruppo
        # I tre parametri vengono passati all'update() di ogni sprite nel gruppo, che può usarli come vuole
        all_sprites_list.update(scrn_size=size,
                                rectPA=paddleA.rect,
                                rectPB=paddleB.rect)

        if pygame.sprite.collide_mask(
                ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB):
            ball.bounce()

        screen.fill(black)
        pygame.draw.line(screen, white, [size.width / 2, 0],
                         [size.width / 2, size.height], 5)
        all_sprites_list.draw(screen)

        #Display scores:
        font = pygame.font.Font(None, 74)
        text = font.render(str(scoreA), 1, white)
        screen.blit(text, (size.width / 4, 0))
        text = font.render(str(scoreB), 1, white)
        screen.blit(text, (size.width * 3 / 4, 0))

        pygame.display.flip()

        # Limite a 90 frame per secondo
        clock.tick(90)
Example #47
0
        handDetect = HandDetect(0)
        ai_paddle = Paddle(0,  0,PADDLE_WIDTH,PADDLE_HEIGHT,PADDLE_COLOR, True)
        human_paddle = Paddle(640 - PADDLE_WIDTH,0,PADDLE_WIDTH,PADDLE_HEIGHT,PADDLE_COLOR)
    # Else if the user is left handed, initialise game for left-handedness
    elif sys.argv[1] == '--left' or sys.argv[1] == '--l':
        handDetect = HandDetect(1)
        ai_paddle = Paddle(640 - PADDLE_WIDTH,0,PADDLE_WIDTH,PADDLE_HEIGHT,PADDLE_COLOR, True)
        human_paddle = Paddle(0,  0,PADDLE_WIDTH,PADDLE_HEIGHT,PADDLE_COLOR)
# If more than two command line args, display same usage error message and exit
else:
    print("Invalid usage, please provide one command line argument stating your handedness")
    print("E.g: python3 game.py [--l | --left | --r | --right]\n")
    sys.exit(1)

# Create the ball game object 
ball = Ball(SCREEN_HEIGHT // 2, SCREEN_WIDTH // 2, BALL_RADIUS, BALL_COLOR)

# Dont run the game loop unit specified by the user
game_start = False

# Main game loop
while(1):

    # Read frame from the capture
    ret, frame = cap.read()
    # Flip the frame as to be displayed correctly
    frame = cv.flip(frame, 1)
    # Create a pure copy of the input for detection/calibration
    calibrate_frame = frame.copy()

    # Call my hand detection API to get the hand position
Example #48
0
class Game():
    def __init__(self, width, height, player_name, opp_name):
        self.player = Player(0, height / 2, player_name)
        self.opponent = Player(width, height / 2, opp_name)
        self.ball = Ball(width / 2, height / 2)

    def update(self, screen):
        self.ball.move(screen, self.player, self.opponent)

        if self.get_winner() is None:
            if self.ball.ball.left <= 0:
                self.opponent.update_score()
                self.restart_round(screen)
            elif self.ball.ball.right >= screen.get_width():
                self.player.update_score()
                self.restart_round(screen)
        else:
            self.stop()
            self.display_winner(screen)

    def get_winner(self):
        if self.player.score >= 11:
            return self.player
        elif self.opponent.score >= 11:
            return self.opponent
        else:
            return None

    def display_play_again(self, screen, x):
        font = pygame.font.Font('freesansbold.ttf', 20)
        loc = (int(screen.get_width() * x), 80)
        rect = pygame.draw.rect(screen, (0, 0, 0),
                                (loc[0] + 30, loc[1] + 50, 100, 50))
        playagain = font.render('Play Again?', False, (255, 255, 255))
        screen.blit(playagain, (int(screen.get_width() * x), 120))

        mouse = pygame.mouse.get_pos()
        mouse_x_in_rect = mouse[0] >= rect.left and mouse[0] <= rect.right
        mouse_y_in_rect = mouse[1] >= rect.top and mouse[1] <= rect.bottom
        if mouse_x_in_rect and mouse_y_in_rect:
            self.restart_game(screen)

    def display_winner(self, screen):
        if self.get_winner().name == self.player.name:
            self.player.display_winner_text(screen, 0.15)
            self.display_play_again(screen, 0.20)
        elif self.get_winner().name == self.opponent.name:
            self.opponent.display_winner_text(screen, 0.6)
            self.display_play_again(screen, 0.75)

    def stop(self):
        self.ball.speed_x = 0
        self.ball.speed_y = 0

    def restart_round(self, screen):
        self.ball.ball.center = (screen.get_width() / 2,
                                 screen.get_height() / 2)
        self.ball.speed_x *= choice((-1, 1))
        self.ball.speed_y *= choice((-1, 1))

    def restart_game(self, screen):
        width = screen.get_width()
        height = screen.get_height()
        pname = self.player.name
        oname = self.opponent.name
        self.__init__(width, height, pname, oname)
        self.restart_round(screen)

    def draw(self, screen):
        screen.fill(background)
        width = screen.get_width()
        pygame.draw.line(screen, line_color, [width / 2, 0],
                         [width / 2, width], 1)
        self.player.update_score_text(screen, 0.25)
        self.opponent.update_score_text(screen, 0.75)
        self.update(screen)

        self.player.draw_paddle(screen)
        self.opponent.draw_paddle(screen)
        self.ball.draw(screen)
Example #49
0
def create_ball(ai_settings, screen, person, balls):
    ball = Ball(ai_settings, screen)
    ball.x = randint(0, ai_settings.screen_width)
    ball.rect.x = ball.x
    balls.add(ball)
Example #50
0
 def __init__(self, width, height, player_name, opp_name):
     self.player = Player(0, height / 2, player_name)
     self.opponent = Player(width, height / 2, opp_name)
     self.ball = Ball(width / 2, height / 2)
Example #51
0
from turtle import Screen
from paddle import Paddle
from ball import Ball
import time
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")

#      []
screen.tracer(0)
right_paddle = Paddle((350, 0))
left_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(key="Up", fun=right_paddle.go_up)
screen.onkey(key="Down", fun=right_paddle.go_down)
screen.onkey(key="w", fun=left_paddle.go_up)
screen.onkey(key="s", fun=left_paddle.go_down)

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(ball.move_speed)
    ball.move()

    if ball.xcor() > 400:
Example #52
0
class Breakout(object):
	def __init__(self):
		# Initilaize pygame and the display/window
		pygame.init()
		self.screen_width, self.screen_height = 600, 800
		self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))  # , pygame.FULLSCREEN)
		pygame.display.set_caption('Breakout')
		
		# Create the game objects
		self.paddle = Paddle(self.screen_width, self.screen_height)
		self.ball = Ball(self.screen_width, self.screen_height)
		self.bricks = list()
		for i in range(0,600,60):
			for j in range(42, 211, 42):
				self.bricks.append(Brick(self.screen_width, self.screen_height, i, j))

		# Let's control the frame rate
		self.clock = pygame.time.Clock()

	def new_game(self):
		"""Start a new game of Breakout.

		Resets all game-level parameters, and starts a new round.
		"""
		self.game_over = False
		self.round = 0
		self.paddle.reset()

		self.new_round()

	def new_round(self):
		"""Start a new round in a Breakout game.

		Resets all round-level parameters, increments the round counter, and
		puts the ball on the paddle.
		"""
		self.round += 1
		self.ball.reset(self.paddle)

	def play(self):
		"""Start Breakout program.

		New game is started and game loop is entered.
		The game loop checks for events, updates all objects, and then
		draws all the objects.
		"""
		self.new_game()
		while not self.game_over:           # Game loop
			self.clock.tick(50)             # Frame rate control
			font = pygame.font.SysFont("monospace", 15)
			round_counter = font.render("Round " + str(self.round), 2, (255,255,0))
		
			for event in pygame.event.get():
				if event.type == pygame.QUIT or event.type == pygame.MOUSEBUTTONDOWN:
					self.game_over = True
					break
				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_SPACE:
						self.ball.serve()
					if event.key == pygame.K_LEFT:
						self.paddle.x_velocity = -4
					elif event.key == pygame.K_RIGHT:
						self.paddle.x_velocity = 4
					if event.key == pygame.K_a:
						self.ball.x_velocity = -3
					elif event.key == pygame.K_d:
						self.ball.x_velocity = 3

					# This starts a new round, it's only here for debugging purposes
					if event.key == pygame.K_r:
						self.new_round()
					# This starts a new game, it's only here for debugging purposes
					if event.key == pygame.K_g:
						self.new_game()
				if event.type == pygame.KEYUP:
					if event.key == pygame.K_LEFT and self.paddle.x_velocity < 0:
						self.paddle.x_velocity = 0
					if event.key == pygame.K_RIGHT and self.paddle.x_velocity > 0:
						self.paddle.x_velocity = 0
			else:
				self.paddle.update()
				contact = self.ball.update(self.paddle, self.bricks)
				for brick in self.bricks:
					if contact == brick:
						self.bricks.remove(brick)
					

				self.screen.fill((0, 0, 0))
				self.screen.blit(round_counter, (0, 0))
				ball_loc = font.render(str(self.ball.x) + "," + str(self.ball.y), 2, (255,255,0))
				self.screen.blit(ball_loc, (0, 14))
				self.paddle.draw(self.screen)
				self.ball.draw(self.screen)
				pygame.display.flip()
		
		
				for brick in self.bricks:
					brick.draw(self.screen)
				
				pygame.display.flip()
					
				if self.ball.y >= self.screen_height - self.ball.radius:
					self.new_round()
				if self.round > 3:
					self.new_game()
		

		pygame.quit()
Example #53
0
from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong Game")
screen.tracer(0)
score = Scoreboard()

r_player = Paddle((350, 0))
l_player = Paddle((-350, 0))
pelota = Ball()

screen.listen()
screen.onkeypress(fun=r_player.up, key='Up')
screen.onkeypress(fun=r_player.down, key='Down')
screen.onkeypress(fun=l_player.up, key='w')
screen.onkeypress(fun=l_player.down, key='s')

game_is_on = True

while game_is_on:
    time.sleep(pelota.move_speed)
    screen.update()
    pelota.move()

    # Detect Collision
Example #54
0
from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time
import random

screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong")
screen.tracer(0)

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball((0, 0))
scoreboard = Scoreboard()

screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")

game_is_on = True
while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move_forward()
    ball.bounce_y()
    # Paddle bounce
Example #55
0
border.goto(-400, -300)
border.pendown()
border.forward(800)
border.left(90)
border.forward(600)
border.left(90)
border.forward(800)
border.left(90)
border.forward(600)
border.hideturtle()

screen.tracer(0)

r_paddle = Paddle((360, 0))
l_paddle = Paddle((-360, 0))
ball = Ball()

screen.listen()
screen.onkey(l_paddle.go_up, "q")
screen.onkey(l_paddle.go_down, "a")
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")

game_is_on = True
while game_is_on:
    time.sleep(0.05)
    screen.update()
    ball.move()
    if ball.ycor() > 290 or ball.ycor() < -290:
        ball.bounce()
    if ball.distance(r_paddle) < 50 and ball.xcor() > 340 or ball.distance(
Example #56
0
 def fire_ball(self):
     ball = Ball(self.x, self.y, self.dir*3)
     game_world.add_object(ball, 1)
Example #57
0
from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)

right_paddle = Paddle((350, 0))
left_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()
screen.listen()

screen.onkey(right_paddle.go_up, "Up")
screen.onkey(right_paddle.go_down, "Down")
screen.onkey(left_paddle.go_up, "w")
screen.onkey(left_paddle.go_down, "s")

game_is_on = True

while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()

    if ball.ycor() > 280 or ball.ycor() < -280:
Example #58
0
    net.color("white")
    net.pensize(10)
    net.shape("square")
    net.setheading(270)
    net.penup()
    net.goto(0, 400)
    while net.ycor() > -400:
        net.pendown()
        net.forward(20)
        net.penup()
        net.forward(20)
    net.goto(0, 400)

    paddle_r = Paddle((350, 0))
    paddle_l = Paddle((-350, 0))
    ball = Ball()
    scoreboard = ScoreBoard()

    # move up and down
    screen.listen()

    screen.onkeypress(paddle_r.up, "Up")
    screen.onkeypress(paddle_r.down, "Down")

    screen.onkey(paddle_l.up, "w")
    screen.onkey(paddle_l.down, "s")


    # let the paddle render
    game_is_on = True
    while game_is_on:
def create_ball(group):
    indx = randint(0, len(balls_surf) - 1)
    x = randint(20, WIDTH - 20)
    speed = randint(1, 4)
    return Ball(x, speed, balls_surf[indx], group)
Example #60
0
from paddle import Paddle
from scoreboard import Scoreboard

import time

screen = Screen()

screen.bgcolor("black")
screen.setup(800, 600)
screen.title("Pong")
screen.tracer(0)

p1 = Paddle(350, 0)
p2 = Paddle(-350, 0)

ball = Ball()
scoreboard = Scoreboard()

screen.update()

screen.listen()
screen.onkey(p1.moveup, "Up")
screen.onkey(p1.movedown, "Down")
screen.onkey(p2.moveup, "w")
screen.onkey(p2.movedown, "s")

is_game_on = True

while is_game_on:
    time.sleep(ball.movespeed)