Exemple #1
0
import pygame
from datetime import date, datetime
import random
import math

from ball import Ball
from constants import *

pygame.init()

# Set up the drawing window
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 18)

balls = [Ball(i, BALL_RADIUS) for i in range(NUMBER_OF_BALLS)]
balls_pos = None

# Run until the user asks to quit
running = True

while running:	
	# Did the user click the window close button?
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			running = False

	# Fill the background with white
	screen.fill(BLACK)

	# fps
Exemple #2
0
HEIGHT = 960

# Basic address information
ip = socket.gethostbyname(socket.gethostname())
port = 5050
addr = ip, port

# Creating local server
local_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
local_server.bind(addr)

players = [
    Player(10, HEIGHT / 2 - 70, 10, 140),
    Player(WIDTH - 20, HEIGHT / 2 - 70, 10, 140)
]
ball = Ball(WIDTH / 2 - 15, HEIGHT / 2 - 15, 30, 30)
score = [0, 0]


# Ball movement loop
def serve():
    clock = pygame.time.Clock()
    while True:
        clock.tick(60)
        point = ball.move(WIDTH, HEIGHT, players[0], players[1])
        if point > -1:
            score[point] += 1
            ball.set_speed(0, 0)
            pygame.time.wait(3000)
            ball.set_speed(9, 9)
Exemple #3
0
# Initializing the clock and setting the caption
clock = pygame.time.Clock()
pygame.display.set_caption('Breakout')

# All sprites group
sprites = pygame.sprite.Group()

# Paddle Object
paddle = Paddle(WHITE, int((WIDTH / 8)), int((HEIGHT / 50)))
paddle.rect.x = int((WIDTH / 2) - 100)
paddle.rect.y = int(HEIGHT * 0.8)
sprites.add(paddle)

# Ball Object
ball = Ball(LIGHTGRAY, 10, 10)
ball.rect.x = int(WIDTH / 2)
ball.rect.y = int(HEIGHT * 0.7)
sprites.add(ball)

# Brick Objects
bricks = pygame.sprite.Group()
for i in range(15):
    brick = Brick(red, 80, 30)
    brick.rect.x = 60 + i * 100
    brick.rect.y = 140
    sprites.add(brick)
    bricks.add(brick)
for i in range(15):
    brick = Brick(yellow, 80, 30)
    brick.rect.x = 60 + i * 100
Exemple #4
0
 def fire_ball(self):
     ball = Ball(self.x, self.y, self.dir * RUN_SPEED_PPS * 10)
     game_world.add_object(ball, 1)
Exemple #5
0
screen = turtle.Screen()
screen.tracer(0)
screen.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
screen.bgcolor('grey')
screen.title("Pong Game")

# Border setup
border = Border(s_width=SCREEN_WIDTH, s_height=SCREEN_HEIGHT)

# paddle setup
paddle = Paddle(border_half_height=border.border_half_height,
                border_half_width=border.border_half_width)
paddle.goto((-1) * (SCREEN_WIDTH / 2 - 60), 0)

# ball setup
ball = Ball(border_half_height=border.border_half_height,
            border_half_width=border.border_half_width)

# score setup
score = Score(s_width=SCREEN_WIDTH, s_height=SCREEN_HEIGHT)

# level setup
level = Level(s_width=SCREEN_WIDTH, s_height=SCREEN_HEIGHT)

screen.update()

# paddle movement handle
screen.listen()
screen.onkeypress(key="Up", fun=paddle.move_up)
screen.onkeypress(key="Down", fun=paddle.move_down)

# play game
Exemple #6
0
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.set_location(400, 100)
		self.player = Player()
		self.ball = Ball()
