def load_data(self): try: self.score = SCORE["player"] except: SCORE["player"] = 0 self.score = SCORE["player"] self.score_box = Box(self.screen, 10, (100, 10, 400, 50), RED, 4) self.font = pygame.font.Font(None, 34) self.paddleA = Paddle(WHITE, 20, 100) self.paddleA.rect.x = 10 self.paddleA.rect.y = 200 self.paddleB = Paddle(WHITE, 20, 100) self.paddleB.rect.x = 670 self.paddleB.rect.y = 200 self.ball = Ball(WHITE, 10, 10) self.ball.rect.x = 345 self.ball.rect.y = 195 # This will be a list that will contain all the sprites we intend to use in our game. self.all_sprites_list = pygame.sprite.Group() self.liste1 = pygame.sprite.Group() self.liste2 = pygame.sprite.Group() self.liste1.add(self.paddleA) self.liste2.add(self.paddleB) # Add the car to the list of objects self.all_sprites_list.add(self.paddleA) self.all_sprites_list.add(self.paddleB) self.all_sprites_list.add(self.ball)
def load_data(self): self.font = pygame.font.Font(None, 34) self.paddleA = Paddle(WHITE, 20, 100) self.paddleA.rect.x = 10 self.paddleA.rect.y = 200 self.paddleB = Paddle(WHITE, 20, 100) self.paddleB.rect.x = 670 self.paddleB.rect.y = 200 self.ball = Ball(WHITE, 10, 10) self.ball.rect.x = 345 self.ball.rect.y = 195 # This will be a list that will contain all the sprites we intend to use in our game. self.all_sprites_list = pygame.sprite.Group() self.liste1 = pygame.sprite.Group() self.liste2 = pygame.sprite.Group() self.liste1.add(self.paddleA) self.liste2.add(self.paddleB) # Add the car to the list of objects self.all_sprites_list.add(self.paddleA) self.all_sprites_list.add(self.paddleB) self.all_sprites_list.add(self.ball)
def reset(self): self.ball.circle.undraw() # Create circle (ball x, y and radius) self.ball = Ball(self.x,self.y,8) self.ball.circle.draw(self.win) # Starting point of ball self.x = 50 self.y = 350
def main(): run = True ball1 = Ball(WIN, red, 500, 500, 50, 10, [0, 0]) ball2 = Ball(WIN, blue, 500, 500, 20, 10, [0, 0]) table = Table(WIN, [ball1]) held_object = None time = 0 startx = 0 starty = 0 while run: clock.tick(FPS) if held_object: time += 1 WIN.fill(black) table.update() for event in pygame.event.get(): if not held_object: if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() for obj in table.objects: if (x - obj.x)**2 + (y - obj.y)**2 <= obj.radius**2: startx = x starty = y held_object = obj obj.change_hold() if held_object: x, y = pygame.mouse.get_pos() obj.x, obj.y = x, y if event.type == pygame.MOUSEBUTTONUP: obj.V = [ 0.1 * (x - startx) / (0.01 * time), 0.1 * (y - starty) / (0.01 * time) ] time = 0 startx = starty = 0 obj.change_hold() held_object = None pygame.display.update()
def __init__(self): pygame.init() self.HEIGHT = 800 self.WIDTH = 600 self.DISPLAY = pygame.display.set_mode((self.HEIGHT, self.WIDTH)) self.DISPLAY.fill((255,255,255)) self.define_play_area() pygame.display.set_caption("PyPong") #! self.players = {} self.players['p1'] = Player(self.DISPLAY, self.P_AREA, 1000, (255,0,0)) self.players['p2'] = Player(self.DISPLAY, self.P_AREA, 500, (255,0,0)) self.ball = Ball(self.DISPLAY, self.P_AREA, self.get_paddle_pos) self.run_graphics_loop()
def main(self): # Create bricks bricks = [] for i in range(60, 460, 45): x1 = i y1 = 400 y2 = 385 y3 = 370 bricks.append(Brick(x1, y1, "#99FF99")) bricks.append(Brick(x1, y2, "#FF6600")) bricks.append(Brick(x1, y3, "#6699FF")) for brick in bricks: brick.rect.draw(self.win) # Create paddle # Paddle size is 40 wide by 10 high paddle = Paddle() paddle.rect.draw(self.win) # Create circle (ball x, y and radius) self.ball = Ball(self.x, self.y, 8) self.ball.circle.draw(self.win) # The direction values determine amount of movement of ball direction = [BALL_SPEED, BALL_SPEED] while True: if self.ball.is_below_paddle(paddle): self.reset() self.ball.hits_wall(self.gamearea, direction) self.ball.hits_paddle(paddle, direction) for item, brick in enumerate(bricks): self.ball.hits_brick(brick, direction, bricks, item) # Move ball to new location self.ball.move(direction[0], direction[1]) # Check for mouse click on play area if self.win.checkMouse(): # pause for click in window break user_event = self.win.checkKey() if user_event == "Left": paddle.move(-10) elif user_event == "Right": paddle.move(10) # Wait for next loop time.sleep(.003) win.close()
def __init__(self): # Create game area self.win = GraphWin("Game Area", 500, 500) self.win.setCoords(0,0,500,500) # Create circle (ball x, y and radius) self.x = 50 self.y = 350 # Initialize game area self.gamearea = GameArea() self.gamearea.rect.draw(self.win) self.ball = Ball(self.x,self.y,8) self.ball.circle.draw(self.win)
def main(self): # Initialize game area gamearea = GameArea() gamearea.rect.draw(win) # Starting point of ball x = 50 y = 350 # Create bricks bricks = [] for i in range(60,460,45): x1 = i y1 = 400 y2 = 385 y3 = 370 bricks.append(Brick(x1,y1,"#99FF99")) bricks.append(Brick(x1,y2,"#FF6600")) bricks.append(Brick(x1,y3, "#6699FF")) for brick in bricks: brick.rect.draw(win) # Create paddle # Paddle size is 40 wide by 10 high paddle = Paddle() paddle.rect.draw(win) # Use a similar process for creating bricks # Create circle (ball x, y and radius) ball = Ball(x,y,8) ball.circle.draw(win) left = 30 right = 470 top = 470 bottom = 30 # The direction values determine amount of movement of ball direction = [5,5] while True: ball_pt = ball.circle.getCenter() paddle_pt = paddle.rect.getCenter() if ball.y <= 30: pass elif gamearea.collision_detection(ball_pt,direction): direction = gamearea.direction if ball.collision_dect(paddle, direction): print "Hit paddle" for item,brick in enumerate(bricks): if ball.collision_dect(brick, direction): bricks.pop(item) brick.rect.undraw() if not bricks: print "ALL BRICKS ARE GONE" x = direction[0] y = direction[1] ball.circle.move(x, y) ball.x += x ball.y += y time.sleep(.02) # Check for mouse click on play area if win.checkMouse(): # pause for click in window break user_event = win.checkKey() if user_event == "Left": paddle.rect.move(-10,0) paddle.x += -10 elif user_event == "Right": paddle.rect.move(10,0) paddle.x += 10 # Get the bottom left point of rectangle (P1) paddle_pt = paddle.rect.getP1() # Print the x of the bottom left corner win.close()
import math import pygame from pygame.locals import * from classes import Ball, Goal, Wall, scoreSheet # Initialise screen pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption( 'Game name here') # maybe we should come up with a name framerate = 60 # I set this framerate to use later screenWidth, screenHeight = screen.get_size() # Setting up game objects b = Ball( screen, screenWidth / 2, 500 ) #Roy: I changed the location of the ball to the middle of the bottom of the screen g = Goal( screen, 400, 100 ) #Roy: And I added the goal on the top of the screen, also in the middle # distance = math.hypot(b.pos.x-g.pos.x,b.pos.y-g.pos.y) #Roy: This line calculates the distance between the ball and the goal. Thijs: I commented this line out, cause I don't beleive the variable is used here walls = [ Wall(screen, 0, 0, "horizontal", screenWidth), Wall(screen, 0, 0, "vertical", screenHeight), Wall(screen, screenWidth - 10, 0, "vertical", screenHeight), Wall(screen, 0, screenHeight - 10, "horizontal", screenWidth), Wall(screen, 200, 200, "horizontal", 200), Wall(screen, 500, 200, "vertical", 300) ] strokes = 1 sheet = scoreSheet(screen)
import pygame from pygame.locals import * from classes import Ball, Wall # Initialise screen pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Test') framerate = 60 screenWidth, screenHeight = screen.get_size() b = Ball(screen, screenWidth/2, screenHeight/2) walls = [Wall(screen, 0, 0, "horizontal", screenWidth), Wall(screen, 0, 0, "vertical", screenHeight), Wall(screen, screenWidth-10, 0, "vertical", screenHeight), Wall(screen, 0, screenHeight-10, "horizontal", screenWidth), Wall(screen, 200, 200, "horizontal", 200), Wall(screen, 500, 200, "vertical", 300)] loop = True while loop: for event in pygame.event.get(): if event.type == QUIT: loop = False if event.type == MOUSEBUTTONDOWN: mousePos = pygame.math.Vector2(event.pos) acc = (mousePos - b.pos).normalize() acc *= 3 b.accelerate(acc) screen.fill((0, 127, 50))
class PvP: def __init__(self, screen): self.screen = screen self.clock = pygame.time.Clock() self.running = True self.scoreA = 0 self.scoreB = 0 self.load_data() def draw_text(self, text, font_name, size, color, x, y, align="nw"): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, color) text_rect = text_surface.get_rect() if align == "nw": text_rect.topleft = (x, y) if align == "ne": text_rect.topright = (x, y) if align == "sw": text_rect.bottomleft = (x, y) if align == "se": text_rect.bottomright = (x, y) if align == "n": text_rect.midtop = (x, y) if align == "s": text_rect.midbottom = (x, y) if align == "e": text_rect.midright = (x, y) if align == "w": text_rect.midleft = (x, y) if align == "center": text_rect.center = (x, y) self.screen.blit(text_surface, text_rect) def load_data(self): self.font = pygame.font.Font(None, 34) self.paddleA = Paddle(WHITE, 20, 100) self.paddleA.rect.x = 10 self.paddleA.rect.y = 200 self.paddleB = Paddle(WHITE, 20, 100) self.paddleB.rect.x = 670 self.paddleB.rect.y = 200 self.ball = Ball(WHITE, 10, 10) self.ball.rect.x = 345 self.ball.rect.y = 195 # This will be a list that will contain all the sprites we intend to use in our game. self.all_sprites_list = pygame.sprite.Group() self.liste1 = pygame.sprite.Group() self.liste2 = pygame.sprite.Group() self.liste1.add(self.paddleA) self.liste2.add(self.paddleB) # Add the car to the list of objects self.all_sprites_list.add(self.paddleA) self.all_sprites_list.add(self.paddleB) self.all_sprites_list.add(self.ball) def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False keys = pygame.key.get_pressed() if keys[pygame.K_w]: self.paddleA.moveUp(5) if keys[pygame.K_s]: self.paddleA.moveDown(5) if keys[pygame.K_UP]: self.paddleB.moveUp(5) if keys[pygame.K_DOWN]: self.paddleB.moveDown(5) def update(self): self.all_sprites_list.update() if self.ball.rect.x >= 680: self.scoreA += 1 self.ball.velocity[0] = -self.ball.velocity[0] if self.ball.rect.x <= 10: self.scoreB += 1 self.ball.velocity[0] = -self.ball.velocity[0] if self.ball.rect.y > 490: self.ball.velocity[1] = -self.ball.velocity[1] if self.ball.rect.y < 0: self.ball.velocity[1] = -self.ball.velocity[1] # Detect collisions between the ball and the paddles if pygame.sprite.spritecollide(self.ball, self.liste1, False) and self.ball.velocity[0] < 0: print("LEFT --", self.ball.velocity) self.ball.bounce() if pygame.sprite.spritecollide(self.ball, self.liste2, False) and self.ball.velocity[0] > 0: print("RIGHT --", self.ball.velocity) self.ball.bounce() def draw(self): self.screen.fill(DARKBLUE) pygame.draw.line(self.screen, WHITE, [349, 0], [349, 500], 5) self.all_sprites_list.draw(self.screen) self.draw_text(f"{self.scoreA}", None, 50, WHITE, 250, 10) self.draw_text(f"{self.scoreB}", None, 50, WHITE, 420, 10) pygame.display.update() def run(self): while self.running: self.dt = self.clock.tick(FPS) / 1000.0 self.events() self.update() self.draw()
class Game(): def __init__(self): pygame.init() self.HEIGHT = 800 self.WIDTH = 600 self.DISPLAY = pygame.display.set_mode((self.HEIGHT, self.WIDTH)) self.DISPLAY.fill((255,255,255)) self.define_play_area() pygame.display.set_caption("PyPong") #! self.players = {} self.players['p1'] = Player(self.DISPLAY, self.P_AREA, 1000, (255,0,0)) self.players['p2'] = Player(self.DISPLAY, self.P_AREA, 500, (255,0,0)) self.ball = Ball(self.DISPLAY, self.P_AREA, self.get_paddle_pos) self.run_graphics_loop() def run_graphics_loop(self): run = True while run: # pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False self.draw_black_rect() self.draw_play_area() self.handle_keypress(event) self.update_players() self.ball.update() self.ball.is_on_edge() self.check_bounce() pygame.display.update() pygame.quit() def update_players(self): for player in self.players.values(): player.update() def handle_keypress(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: self.players['p1'].paddle.pos += 10 elif event.key == pygame.K_DOWN: self.players['p1'].paddle.pos -= 10 elif event.key == pygame.K_RIGHT: self.players['p2'].paddle.pos += 10 elif event.key == pygame.K_LEFT: self.players['p2'].paddle.pos -= 10 def define_play_area(self): delta = int(((self.HEIGHT+self.WIDTH) / 2 ) / 4) self.P_AREA = {} self.P_AREA['x'] = delta self.P_AREA['y'] = delta self.P_AREA['w'] = self.HEIGHT-2*delta self.P_AREA['h'] = self.WIDTH-2*delta def draw_black_rect(self): delta = 10 pos = (delta, delta) dim = (self.HEIGHT - 2*delta, self.WIDTH - 2*delta) pygame.draw.rect(self.DISPLAY, (0,0,255), pygame.Rect(*pos, *dim)) def draw_play_area(self): pygame.draw.rect(self.DISPLAY, (0,0,0), pygame.Rect([val for val in self.P_AREA.values()])) @property def get_paddle_pos(self): paddle_pos_lst = [] for player in self.players.values(): paddle_pos_lst.append(player.paddle.pos) return paddle_pos_lst def curr_player(self): pass def check_bounce(self): for player in self.players.values(): if self.ball.is_on_paddle(player.paddle.centers): print('bouncy bounce') self.ball.velocity *= -1
def __init__(self): # Set current game mode self.singleplayer = False # Creating the window self.win = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption("Football") # setting the favicon self.favicon = pygame.image.load("data/img/favicon.png") pygame.display.set_icon(self.favicon) # loading the bg image self.bgimg = pygame.image.load("data/img/background.png") # loading ball image self.ball = pygame.image.load("data/img/ball.png") # loading the net image self.netimg1 = pygame.image.load("data/img/net1.png") self.netimg2 = pygame.image.load("data/img/net2.png") # loading fonts self.font = pygame.font.SysFont('courier', 40, True) self.buttonFont = pygame.font.SysFont('Ariel', 25, False) # loading the sound files self.goalSound = pygame.mixer.Sound("data/wav/goal.wav") self.selectSound = pygame.mixer.Sound("data/wav/select.wav") self.clock = pygame.time.Clock() # Player Instances self.player1 = Player(100, SCREENHEIGHT - PLAYERHEIGHT, RED, PLAYERWIDTH, PLAYERHEIGHT, PLAYERSPEED, self.win) self.player2 = Player(SCREENWIDTH - 100 - PLAYERWIDTH, SCREENHEIGHT - PLAYERHEIGHT, BLUE, PLAYERWIDTH, PLAYERHEIGHT, PLAYERSPEED, self.win) # Ball Instance self.ball = Ball((SCREENWIDTH // 2) - (BALLRADIUS // 2), (SCREENHEIGHT // 2) - BALLRADIUS, self.ball, BALLRADIUS, BALLSPEED, self.win) self.ball.randDirec(False, True) # Net Instances self.net1 = Net(20, SCREENHEIGHT - NETHEIGHT, self.netimg1, NETWIDTH, NETHEIGHT, self.win) self.net2 = Net(SCREENWIDTH - 20 - NETWIDTH, SCREENHEIGHT - NETHEIGHT, self.netimg2, NETWIDTH, NETHEIGHT, self.win) # Crossbar Instances self.net1Top = ColliderBox(0, SCREENHEIGHT - NETHEIGHT - 10, NETWIDTH + 21, 10, self.win) self.net2Top = ColliderBox(SCREENWIDTH - 20 - NETWIDTH, SCREENHEIGHT - NETHEIGHT - 10, NETWIDTH + 20, 10, self.win) # Buttons to change gamemode # NOT SINGLEPLAYER MEANS SINGLEPLAYER BUTTON IS OFF # SINGLEPLAYER == TRUE MEANS SINGLEPLAYER BUTTON IS ON self.spButton = Button(MODE_BUTTONS_X, MODE_BUTTONS_Y, MODE_BUTTON_WIDTH, MODE_BUTTON_HEIGHT, self.win, lambda: self.switchMode("singleplayer"), GREEN, RED, not self.singleplayer, self.buttonFont, "Singleplayer") self.mpButton = Button(MODE_BUTTONS_X + MODE_BUTTON_WIDTH + 20, MODE_BUTTONS_Y, MODE_BUTTON_WIDTH, MODE_BUTTON_HEIGHT, self.win, lambda: self.switchMode("multiplayer"), GREEN, RED, self.singleplayer, self.buttonFont, "Multiplayer") # Array of all items self.items = [ self.ball, self.player1, self.player2, self.net1, self.net1Top, self.net2, self.net2Top, self.spButton, self.mpButton ]
class Game(object): # Start of shit def __init__(self): # Set current game mode self.singleplayer = False # Creating the window self.win = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption("Football") # setting the favicon self.favicon = pygame.image.load("data/img/favicon.png") pygame.display.set_icon(self.favicon) # loading the bg image self.bgimg = pygame.image.load("data/img/background.png") # loading ball image self.ball = pygame.image.load("data/img/ball.png") # loading the net image self.netimg1 = pygame.image.load("data/img/net1.png") self.netimg2 = pygame.image.load("data/img/net2.png") # loading fonts self.font = pygame.font.SysFont('courier', 40, True) self.buttonFont = pygame.font.SysFont('Ariel', 25, False) # loading the sound files self.goalSound = pygame.mixer.Sound("data/wav/goal.wav") self.selectSound = pygame.mixer.Sound("data/wav/select.wav") self.clock = pygame.time.Clock() # Player Instances self.player1 = Player(100, SCREENHEIGHT - PLAYERHEIGHT, RED, PLAYERWIDTH, PLAYERHEIGHT, PLAYERSPEED, self.win) self.player2 = Player(SCREENWIDTH - 100 - PLAYERWIDTH, SCREENHEIGHT - PLAYERHEIGHT, BLUE, PLAYERWIDTH, PLAYERHEIGHT, PLAYERSPEED, self.win) # Ball Instance self.ball = Ball((SCREENWIDTH // 2) - (BALLRADIUS // 2), (SCREENHEIGHT // 2) - BALLRADIUS, self.ball, BALLRADIUS, BALLSPEED, self.win) self.ball.randDirec(False, True) # Net Instances self.net1 = Net(20, SCREENHEIGHT - NETHEIGHT, self.netimg1, NETWIDTH, NETHEIGHT, self.win) self.net2 = Net(SCREENWIDTH - 20 - NETWIDTH, SCREENHEIGHT - NETHEIGHT, self.netimg2, NETWIDTH, NETHEIGHT, self.win) # Crossbar Instances self.net1Top = ColliderBox(0, SCREENHEIGHT - NETHEIGHT - 10, NETWIDTH + 21, 10, self.win) self.net2Top = ColliderBox(SCREENWIDTH - 20 - NETWIDTH, SCREENHEIGHT - NETHEIGHT - 10, NETWIDTH + 20, 10, self.win) # Buttons to change gamemode # NOT SINGLEPLAYER MEANS SINGLEPLAYER BUTTON IS OFF # SINGLEPLAYER == TRUE MEANS SINGLEPLAYER BUTTON IS ON self.spButton = Button(MODE_BUTTONS_X, MODE_BUTTONS_Y, MODE_BUTTON_WIDTH, MODE_BUTTON_HEIGHT, self.win, lambda: self.switchMode("singleplayer"), GREEN, RED, not self.singleplayer, self.buttonFont, "Singleplayer") self.mpButton = Button(MODE_BUTTONS_X + MODE_BUTTON_WIDTH + 20, MODE_BUTTONS_Y, MODE_BUTTON_WIDTH, MODE_BUTTON_HEIGHT, self.win, lambda: self.switchMode("multiplayer"), GREEN, RED, self.singleplayer, self.buttonFont, "Multiplayer") # Array of all items self.items = [ self.ball, self.player1, self.player2, self.net1, self.net1Top, self.net2, self.net2Top, self.spButton, self.mpButton ] # Button to change gamemode func def switchMode(self, mode): self.selectSound.play() if mode == "multiplayer": self.singleplayer = False self.spButton.active = True self.mpButton.active = False elif mode == "singleplayer": self.singleplayer = True self.mpButton.active = True self.spButton.active = False # Function to reset and play the score sound def onScore(self): self.goalSound.play() for player in (self.player1, self.player2): player.jumpCount = 10 player.isJump = False for item in self.items: item.x = item.initx item.y = item.inity # Function to draw the next frame def drawNewFrame(self): self.win.blit(self.bgimg, (0, 0)) scr1 = self.font.render(str(self.player1.score), 1, RED) self.win.blit(scr1, (10, 10)) scr2 = self.font.render(str(self.player2.score), 1, BLUE) self.win.blit(scr2, ((SCREENWIDTH - scr2.get_width() - 10), 10)) for item in self.items: item.draw() pygame.display.update() # Function that processes the events of the game on each frame def update(self): # Check if the user wants to change the game mode self.spButton.check_pressed() self.mpButton.check_pressed() # Get a list of the currently selected keyboard keys keys = pygame.key.get_pressed() # Check if the user wants to jump if keys[pygame.K_a] and self.player1.x > 0: self.player1.x -= self.player1.vel if keys[pygame.K_d] and self.player1.x < (SCREENWIDTH - PLAYERWIDTH): self.player1.x += self.player1.vel self.player1.jumpLoop(keys[pygame.K_w]) # Run the AI frame if it is singleplayer if self.singleplayer: if self.ball.x + 20 < self.player2.x: self.player2.x -= self.player2.vel // 1.5 if self.ball.x + 20 > self.player2.x: self.player2.x += self.player2.vel // 1.5 self.player2.jumpLoop((self.player2.x - self.ball.x) > -40 and (self.player2.x - self.ball.x) < 40 and self.player2.y > self.ball.y) else: # If not, allow player 2 to move should they choose to if keys[pygame.K_LEFT] and self.player2.x > 0: self.player2.x -= self.player2.vel if keys[pygame.K_RIGHT] and self.player2.x < (SCREENWIDTH - PLAYERWIDTH): self.player2.x += self.player2.vel self.player2.jumpLoop(keys[pygame.K_UP]) # 0 = Up, 1 = Left, 2 = Down, 3 = Right if 0 in self.ball.direc: self.ball.y -= self.ball.vel // self.ball.div if 1 in self.ball.direc: self.ball.x -= self.ball.vel if 2 in self.ball.direc: self.ball.y += self.ball.vel // self.ball.div if 3 in self.ball.direc: self.ball.x += self.ball.vel if self.ball.x <= (0 + self.ball.radius): self.ball.bounceHorz() self.ball.x = 1 + self.ball.radius if self.ball.x >= (SCREENWIDTH - (self.ball.radius // 2)): self.ball.bounceHorz() self.ball.x = (SCREENWIDTH - (self.ball.radius // 2)) - 1 if self.ball.y <= (0 + self.ball.radius): self.ball.bounceVert() self.ball.y = 1 + self.ball.radius if self.ball.y >= (SCREENHEIGHT - (self.ball.radius // 2)): self.ball.bounceVert() self.ball.y = (SCREENHEIGHT - (self.ball.radius // 2)) - 1 if self.ball.collisionCooldown > 0: self.ball.collisionCooldown -= 1 else: for colliderHit in (self.player1, self.player2, self.net1, self.net1Top, self.net2, self.net2Top): if self.ball.y - self.ball.radius < colliderHit.hitbox[ 1] + colliderHit.hitbox[3]: if self.ball.y + self.ball.radius > colliderHit.hitbox[1]: if self.ball.x + self.ball.radius > colliderHit.hitbox[ 0]: if self.ball.x - self.ball.radius < colliderHit.hitbox[ 0] + colliderHit.hitbox[2]: if colliderHit == self.net1: self.player2.score += 1 self.ball.setDiv() self.onScore() elif colliderHit == self.net2: self.player1.score += 1 self.ball.setDiv() self.onScore() else: self.ball.bounceHorz() self.ball.bounceVert() self.ball.collisionCooldown = 10 # Function to poll necessary pygame events def pollEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.run = False # Main Program Loop def mainloop(self): self.run = True while self.run: self.drawNewFrame() # Draw next frame self.clock.tick(60) # Delay by 1 60th of a second self.update() # Process current frame self.pollEvents() # Poll events
def game_loop(): block_arr = [] rect_arr = [] welcome() #loop variables exit_game = False game_start = False game_over = False ball_thrown = False platform = pygame.Rect(screen_width/2 , screen_height/2+200 , 100,10) ball = Ball([screen_width/2+30 , screen_height/2 + 200-7] , 7 , 1.5 , [math.cos(math.pi/4) , math.sin(math.pi/4)]) score = 0 lifes = 1 #make list of blocks for _ in range(no_of_block): temp = Block([random.randint(100,800) , random.randint(50,300) , block_size , block_size] , Colors.rand_col() , 40) rect_arr.append(pygame.Rect(temp.list_info[0] , temp.list_info[1] , block_size , block_size)) block_arr.append(temp) #game loop while not exit_game: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game = True pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: game_start = True elif event.key == pygame.K_ESCAPE: game_start = False ball_thrown = False platform = pygame.Rect(screen_width / 2, screen_height / 2 + 200, 100, 10) ball = Ball([screen_width / 2 + 30, screen_height / 2 + 200 - 7], 7, 1.5 ,[math.cos(math.pi/4) , math.sin(math.pi/4)]) if event.type == pygame.MOUSEBUTTONDOWN and game_start: ball_thrown = True gameWindow.fill(Colors.white) if game_over: temp_color = Colors.rand_col() while not exit_game: gameWindow.fill(temp_color) text_screen("press x to restart", Colors.black, 350, 300) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_x: game_loop() pygame.draw.rect(gameWindow , Colors.black , platform) #draw platform tr = pygame.draw.circle(gameWindow , Colors.black ,ball.center , ball.radius) #draw circle for i in range(len(block_arr)): if block_arr[i].color == (0,0,0): if(random.randint(1,5) == 1): temp = Block([random.randint(100, 800), random.randint(50, 300), block_size, block_size],Colors.rand_col(), 40) rect_arr[i] = pygame.Rect(temp.list_info[0] , temp.list_info[1] , block_size , block_size) block_arr[i] = temp else: pygame.draw.rect(gameWindow, block_arr[i].color, block_arr[i].list_info) text_screen(f"Score {score}", Colors.red, 330, 525) text_screen(f"Lifes {lifes}", Colors.red, 530, 525) pygame.display.update() #move platform pos = pygame.mouse.get_pos() x = pos[0] y = pos[1] if game_start == True: try: platform.left = platform.left + 8*(x-platform.left)/((x-platform.left)*(x-platform.left) + (y-platform.top)*(y-platform.top) )**0.5 except: pass #move ball if ball_thrown == False: ball.center = [platform.left+platform.width/2 , platform.top-7] else: temp_x = ball.center[0] temp_y = ball.center[1] ball.center = [temp_x + ball.direction[0]*ball.magnitude , temp_y - ball.direction[1]*ball.magnitude] if (ball.center[0] >= 893 and ball.direction[0] >0) or (ball.center[0] <= 0 and ball.direction[0]<0): ball.direction[0] = -1*ball.direction[0] if ball.center[1] <= 0: if (ball.center[0] >= 893 and ball.direction[0] >0) or (ball.center[0] <= 0 and ball.direction[0]<0): ball.direction = [math.cos(math.pi/4) , math.sin(math.pi/4)] else: ball.direction[1] = -1*ball.direction[1] if pygame.Rect.colliderect(tr , platform) and ball.direction[1] <0: ball.direction[1] = -1*ball.direction[1] if ball.direction[0] == 0: ball.direction[0]= 1.5 if ball.direction[1] == 0: ball.direction = 1.5 #collision with block for i in range(no_of_block): if pygame.Rect.colliderect(tr , rect_arr[i]) and block_arr[i].color != (0,0,0): if abs(tr.left - rect_arr[i].right) <= 3: ball.direction[0] = -1*ball.direction[0] elif abs(tr.right - rect_arr[i].left) <= 3: ball.direction[0] = -1*ball.direction[0] elif abs(tr.top - rect_arr[i].bottom) <= 3: ball.direction[1] = -1*ball.direction[1] elif abs(tr.bottom - rect_arr[i].top) <= 3: ball.direction[1] = -1*ball.direction[1] temp0 = block_arr[i].color[0] temp1 = block_arr[i].color[1] temp2 = block_arr[i].color[2] block_arr[i].color = (int(temp0/1.2) , int(temp1/1.2) , int(temp2/1.2)) if(random.randint(1,20) == 1): score+=1 #ball falls down if ball.center[1]>= 600: game_start = False ball_thrown = False lifes-=1 if lifes == 0: game_over = True platform = pygame.Rect(screen_width / 2, screen_height / 2 + 200, 100, 10) ball = Ball([screen_width / 2 + 30, screen_height / 2 + 200 - 7], 7, 1.5,[math.cos(math.pi / 4), math.sin(math.pi / 4)]) clock.tick(fps)
class PvE: def __init__(self, screen): self.screen = screen self.clock = pygame.time.Clock() self.running = True self.countdown = True self.end = False self.timer_color = WHITE self.count = 4 self.time = 5 self.scoreA = 0 self.scoreB = 0 self.load_data() def draw_text(self, text, font_name, size, color, x, y, align="nw"): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, color) text_rect = text_surface.get_rect() if align == "nw": text_rect.topleft = (x, y) if align == "ne": text_rect.topright = (x, y) if align == "sw": text_rect.bottomleft = (x, y) if align == "se": text_rect.bottomright = (x, y) if align == "n": text_rect.midtop = (x, y) if align == "s": text_rect.midbottom = (x, y) if align == "e": text_rect.midright = (x, y) if align == "w": text_rect.midleft = (x, y) if align == "center": text_rect.center = (x, y) self.screen.blit(text_surface, text_rect) def load_data(self): try: self.score = SCORE["player"] except: SCORE["player"] = 0 self.score = SCORE["player"] self.score_box = Box(self.screen, 10, (100, 10, 400, 50), RED, 4) self.font = pygame.font.Font(None, 34) self.paddleA = Paddle(WHITE, 20, 100) self.paddleA.rect.x = 10 self.paddleA.rect.y = 200 self.paddleB = Paddle(WHITE, 20, 100) self.paddleB.rect.x = 670 self.paddleB.rect.y = 200 self.ball = Ball(WHITE, 10, 10) self.ball.rect.x = 345 self.ball.rect.y = 195 # This will be a list that will contain all the sprites we intend to use in our game. self.all_sprites_list = pygame.sprite.Group() self.liste1 = pygame.sprite.Group() self.liste2 = pygame.sprite.Group() self.liste1.add(self.paddleA) self.liste2.add(self.paddleB) # Add the car to the list of objects self.all_sprites_list.add(self.paddleA) self.all_sprites_list.add(self.paddleB) self.all_sprites_list.add(self.ball) def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False if not self.end: keys = pygame.key.get_pressed() if keys[pygame.K_w]: self.paddleA.moveUp(5) if keys[pygame.K_s]: self.paddleA.moveDown(5) else: SCORE["player"] = self.scoreA, self.scoreB def update(self): self.all_sprites_list.update() if self.ball.rect.x >= 680: self.scoreA += 1 self.ball.velocity[0] = -self.ball.velocity[0] if self.ball.rect.x <= 10: self.scoreB += 1 self.ball.velocity[0] = -self.ball.velocity[0] if self.ball.rect.y > 490: self.ball.velocity[1] = -self.ball.velocity[1] if self.ball.rect.y < 0: self.ball.velocity[1] = -self.ball.velocity[1] # Here Comes the Bot if self.paddleB.rect.y >= self.ball.rect.y: self.paddleB.moveUp(5) elif self.paddleB.rect.y <= self.ball.rect.y: self.paddleB.moveDown(5) # Detect collisions between the ball and the paddles if pygame.sprite.spritecollide(self.ball, self.liste1, False) and self.ball.velocity[0] < 0: print("LEFT --", self.ball.velocity) self.ball.bounce() if pygame.sprite.spritecollide(self.ball, self.liste2, False) and self.ball.velocity[0] > 0: print("RIGHT --", self.ball.velocity) self.ball.bounce() def draw(self): self.screen.fill(DARKBLUE) if not self.countdown: self.draw_text( f"{int((self.time-self.time_remaining)/60)} : {int(self.time-self.time_remaining)%60}", None, 70, self.timer_color, 300, 20) if not self.end: pygame.draw.line(self.screen, WHITE, [349, 80], [349, 500], 5) if not self.end: self.all_sprites_list.draw(self.screen) if self.countdown: self.draw_text(f"{int(self.count-self.seconds)} ", None, 100, WHITE, 330, 100) self.draw_text(f"{self.scoreA}", None, 50, WHITE, 220, 10) self.draw_text(f"{self.scoreB}", None, 50, WHITE, 450, 10) if self.end: self.score_box.draw() pygame.display.update() def run(self): self.start_ticks = pygame.time.get_ticks() while self.running: self.dt = self.clock.tick(FPS) / 1000.0 self.events() if not self.countdown and not self.end: self.update() else: self.seconds = (pygame.time.get_ticks() - self.start_ticks) / 1000 if self.seconds > self.count: self.countdown = False if not self.end: self.time_remaining = (pygame.time.get_ticks() - self.start_ticks) / 1000 if self.time - self.time_remaining < 0: self.end = True if (self.time - self.time_remaining - 10) <= 0: self.timer_color = RED self.draw()
def main(): ''' Function containing the game loop, no returns or parameters. ''' #Begins by loading the data from the data file with open(r"assets/data.json") as file: data = json.load(file) print(f"Information in settings: {data}") file.close() #if the window is set to fullscreen in the data, file create a fullscreen pygame window if data["resolution"] == [0, 0]: mainGame = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) resolution = pygame.display.get_window_size() else: resolution = data["resolution"] mainGame = pygame.display.set_mode(resolution) #scaling stores the scaling factor for the width of the screen and the length/height scaling = (resolution[0] / 1280, resolution[1] / 720) #world object is the surface that the game is rendered to world = pygame.Surface((1150, 720)) player = Ball(world, (30, 360), ballColorIn=data["ballcolor"]) clock = pygame.time.Clock() #gameState of 0 is the intro screen, following code setups the intro screen and and other variables in the game gameState = 0 buttons = [ Button("QUIT", textIn="QUIT", posIn=(700 * scaling[0], 500 * scaling[1])), Button("PLAY", textIn="Play", posIn=(500 * scaling[0], 500 * scaling[1])), Button("TUTORIAL", textIn="How to Play", posIn=(575 * scaling[0], 600 * scaling[1])), Button("SETTINGS", textIn="Settings", posIn=(1200 * scaling[0], 680 * scaling[1]), fontSizeIn=14) ] if data["highscore"] == -1: highScore = None else: highScore = data["highscore"] score = 0 startTimer = 0 #scales backgrounds to the screen resolution backgrounds = (pygame.transform.scale( pygame.image.load(r"assets/background.jpg"), pygame.display.get_window_size()), pygame.transform.scale( pygame.image.load(r"assets/backgroundTwo.jpg"), pygame.display.get_window_size())) while True: ev = pygame.event.poll() if ev.type == pygame.QUIT or gameState == -1: #if the user clicks the x button or the gameState is -1, it breaks from the main loop and closes game break if gameState == 0: mainGame.blit(backgrounds[0], (0, 0)) for button in buttons: if ev.type == pygame.MOUSEBUTTONDOWN: if button.buttonHit() == "PLAY": #if the player clicks the play button the gameState is set to 1. #setsup map and buttons needed for the game, also creates a variable called starTimer which is used for the timer gameState = 1 walls = generateMap(world) mazeExit = walls[len(walls) - 1] del walls[len(walls) - 1] buttons = [ Button("QUIT", textIn="QUIT", posIn=(630 * scaling[0], 650 * scaling[1])) ] texts = [ TextBox(textIn="Score:", posIn=(1000 * scaling[0], 100 * scaling[1])), TextBox(textIn=f"{score}", posIn=(1000 * scaling[0], 160 * scaling[1])) ] startTimer = time.time() break elif button.buttonHit() == "QUIT": #gameState of -1 is the default gamestate which is called when the user clicks the quit button on any screen gameState = -1 break elif button.buttonHit() == "TUTORIAL": #if the user clicks how to play, it opens a link to a google doc with instructions on how to play webbrowser.open( "https://docs.google.com/document/d/10sVfS0pjQY3BrWsw5jMPi9ZBJNQ-JpQf02bXztE-rAk/edit?usp=sharing" ) elif button.buttonHit() == "SETTINGS": #if the user clicks the settings button, then it sets up the setting screen (gameState = 3) buttons = [ MultiButton(keyIn="RESOLUTION", textIn=("1280x720", "1920x1080", "Fullscreen"), posIn=(700 * scaling[0], 350 * scaling[1])), MultiButton(keyIn="BALLCOLOR", textIn=("Red", "Blue", "Green"), posIn=(700 * scaling[0], 400 * scaling[1])), Button("QUIT", textIn="QUIT", posIn=(630 * scaling[0], 650 * scaling[1])), Button("BACK", textIn="Back", posIn=(200 * scaling[0], 650 * scaling[1])), Button("RESET", textIn="Reset Settings and HighScore", posIn=(500 * scaling[0], 550 * scaling[1])) ] texts = [ TextBox(textIn="Resolution", textBoxColorIn=(30, 30, 30), posIn=(500 * scaling[0], 350 * scaling[1])), TextBox(textIn="Ball Color", textBoxColorIn=(30, 30, 30), posIn=(500 * scaling[0], 400 * scaling[1])), TextBox(textIn="Settings", textBoxColorIn=(30, 30, 30), fontSizeIn=40, posIn=(550 * scaling[0], 100 * scaling[1])), TextBox(textIn= "Restart Game for Changes to Take Effect", textBoxColorIn=(30, 30, 30), fontSizeIn=14, posIn=(500 * scaling[0], 200 * scaling[1])) ] gameState = 3 button.draw(mainGame) elif gameState == 1: #this gamestate is for when the user is actually playing the game #fills the background for the world and blits the background for the display surface world.fill((255, 255, 255)) mainGame.blit(backgrounds[0], (0, 0)) #depending on which direction the player wants to move in, it checks if the player is allowed to move in that direction #if yes, then it moves the player in that direction. keyPressed = pygame.key.get_pressed() if keyPressed[pygame.K_w]: if permissionToMove("UP", walls, player.getPoints()): player.moveUp() if keyPressed[pygame.K_s]: if permissionToMove("DOWN", walls, player.getPoints()): player.moveDown() if keyPressed[pygame.K_a]: if permissionToMove("LEFT", walls, player.getPoints()): player.moveLeft() if keyPressed[pygame.K_d]: if permissionToMove("RIGHT", walls, player.getPoints()): player.moveRight() if (mazeExit.pos[0] <= player.pos[0] <= (mazeExit.pos[0] + mazeExit.wallDimensions[0]) and mazeExit.pos[1] <= player.pos[1] <= (mazeExit.pos[1] + mazeExit.wallDimensions[1])): #if the player goes into the maze exit, it setsup the win screen (gameState = 2) gameState = 2 score = round((time.time() - startTimer) * 100) / 100 if highScore == None or score < highScore: #if the highscore is not set yet or if the score is less than high score then it updates the highscore #also saves highscore to file highScore = score data["highscore"] = highScore with open(r"assets/data.json", "w") as file: json.dump(data, file) file.close() buttons = [ Button("QUIT", textIn="QUIT", posIn=(620 * scaling[0], 650 * scaling[1])), Button("PLAY", textIn="Play Again", posIn=(600 * scaling[0], 500 * scaling[1])) ] texts = [ TextBox(textIn="You Win!", fontSizeIn=40, posIn=(560 * scaling[0], 150 * scaling[1])), TextBox(textIn="Your score is:", fontSizeIn=20, posIn=(525 * scaling[0], 300 * scaling[1])), TextBox(textIn=f"{score}", fontSizeIn=20, posIn=(700 * scaling[0], 300 * scaling[1])), TextBox(textIn="Your highscore is:", fontSizeIn=14, posIn=(545 * scaling[0], 400 * scaling[1])), TextBox(textIn=f"{highScore}", fontSizeIn=14, posIn=(700 * scaling[0], 400 * scaling[1])) ] continue if ev.type == pygame.MOUSEBUTTONDOWN and buttons[0].buttonHit( ) == "QUIT": gameState = -1 #draws all elements on screen mazeExit.drawWall() player.drawBall() for wall in walls: wall.drawWall() buttons[0].draw(mainGame) for text in texts: text.draw(mainGame) score = round((time.time() - startTimer) * 100) / 100 texts[1].changeText(score) #This is where the camera is created #The camera works by creating a surface, and blitting a small portion of the rendered world #to the camera surface, then blitting the camera surface onto the main display surface camera = pygame.Surface((100, 100)) camera.blit(world, (0, 0), (player.pos[0] - 50, player.pos[1] - 50, 100, 100)) camera = pygame.transform.scale( camera, (round(500 * scaling[0]), round(500 * scaling[1]))) mainGame.blit(camera, (390 * scaling[0], 110 * scaling[1])) elif gameState == 2: #gamestate for the win screen mainGame.blit(backgrounds[1], (0, 0)) for button in buttons: button.draw(mainGame) if ev.type == pygame.MOUSEBUTTONDOWN: if button.buttonHit() == "QUIT": gameState = -1 break if button.buttonHit() == "PLAY": #sets the game up again if the user wants to play again gameState = 1 walls = generateMap(world) mazeExit = walls[len(walls) - 1] del walls[len(walls) - 1] buttons = [ Button("QUIT", textIn="QUIT", posIn=(630 * scaling[0], 650 * scaling[1])) ] texts = [ TextBox(textIn="Score:", posIn=(1000 * scaling[0], 100 * scaling[1])), TextBox(textIn=f"{score}", posIn=(1000 * scaling[0], 160 * scaling[1])) ] player.setPos((30, 360)) startTimer = time.time() for text in texts: text.draw(mainGame) elif gameState == 3: #gameState for the settings screen mainGame.blit(backgrounds[1], (0, 0)) for button in buttons: button.draw(mainGame) if ev.type == pygame.MOUSEBUTTONDOWN: if button.buttonHit() == "RESOLUTION": #if the user clicks on the resolution button, it cycles to the next text in the multibutton, #then it stores the selected resolution into the json file #restarting the game is needed to changes to take effect button.changeState() if button.getText() == "1280x720": data["resolution"] = [1280, 720] elif button.getText() == "1920x1080": data["resolution"] = [1920, 1080] elif button.getText() == "Fullscreen": data["resolution"] = [0, 0] with open(r"assets/data.json", "w") as file: json.dump(data, file) file.close() elif button.buttonHit() == "BALLCOLOR": #if the user clicks on the ballcolor button, it cycles to the next option in the multibutton #stores the color into the json file button.changeState() if button.getText() == "Red": data["ballcolor"] = [255, 0, 0] elif button.getText() == "Green": data["ballcolor"] = [0, 255, 0] elif button.getText() == "Blue": data["ballcolor"] = [0, 0, 255] with open(r"assets/data.json", "w") as file: json.dump(data, file) file.close() elif button.buttonHit() == "RESET": #if the user clicks the reset button, it resets all the data in the data file back to original settings #and clears highscore data["resolution"] = [1280, 720] data["highscore"] = -1 data["ballcolor"] = [255, 0, 0] with open(r"assets/data.json", "w") as file: json.dump(data, file) file.close() elif button.buttonHit() == "QUIT": gameState = -1 break elif button.buttonHit() == "BACK": gameState = 0 buttons = [ Button("QUIT", textIn="QUIT", posIn=(700 * scaling[0], 500 * scaling[1])), Button("PLAY", textIn="Play", posIn=(500 * scaling[0], 500 * scaling[1])), Button("TUTORIAL", textIn="How to Play", posIn=(575 * scaling[0], 600 * scaling[1])), Button("SETTINGS", textIn="Settings", posIn=(1200 * scaling[0], 680 * scaling[1]), fontSizeIn=14) ] for text in texts: text.draw(mainGame) #framerate clock.tick(60) mainGame.blit(updateFps(clock), (0, 0)) pygame.display.update() pygame.quit()