Exemple #7
0
def test_coord():
    global last_time

    holes: list = list()
    for coord in hole_cord:
        holes.append(Hole(coord))

    ########################################
    #   CONST
    ########################################
    dt = 0.001  # (DEFAULT: 0.001) If set to 'none', then the calculation will depend on the processor.
    SPEED_PLAYER: int = 5000
    COORD: list = [{
        'x': 749.1037356209815,
        'y': 400.0
    }, {
        'x': 737.4778075654237,
        'y': 518.4374639103951
    }, {
        'x': 841.6458133769794,
        'y': 296.7989203069272
    }, {
        'x': 834.1708522543635,
        'y': 534.2549155340065
    }, {
        'x': 918.795265395989,
        'y': 387.5792773227268
    }, {
        'x': 924.1263862601234,
        'y': 444.9924739563589
    }, {
        'x': 906.6978983363924,
        'y': 263.33987765061704
    }, {
        'x': 886.699359748491,
        'y': 522.0441045696581
    }, {
        'x': 980.8492405433761,
        'y': 435.93334702264514
    }, {
        'x': 971.2759021415388,
        'y': 372.77205010294244
    }, {
        'x': 981.3676568055325,
        'y': 313.51423648206907
    }, {
        'x': 742.44247267777,
        'y': 241.66676006285635
    }, {
        'x': 1062.1638977248808,
        'y': 343.8689652863846
    }, {
        'x': 1087.6745239649977,
        'y': 412.3710284138871
    }, {
        'x': 1040.0,
        'y': 455.0
    }, {
        'x': 961.9666736738287,
        'y': 670.3627325102416
    }]

    ########################################
    #   Generate balls
    ########################################
    balls: list = list()
    with open('balls.json') as f:
        for ball_name, struct in json.load(f).items():
            balls.append(
                Ball(struct['position'], struct['color'], struct['radius'],
                     balls))

    ########################################
    #   Move player
    ########################################
    player: Ball = balls[0]
    player.speed_x = SPEED_PLAYER

    ########################################
    #   Check speed
    ########################################
    speed: bool = True
    while speed:
        last_time, balls = update(last_time, balls, dt)

        count_ball: int = 0
        for ball in balls:
            if not (round(ball.speed_x, 3) or round(ball.speed_y, 3)):
                count_ball += 1

        if count_ball == len(balls):
            speed = False

    ########################################
    #   Check location ball
    ########################################
    buf: float = 0.0
    for i, ball in enumerate(balls):
        # relative error
        sigma_x = (abs(COORD[i]['x'] - ball.location['x']) /
                   ball.location['x']) * 100
        sigma_y = (abs(COORD[i]['y'] - ball.location['y']) /
                   ball.location['y']) * 100
        print(f'x: {round(sigma_x, 1)} %, y: {round(sigma_y, 1)} %')
        buf += sigma_x + sigma_y

    # Average
    A = round(buf / (len(balls) * 2), 1)
    print(f'{A} %')
    assert 0.0 == A
Exemple #8
0
def main():
    pygame.init()
    pygame.display.set_caption('Interference')
    pygame.key.set_repeat(10, 10)  # keypresses to auto-repeat every 10msec
    rects = []  # create a list

    screen = pygame.display.set_mode((screenwidth, screenheight))
    background = Background("assets/level1-stage.gif", [0, 0])
    bgsurface = pygame.Surface(screen.get_size())
    bgsurface = bgsurface.convert()  # speeds up blitting
    bgsurface.fill([0, 0, 255])  # set background to blue
    # if we only use a portion of the background image, change the first two values here:
    bgsurface.blit(
        background.image.subsurface(0, 0, screenwidth, screenheight), (0, 0))
    screen.blit(bgsurface, (0, 0))  # get the bgsurface onto the screen surface
    pygame.display.update()  # update the entire display

    # instantiate the sprites
    ball_sprite = Ball()
    bat_sprite = Bat()

    # store all sprite rects we create into this list
    rects.append(ball_sprite.getrect())
    rects.append(bat_sprite.getrect())

    balls_group = pygame.sprite.Group(ball_sprite)
    characters_group = pygame.sprite.Group(bat_sprite)

    while True:  # this is a forever loop
        ev = pygame.event.poll()
        if ev.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)

        batmoved = 0
        if ev.type == KEYDOWN:  # button pressed?
            if (ev.key == btn_left):
                batloc = [-1, 0]
                bat_sprite.movepos(batloc)
                ball_sprite.accel(-1)  # influence ball speed if needed
                batmoved = -1
            elif (ev.key == btn_right):
                batloc = [1, 0]
                bat_sprite.movepos(batloc)
                ball_sprite.accel(1)  # influence ball speed if needed
                batmoved = 1

        # check for collisions
        collide = pygame.sprite.collide_rect(bat_sprite, ball_sprite)
        if collide:
            ball_sprite.collision(bat_sprite.getrect(), batmoved)

        # clear the sprite(s) and then update and redraw them
        characters_group.clear(screen, bgsurface)
        balls_group.clear(screen, bgsurface)
        characters_group.update()
        balls_group.update()
        characters_group.draw(screen)
        balls_group.draw(screen)

        pygame.display.update(rects)
Exemple #9
0
import pygame
from ball import Ball
from pad import Pad
from brick import Brick

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("打磚塊遊戲")
background = pygame.Surface(screen.get_size()).convert()
background.fill((255, 255, 255))
allsprite = pygame.sprite.Group()  #建立全部角色群組
bricks = pygame.sprite.Group()  #建立磚塊角色群組
ball = Ball(10, 300, 200, 30, (255, 0, 0), edge=3)  #建立紅色球物件
#ball1 = Ball(10, 300, 200, 30, (0,0,255),edge=3)
allsprite.add(ball)  #加入全部角色群組
#allsprite.add(ball1)  #加入全部角色群組
pad = Pad()  #建立滑板球物件
allsprite.add(pad)  #加入全部角色群組
clock = pygame.time.Clock()
for row in range(0, 4):  #3列方塊
    for column in range(0, 15):  #每列15磚塊
        if row == 0 or row == 1:  #1,2列為綠色磚塊
            brick = Brick((0, 255, 0), column * 40 + 1, row * 15 + 1)
        if row == 2 or row == 3:  #3,4列為藍色磚塊
            brick = Brick((0, 0, 255), column * 40 + 1, row * 15 + 1)
        bricks.add(brick)  #加入磚塊角色群組
        allsprite.add(brick)  #加入全部角色群組
playing = False  #開始時球不會移動
running = True
while running:
    clock.tick(30)
Exemple #10
0
            output += obj.toString() + ","
        return output


if __name__ == "__main__":
    # inicjacja modułu pygame
    pygame.init()

    WIDTH = 800
    HEIGHT = 400
    main_window = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
    pygame.display.set_caption('Prosty Pong')

    pad1 = Pad(pygame, Color.BLUE, 350, 360)
    pad2 = Pad(pygame, Color.RED, 350, 20)
    ball = Ball(pygame)
    state = GameState([pad1, pad2, ball])

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

    AI_SPEED = 5

    PLAYER_SCORE = '0'
    AI_SCORE = '0'
    fontObj = pygame.font.Font('freesansbold.ttf', 64)

    pygame.key.set_repeat(50, 25)
    x = threading.Thread(target=start_zmq_server, args=(state, ), daemon=True)
    x.start()
Exemple #11
0
def create_ball(balls, screen, ai_settings):
    # create a ball and put that in the group balls
    ball = Ball(screen, ai_settings)
    balls.add(ball)
        nearest_wall.start[1] - ball.pos[1]
    ])

    var_t = np.linalg.solve(variables, absolute)[0]
    intersection = np.array([
        ball.pos[0] + var_t * perpendicular_vector[0],
        ball.pos[1] + var_t * perpendicular_vector[1]
    ])

    # mirrored point is equal to current ball pos + 2 * the distance between the ball_pos and the intersection_point
    mirror_point = np.array([
        ball.pos[0] + 2 * (intersection[0] - ball.pos[0]),
        ball.pos[1] + 2 * (intersection[1] - ball.pos[1])
    ])
    return mirror_point


window.bind("<Button-3>", rightPressed)
window.bind("<B3-Motion>", rightMoved)
window.bind("<ButtonRelease-3>", rightReleased)
window.bind("<Button-1>", leftPressed)

c = Canvas(window, width=WIDTH, height=HEIGHT)
c.configure(background="#0a6c03")

ball = Ball(c)
ball.draw()

c.pack()
window.mainloop()
 
turtle.penup()

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

#ball_a = Ball(3,5,2,3,6,"blue")
#ball_b = Ball(4,6,7,4,8, "red")
#ball_a.goto(100,100)
#ball_b.goto(100,100)

MY_BALL = Ball(0,0,10,10,13,"green")
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 = []


#PART 0
for i in range(NUMBER_OF_BALLS):
    X = random.randint(round(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS),round(SCREEN_WIDTH - MAXIMUM_BALL_RADIUS))
    
    Y = random.randint(round(- SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS),round(SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS))
Exemple #14
0
from ball import Ball
from container import Container

ball = Ball(50, 50, 5, 10, 30)
box = Container(0, 0, 100, 100)
for step in range(0, 100):
    ball.move()
    box.collides_with(ball)
    print(ball)
Exemple #15
0
from turtle import *
import turtle
import time
import random
import math
from ball import Ball

turtle.colormode(1)

turtle.tracer(0)
turtle.hideturtle()
running = True
screen_width = turtle.getcanvas().winfo_width() / 2
screen_height = turtle.getcanvas().winfo_height() / 2
my_ball = Ball(100, 50, 3, 3, 50, "red")
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 = random.randint(-screen_width + maximum_ball_radius,
                       screen_width - maximum_ball_radius)
    y = random.randint(-screen_height + maximum_ball_radius,
                       screen_height - maximum_ball_radius)
    dx = random.randint(minimum_ball_dx, maximum_ball_dx)
WHITE = (255, 255, 255)

# Open a new window
size = (1280, 720)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")

paddleA = Paddle(WHITE, 10, 100)
paddleA.rect.x = 20
paddleA.rect.y = 360

paddleB = Paddle(WHITE, 10, 100)
paddleB.rect.x = 1250
paddleB.rect.y = 360

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

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

# Add the car to the list of objects
all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)
all_sprites_list.add(ball)

# The loop will carry on until the user exit the game (e.g. clicks the close button).
carryOn = True

# The clock will be used to control how fast the screen updates
Exemple #17
0
screen = pygame.display.set_mode(size)#setting the size of window
pygame.display.set_caption("Air Hockey 2D")#updating the heading
gameIcon=pygame.image.load('apaddle.jpg')#icon image
pygame.display.set_icon(gameIcon)#setting the icon
background=pygame.image.load("background.jpg").convert()

    
paddleA = Paddle(BLUE, 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(RED,10,10)
ball.rect.x=345
ball.rect.y=195

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()
    
# Add the paddles to the list of sprites
all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)
all_sprites_list.add(ball)


def text_objects(text, font,color):
    textSurface = font.render(text,True,color)
    return textSurface, textSurface.get_rect()
Exemple #18
0
def run_game():
    # initialize pygame, clock, settings, and screen objects
    pygame.init()
    clock = pygame.time.Clock()
    p_settings = Settings()
    screen = pygame.display.set_mode(
        (p_settings.screen_width, p_settings.screen_height))
    screen_rect = screen.get_rect()
    pygame.display.set_caption("Pong")

    # create the game over message
    play_button = Button(screen, "Play")

    # Create an instance to store game statistics, and a scoreboard.
    stats = GameStats(p_settings)
    sb = Scoreboard(p_settings, screen, stats)

    # set the background color
    bg_color = (230, 230, 230)

    # make a paddle
    paddle_right = Paddle(p_settings, screen, 'right', 'vert')
    paddle_left = Paddle(p_settings, screen, 'left', 'vert')
    paddle_tr = Paddle(p_settings, screen, 'tr', 'hor')
    paddle_tl = Paddle(p_settings, screen, 'tl', 'hor')
    paddle_br = Paddle(p_settings, screen, 'br', 'hor')
    paddle_bl = Paddle(p_settings, screen, 'bl', 'hor')

    # make a ball
    ball = Ball(p_settings, screen)
    balls = Group(ball)

    # make a group of paddles
    paddles = Group(paddle_right, paddle_left, paddle_tr, paddle_tl, paddle_br,
                    paddle_bl)

    # start screen
    gi.Game_Intro(p_settings, screen, stats, sb, play_button, paddles, ball,
                  paddle_right, paddle_tr, paddle_br, clock)

    # start the main loop for the game
    while True:

        gf.check_events(p_settings, screen, stats, sb, play_button, paddles,
                        ball, paddle_right, paddle_tr, paddle_br)

        if stats.game_active:
            gf.track_ball(ball, paddle_left, paddle_tl, paddle_bl)

            paddle_right.update()
            paddle_tr.update()
            paddle_br.update()
            paddle_left.update()
            paddle_tl.update()
            paddle_bl.update()
            paddles.update()
            ball.update()
            # print ("game active")
            gf.check_ball_paddle_collisions(p_settings, screen, ball,
                                            paddle_right, paddle_left,
                                            paddle_tr, paddle_tl, paddle_br,
                                            paddle_bl)

        # print("player score " + str(stats.p_score))
        # print("ai score " + str(stats.ai_score))

        gf.update_screen(p_settings, screen, paddles, ball, sb, stats,
                         play_button, paddle_right, paddle_left, paddle_tr,
                         paddle_tl, paddle_br, paddle_bl)

        gf.check_ball_out(p_settings, screen, screen_rect, stats, sb, paddles,
                          ball, paddle_right, paddle_left, paddle_tr,
                          paddle_tl, paddle_br, paddle_bl)

        # checks if score limit has been reached
        if stats.ai_score == 5 or stats.p_score == 5:
            # game over screen
            go.Game_Over(p_settings, screen, stats, sb, play_button, paddles,
                         ball, paddle_right, paddle_tr, paddle_br, clock)
            stats.reset_stats()
            sb.prep_p_score()
            sb.prep_ai_score()

        # set the game fps
        clock.tick(60)
Exemple #19
0
 def initialize_balls(self):
     for i in range(self.sequence_size - 1, -2, -1):
         color = random.randint(0, len(Colors.get_all_colors()) - 1)
         self.sequence.enqueue(
             Ball(self.start.x, self.start.y,
                  Colors.get_all_colors()[color]))
Exemple #20
0
    def update(self, time_delta):
        """
        Updates game condition

        time_delta is time passed from last call
        """
        self.update_debuffs(time_delta)
        if len(self.come_back) == 0:
            if 'slow' in self.debuffs:
                self.move_balls_head_by_time(len(self.balls), time_delta / 2)
            else:
                self.move_balls_head_by_time(len(self.balls), time_delta)
        else:
            amount = self.come_back[0]
            self.move_balls_head_by_time(amount, time_delta * 3, True)
            d = self.get_ball_distance(self.balls[amount - 1],
                                       self.balls[amount])
            if d < self.r * 2:
                self.move_balls_head_by_distance(amount, self.r * 2 - d)
                self.come_back.clear()
                s1 = self.check_sequence(amount - 1)
                s2 = self.check_sequence(amount)
                if s1 == s2 and s1[1] - s1[0] >= 2:
                    self.delete_ball_sequence(s1[0], s1[1])
        if self.amount > 0 and (len(self.balls) == 0 or get_distance(
                self.cp[0], self.balls[len(self.balls) - 1].pos) >= self.r * 2
                                ):
            if luck_check(8) and len(self.bonuses) > 0:
                b = Ball(random.randint(-len(self.bonuses), -1), self.r,
                         self.cp[0])
            else:
                b = Ball(random.randint(0, self.ball_amount - 1), self.r,
                         self.cp[0])
            self.balls.append(b)
            self.amount -= 1
        if len(self.come_back) == 0:
            counter = 0
            for bul_pair in self.p.bullets:
                dx = self.p.b_speed * time_delta
                bul_pair[0].move(dx * math.cos(bul_pair[1]),
                                 -dx * math.sin(bul_pair[1]))
                if not is_in_border(bul_pair[0].pos, (-self.r, -self.r),
                                    (self.w + self.r, self.h + self.r)):
                    bul_pair[0].status = 3
                for i in range(len(self.balls)):
                    if get_distance(bul_pair[0].pos, self.balls[i].pos) <= \
                       self.r * 2:
                        if len(self.balls) == 1:
                            a1 = get_angle2(bul_pair[0].pos, self.balls[0].pos,
                                            self.cp[self.balls[0].goal])
                            a2 = get_angle2(bul_pair[0].pos, self.balls[0].pos,
                                            self.cp[self.balls[0].goal - 1])
                            if a1 < a2:
                                self.insert_ball(0, bul_pair[0], 1)
                            else:
                                self.insert_ball(1, bul_pair[0], 0)

                        elif i == 0:
                            if get_angle2(bul_pair[0].pos, self.balls[i].pos,
                                          self.balls[i + 1].pos) < math.pi / 2:
                                self.insert_ball(1, bul_pair[0], 0)
                            else:
                                self.insert_ball(0, bul_pair[0], 1)
                        elif i == len(self.balls) - 1:
                            if get_angle2(bul_pair[0].pos, self.balls[i].pos,
                                          self.balls[i - 1].pos) < math.pi / 2:
                                self.insert_ball(i, bul_pair[0], i + 1)
                            else:
                                self.insert_ball(i + 1, bul_pair[0], i)
                        else:
                            d1 = get_distance(bul_pair[0].pos,
                                              self.balls[i - 1].pos)
                            d2 = get_distance(bul_pair[0].pos,
                                              self.balls[i + 1].pos)
                            if d1 < d2:
                                self.insert_ball(i, bul_pair[0], i + 1)
                            else:
                                self.insert_ball(i + 1, bul_pair[0], i)
                        counter -= 1
                        self.p.bullets.remove(bul_pair)
                        break
                counter += 1
        if len(self.balls) == 0 and self.amount == 0:
            self.won = True
            self.finished = True
            self.update_highscores()
Exemple #21
0
 def fire(self):
     global wav_explosion
     self.ball = Ball(self.player.pos, (5, 5))
     gfw.world.add(gfw.layer.ball, self.ball)
     wav_explosion.play()
Exemple #22
0
 def fire_ball(self):
     ball = Ball(self.x, self.y, self.dir * 3)
     game_world.add_object(ball, 1)
     pass
Exemple #23
0
from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

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

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

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

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

    # Detect collision with wall
    if ball.ycor() > 280 or ball.ycor() < -280:
Exemple #24
0
def game():
    ball_vel = 8
    player_vel = 15
    is_running = True
    player = Paddle((WIDTH//2)-(SIZE*4), HEIGHT-SIZE*3)
    ball = Ball(player.get_rect().centerx, player.get_rect().top - SIZE)
    scoreboard = ScoreBoard()
    clock = pygame.time.Clock()
    bricks = []
    hearts = []

    def make_bricks():
        for i in range(5):
            for j in range(WIDTH//(BRICK_WIDTH+SIZE//2)-2):
                brick_x = (j+1)*(BRICK_WIDTH+SIZE//2) + SIZE
                brick_y = (i+4)*BRICK_HEIGHT*3//2 + SCOREBOARD_HEIGHT
                bricks.append(Brick(brick_x, brick_y, scoreboard.level))
    make_bricks()

    def redraw_window():
        window.fill('black')
        player.draw(window)
        for brick in bricks:
            brick.draw(window)
        ball.draw(window)
        for bullet in player.bullets:
            if bullet.check_out_of_window():
                player.bullets.remove(bullet)
            elif bullet.check_brick_collision(bricks, hearts):
                if len(bricks) == 0:
                    scoreboard.level += 1
                    ball.reset()
                    player.reset()
                    ball.cooldown(1500)
                    make_bricks()
                scoreboard.score += 10
                player.bullets.remove(bullet)
                break_sound.play()
            else:
                bullet.draw(window, dt*ball_vel)
        for heart in hearts:
            heart.move(dt*ball_vel/2)
            if heart.check_collision(player):
                scoreboard.life += 1
                health_sound.play()
                hearts.remove(heart)
            elif heart.check_out_of_window():
                hearts.remove(heart)
            heart.draw(window, heart_img)
        scoreboard.draw(window)
        pygame.display.flip()

    while is_running:
        dt = clock.tick(FPS) / 16
        player.shoot_cooldown -= dt*16
        if ball.player_collision(player):
            blip_sound.play()
        if ball.brick_collision(bricks, hearts):
            break_sound.play()
            scoreboard.score += 10
            if len(bricks) == 0:
                scoreboard.level += 1
                ball.reset()
                player.reset()
                ball.cooldown(1500)
                make_bricks()
        ball.move(dt*ball_vel, dt, blip_sound)
        if ball.check_dead():
            dead_sound.play()
            ball.reset()
            player.reset()
            scoreboard.life -= 1
            if scoreboard.life == 0:
                is_running = False
            ball.cooldown(1500)
        redraw_window()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                pass
        key_pressed = pygame.key.get_pressed()
        if key_pressed[K_RIGHT]:
            player.right(dt*player_vel)
        if key_pressed[K_LEFT]:
            player.left(dt*player_vel)
        if key_pressed[K_SPACE]:
            player.shoot(shot_sound)
Exemple #25
0
#global variables
WIN_HEIGHT = 1024
WIN_WIDTH = 768
SPEED = 5
PX = 956
PY = 320
MOVEMENT = 5

screen = pygame.display.set_mode((WIN_HEIGHT, WIN_WIDTH))
pygame.display.set_caption("Pong")

START_BUTTON = Button((325, 225), (0, 0, 0), (215, 55), "Bonjour % ", 60)
EXIT_BUTTON = Button((890, 25), (0, 0, 0), (180, 55), "Quitter", 45)
PLAYER = Player(PX, PY, MOVEMENT, screen)
BALL = Ball(550, 60, screen, .5, .4, PX, PY)


def redraw_screen():

    START_BUTTON.draw_button(screen)
    EXIT_BUTTON.draw_button(screen)
    pygame.display.flip()
    pygame.display.update()


running = True
while running:

    redraw_screen()
Exemple #26
0
turtle.tracer(0)
turtle.hideturtle()
turtle_gameover = turtle.clone()
runinng =  True 
screen_width = turtle.getcanvas().winfo_width()/2
screen_hight = turtle.getcanvas().winfo_height()/2
turtle.colormode(255)

def random_color():
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    return (r,g,b)

my_ball = Ball(100,35,21,23,50,random_color())

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 = random.randint(-screen_width + maximum_ball_radius,screen_width - maximum_ball_radius)
    y = random.randint(-screen_hight + maximum_ball_radius,screen_hight - maximum_ball_radius)
    dx = random.randint(minimum_ball_dx,maximum_ball_dx)
    dy = random.randint(minimum_ball_dy,maximum_ball_dy)
Exemple #27
0
	def game_mode1():
		#variables
		turtle.tracer(0,0)
		turtle.hideturtle()
		
		RUNNING = True
		SLEEP = 0.0077  
		SCREEN_WIDTH = turtle.getcanvas() . winfo_width()/2
		SCREEN_HEIGHT = turtle.getcanvas() . winfo_height()/2
		player = Ball(0, 0, 25, 25, 15, "blue")
		NUMBER_OF_BALLS = 25
		MINIMUM_BALL_RADIUS = 5
		MAXIMUM_BALL_RADIUS = 25
		MINIMUM_BALL_DX = -3
		MAXIMUM_BALL_DX = 3
		MINIMUM_BALL_DY = -3
		MAXIMUM_BALL_DY = 3
		BALLS = []
		points = 3
		timer = turtle.Turtle()
		timer.hideturtle()
		timer.penup()
		timer.goto(0,300)
		global score
		score = 0
		
		#creating the circles
		for i in range(NUMBER_OF_BALLS):
			x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
			y = 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)
			r  = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
			color = (random.random(),random.random(),random.random())
			while dx == 0:
				dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
			while dy == 0:
				dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
			new_ball = Ball(x,y,dx,dy,r,color)
			BALLS.append(new_ball)








		#checking collisions between 2 balls
		def collide(ball_a, ball_b):
			if ball_a == ball_b:
				return False
			current_x1 = ball_a.xcor()
			current_y1 = ball_a.ycor()

					
			current_x2 = ball_b.xcor()
			current_y2 = ball_b.ycor()

			D = math.sqrt(math.pow((current_x2-current_x1),2) + math.pow((current_y2 - current_y1),2))	
			if D >= ball_a.r + ball_b.r:
				return False
			if D < ball_a.r + ball_b.r:
				return True 

			
		def check_all_balls():
				for ball_a in BALLS:			
					for ball_b in BALLS:
						collide(ball_a, ball_b)
						
						if collide(ball_a,ball_b) == True:
							r1 = ball_a.r
							r2 = ball_b.r

							x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
							y = 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)
							r  = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
							color = (random.random(),random.random(),random.random())
							while dx == 0:
								dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
							while dy == 0:
								dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
							if r1 > r2:
								if r1 < 250:
									ball_a.r = ball_a.r + 4
									
								
									ball_b.goto(x,y)
									ball_b.color(color)
									ball_b.r = r

									ball_a.shapesize(ball_a.r/10)
									ball_b.shapesize(ball_b.r/10)
									
									


							

		points2 = turtle.Turtle()
		points2.hideturtle()
		points2.penup()
		def myball_collision():
				global score
				for ball_a in BALLS:
					collide(ball_a, player)
					if collide(ball_a, player) == True:
						if ball_a.r > player.r:
							quit()
						
						if ball_a.r < player.r:
							if player.r < 250:
								x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
								y = 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)
								r  = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
								color = (random.random(),random.random(),random.random())
								while dx == 0:
									dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
								while dy == 0:
									dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
								ball_a.goto(x,y)
								player.r = player.r + 2
							
								ball_a.color(color)
								ball_a.r = r
								player.shapesize(player.r/10)
								ball_a.shapesize(ball_a.r/10)
								
								points2.goto(0,300)
								score += 1
								points2.clear()
								points2.write(str("Your score is : " + str(score)), move = True, align = "center", font = ("Arial", 20, "normal"))







								return True


		#making the game move 
		def move_all_balls():
			for i in BALLS:
				i.move(SCREEN_WIDTH, SCREEN_HEIGHT)
					
		def movearound(event):
			player.goto(event.x - SCREEN_WIDTH, SCREEN_HEIGHT - event.y)

		turtle.getcanvas() .bind("<Motion>", movearound)

		while RUNNING:
			move_all_balls()
			myball_collision()
			check_all_balls()
			turtle.update()
			time.sleep(SLEEP)
			while points >= 0:
				timer.write(str("GAME STARTS IN : " + str(points) + " SECONDS"), move = True, align = "center", font = ("Arial", 20, "normal"))
				points -= 1
				time.sleep(1)
				timer.clear()
				timer.goto(0, 300)
			



	


		#creating the circles
		for i in range(NUMBER_OF_BALLS):
			x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
			y = 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)
			r  = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
			color = (random.random(),random.random(),random.random())
			while dx == 0:
				dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
			while dy == 0:
				dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
			new_ball = Ball(x,y,dx,dy,r,color)
			BALLS.append(new_ball)








	
		def collide(ball_a, ball_b):
			if ball_a == ball_b:
				return False
			current_x1 = ball_a.xcor()
			current_y1 = ball_a.ycor()

					
			current_x2 = ball_b.xcor()
			current_y2 = ball_b.ycor()

			D = math.sqrt(math.pow((current_x2-current_x1),2) + math.pow((current_y2 - current_y1),2))	
			if D >= ball_a.r + ball_b.r:
				return False
			if D < ball_a.r + ball_b.r:
				return True 

		

							


		def myball_collision():
				for ball_a in BALLS:
					collide(ball_a, player)
					if collide(ball_a, player) == True:
						if ball_a.r > player.r or  ball_a.r < player.r:
							quit()

						
						


		#making the game move 
		def move_all_balls():
			for i in BALLS:
				i.move(SCREEN_WIDTH, SCREEN_HEIGHT)
					
		def movearound(event):
			player.goto(event.x - SCREEN_WIDTH, SCREEN_HEIGHT - event.y)

		turtle.getcanvas() .bind("<Motion>", movearound)

		
		while RUNNING:
			move_all_balls()
			myball_collision()

			turtle.update()
			time.sleep(SLEEP)
			
			while points >= 0:
				timer.write(str("GAME STARTS IN : " + str(points) + " SECONDS"), move = True, align = "center", font = ("Arial", 20, "normal"))
				points -= 1
				time.sleep(1)
				timer.clear()
				timer.goto(0, 300)
Exemple #28
0
#!/usr/bin/env python3
'''
@author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic
@license This software is free - http://www.gnu.org/licenses/gpl.html
'''

import pygame
from arena import Character, Arena
from ball import Ball, Ghost

arena = Arena(16, 12)
Ball(arena, 4, 8)
Ball(arena, 8, 4)
Ghost(arena, 12, 8)

TILE_SIDE = 20
SCREEN_SIZE = (arena.width * TILE_SIDE, arena.height * TILE_SIDE)
BACKGROUND = (255, 255, 255)

pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode(SCREEN_SIZE)
images = {
    Ball.SYMBOL: pygame.image.load('ball.bmp'),
    Ghost.SYMBOL: pygame.image.load('ghost.bmp')
}
# if img size ≠ 20x20: pygame.transform.scale

playing = True
while playing:
    for e in pygame.event.get():
Exemple #29
0
##    chek_colision(ball3 , ball2)   




def moove_all_balls():
    for i in BALLS:
           i.move(SCREEN_WIDTH  , SCREEN_HEIGHT)
        

def chek_my_ball_colision():
    for i in BALLS:
        if chek_colision(BALLS[i] , MY_BALL):


ball2=Ball(x, y, dx, dy,radius , "blue");

ball2.goto(100,100)

BALLS.append(ball2)


ball3=Ball(x, y, dx, dy,radius , "green")
ball3.goto(200,200)
BALLS.append(ball2)

##ball4=Ball(x, y, dx, dy,radius , "oreng")
##BALLS.append(ball4)
##ball4.move(SCREEN_WIDTH , SCREEN_HEIGHT )

ball1=Ball(x, y, dx, dy,radius , "red")
Exemple #30
0
def game_loop():
    paddleA = Paddle(constants.BLACK, 10, 100)
    paddleA.rect.x = 20 
    paddleA.rect.y = 200 

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

    ball = Ball(constants.BLACK,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)

    carryOn = True

    scoreA = 0 
    scoreB = 0 

    while carryOn:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                carryOn = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x: 
                    carryOn=False 
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                while True:
                    event = pygame.event.wait()
                    if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        break

        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            paddleA.moveUp(constants.MOVE_SPEED)
        if keys[pygame.K_s]:
            paddleA.moveDown(constants.MOVE_SPEED)
        if keys[pygame.K_UP]:
            paddleB.moveUp(constants.MOVE_SPEED)
        if keys[pygame.K_DOWN]:
            paddleB.moveDown(constants.MOVE_SPEED)

        all_sprites_list.update()

        if ball.rect.x>=690:
            scoreA+=1
            HelperFunction.playSFX(constants.BOOP)
            ball.rect.x = 345
            ball.rect.y = 195
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x<=0:
            HelperFunction.playSFX(constants.BOOP)
            scoreB+=1
            ball.rect.x = 345
            ball.rect.y = 195
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y>490:
            ball.velocity[1] = -ball.velocity[1]
        if ball.rect.y<0:
            ball.velocity[1] = -ball.velocity[1]

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

        constants.screen.blit(game_background, (0,0))

        pygame.draw.line(constants.screen, constants.BLACK, [349, 0], [349,500], 5)

        all_sprites_list.draw(constants.screen)

        font = pygame.font.Font(None, 74)
        text = font.render(str(scoreA), 1, constants.BLACK)
        constants.screen.blit(text, (250,10))
        text = font.render(str(scoreB), 1, constants.BLACK)
        constants.screen.blit(text,(420,10))

        pygame.display.flip()

        clock.tick(30)