Object moves off screen - python

import pygame
#Colors, Allways you need colors!!!!
BLACK = ( 0, 0, 0)
GREEN = ( 0, 255, 0)
WHITE = ( 255, 255, 255)
RED = ( 255, 0, 0)
ORANGE = ( 255, 115, 0)
YELLOW = ( 242, 255, 0)
BROWN = ( 115, 87, 39)
PURPLE = ( 298, 0, 247)
GRAY = ( 168, 168, 168)
PINK = ( 255, 0, 234)
BLUE = ( 0, 0 , 255)
pygame.init()
# Screen
screen = pygame.display.set_mode([700,500])
#Name of thewindow
pygame.display.set_caption("Trial to make PONG")
# Any variables!
x_speed = 0
y_speed = 0
x_coord = 10
y_coord = 250
x = 670
y = 250
other_speed = 0
other_speed2 = 0
rect_x = 50
rect_y = 50
rect_change_x = 5
rect_change_y = 5
clock = pygame.time.Clock()
#Sounds,maybe needed?
#Main Loop__________
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# User pressed down on a key
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key. If so
# adjust speed.
if event.key == pygame.K_UP:
y_speed = -5
elif event.key == pygame.K_DOWN:
y_speed = 5
elif event.key == pygame.K_w:
other_speed2 = -5
elif event.key == pygame.K_s:
other_speed2 = 5
# User let up on a key
elif event.type == pygame.KEYUP:
# If it is an arrow key, reset vector back to zero
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
other_speed2 = 0
# Move the object according to the speed vector.
x_coord += x_speed
y_coord += y_speed
x += x_speed
y += other_speed2
screen.fill(BLACK)
pygame.draw.rect(screen,BLUE,[x_coord,y_coord,20,60])
pygame.draw.rect(screen,YELLOW,[x,y,20,60])
if x > 650 or x < 0:
# Draw the rectangle
pygame.draw.ellipse(screen, BLUE, [rect_x, rect_y, 50, 50])
# Move the rectangle starting point
rect_x += rect_change_x
rect_y += rect_change_y
if rect_x > 650 or rect_x < 0:
rect_change_x = rect_change_x * -1
if rect_y > 450 or rect_y < 0:
rect_change_y = rect_change_y * -1
pygame.display.flip()
clock.tick(60)
pygame.quit()
Ok so I have 2 paddles in this pong game called Blue and yellow rectangle. I can move them but they move off the screen. How do I prevent that. Iv looked online but nothing seems to be working. I thought about putting rectangles around the screen to make a collision point argument where when the Blue/Yellow paddle hit it they won't move any further, but im not sure how to do that with ought ruining the code? Thank you for your help..

You should check to see if it's off the edge of the screen before you change the y coordinate. See
if y_coord + y_speed >= 0 and y_coord + y_speed + 60 <= 500:
y_coord += y_speed
Though as you can see it can get a little confusing to use numbers, which is why you should avoid hard-coding. It's better to have a display_height, display_width, and y_speed variable. Basically, outside of initializing variables, you should only have 0s as numbers. Also, note what happens when you leave out + y_speed in the if statement.

I suggest you start using the Rect class, since it makes handling such cases easy. Also, your code will become cleaner and shorter.
Here's an example of using Rect. Note that I simply use clamp_ip to ensure the player paddles can't leave the screen:
import pygame
BLACK = pygame.color.Color('Black')
YELLOW = pygame.color.Color('Yellow')
BLUE = pygame.color.Color('Blue')
pygame.init()
screen = pygame.display.set_mode([700,500])
screen_rect = screen.get_rect()
pygame.display.set_caption("Trial to make PONG")
blue_rect = pygame.Rect(10, 250, 20, 60)
yellow_rect = pygame.Rect(670, 250, 20, 60)
ball_rect = pygame.Rect(50, 50, 50, 50)
ball_x_speed = 5
ball_y_speed = 5
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# check all pressed keys and move the paddles
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: blue_rect.move_ip(0, -5)
if pressed[pygame.K_DOWN]: blue_rect.move_ip(0, 5)
if pressed[pygame.K_w]: yellow_rect.move_ip(0, -5)
if pressed[pygame.K_s]: yellow_rect.move_ip(0, 5)
# ensure paddles stay on screen
blue_rect.clamp_ip(screen_rect)
yellow_rect.clamp_ip(screen_rect)
# move the ball
ball_rect.move_ip(ball_x_speed, ball_y_speed)
# check if the ball needs to change direction
if ball_rect.x + ball_rect.width > screen_rect.width or ball_rect.x < 0:
ball_x_speed = ball_x_speed * -1
if ball_rect.y + ball_rect.height> screen_rect.height or ball_rect.y < 0:
ball_y_speed = ball_y_speed * -1
# draw everything
screen.fill(BLACK)
pygame.draw.ellipse(screen, BLUE, ball_rect)
pygame.draw.rect(screen,BLUE, blue_rect)
pygame.draw.rect(screen,YELLOW, yellow_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()

It seems like you're setting the height of the screen to be 500 pixels. Maybe you could check if your paddles are at the limit of the screen before moving them.
newY = y_coord + y_speed
if newY >= 0 and newY + PADDLE_HEIGHT < SCREEN_HEIGHT:
y_coord = newy

Related

If I have two rectangles of different sizes(10 by 10 and 20 by 20) in Pygame, how can I figure out when the two rectangles collide?

I am unable to detect when two rectangles of different sizes collide.
I've tried, "if x == obj_x and y == obj_y:" where x is one rectangle's x-value, obj_x is the other rectangle's x value, and the same for the y-values.
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
display_width = 500
display_height = 500
screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Avoid')
x_change = 0
y_change = 0
FPS = 30
block_size = 10
font = pygame.font.SysFont(None, 25)
smallfont = pygame.font.SysFont("comicsansms",25)
def showLives(lives):
text = smallfont.render("Lives: "+str(lives), True, white)
screen.blit(text, [0,0])
def message_to_screen(msg,color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [100,250])
clock = pygame.time.Clock()
def gameLoop():
gameExit = False
gameOver = False
x = 250
y = 425
x_change = 0
y_change = 0
obj_speed = 5
obj_y = 0
obj_x = 0
obj2_y = 0
obj2_x = 0
obj2_speed = 3
lives = 3
while not gameExit:
while gameOver == True:
screen.fill(white)
message_to_screen("Game Over, Press C to play again or Q to quit", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
x_change = 0
y_change = 0
if x > 500-block_size:
x-=block_size
if x < 0+block_size:
x+=block_size
# if x >= display_width-block_size-block_size or x < 0:
# gameOver = True
obj_y = obj_y + obj_speed
if obj_y > display_height:
obj_x = random.randrange(0, display_width-block_size)
obj_y = -25
obj2_y = obj2_y + obj2_speed
if obj2_y > display_height:
obj2_x = random.randrange(1, display_width-block_size)
obj2_y = -27
x += x_change
y += y_change
screen.fill(black)
pygame.draw.rect(screen,white, [obj_x,obj_y,20,20])
pygame.draw.rect(screen,white, [obj2_x,obj2_y,20,20])
pygame.draw.rect(screen, red, [x,y,block_size,block_size])
showLives(lives)
pygame.display.update()
if x == obj_x and y == obj_y:
lives -= 1
if lives == 0:
gameOver = True
clock.tick(FPS)
pygame.quit()
quit()
gameLoop()
I want the program to detect when any part of the rectangles collide instead of just detecting when one point on each of the rectangles collide.
PyGame has class pygame.Rect() to keep rectangle's position and size. It uses it to draw images/sprites and check collision between sprites.
x = 250
y = 425
obj_y = 0
obj_x = 0
rect_1 = pygame.Rect(x, y, 10, 10)
rect_2 = pygame.Rect(obj_x, obj_y, 20, 20)
and then you can check collision
rect_1.colliderect(rect_2)
You can also use it to draw rectangle on screen
pygame.draw.rect(screen, white, rect_2)
pygame.draw.rect(screen, red, rect_1)
You can also use it to check collision between rectangle and point - ie. to check if button was clicked by mouse
button_rect.collidepoint(event.pos)
To change values in rectangle you have rect_1.x, rect_1.y, rect_1.width, rect_1.height but also
x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h
Some of them takes tuple with (x, y)
for example: center rectangle on screen
rect_1.center = (display_width//2, display_height//2)
or event using screen
rect_1.center = screen.get_rect().center
OR center text on screen
screen_text_rect = screen_text.get_rect()
screen_text_rect.center = screen.get_rect().center
screen.blit(screen_text, screen_text_rect)

Forwards movement in a sprite

I have been making a game in pygame where 2 squares hit a ball around score when they hit it into a net. I have added a minimalistic version of the code underneath.
When the ball hits the square, I am trying to make the ball go forward and a bit upwards before coming back down due to gravity in a realistic-looking way. Is there any possible way of doing this?
import pygame as pg
from pygame.math import Vector2
pg.init()
LIGHTBLUE = pg.Color('lightskyblue2')
DARKBLUE = pg.Color(11, 8, 69)
screen = pg.display.set_mode((800, 600))
width, height = screen.get_size()
clock = pg.time.Clock()
pg.display.set_caption("Super Acrobatic Rocket Powered Battle Polygons(SARPBP)")
x = 740
y = 500
x2 = 395
y2 = 15
x_change = 0
y_change = 0
bluespeed = 5
ground_pos = 70
on_ground = False
bluecar = pg.Surface((60, 30))
bluecar.fill((0,0,255))
bluegoal = pg.Surface((60,150))
bluegoal.fill((0,0,255))
BALL = pg.Surface((30, 30), pg.SRCALPHA)
pg.draw.circle(BALL, [0,0,0], [15, 15], 15)
ball_pos = Vector2(x2, y2)
ballrect = BALL.get_rect(center=ball_pos)
ball_vel = Vector2(0, 0)
ball_mask = pg.mask.from_surface(BALL)
mask_blue = pg.mask.from_surface(bluecar)
mask_ball = pg.mask.from_surface(BALL)
pos_blue = Vector2(x,y)
bluerect = bluecar.get_rect(center = pos_blue)
vel_blue = Vector2(bluespeed,0)
# A constant value that you add to the y_change each frame.
GRAVITY = .5
GRAVITY2 = .5
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_a:
x_change = -5
elif event.key == pg.K_d:
x_change = 5
elif event.key == pg.K_w:
if on_ground: # Only jump if the player is on_ground.
y_change = -12
on_ground = False
elif event.type == pg.KEYUP:
if event.key == pg.K_a and x_change < 0:
x_change = 0
elif event.key == pg.K_d and x_change > 0:
x_change = 0
ball_vel.y += GRAVITY # Accelerate downwards.
ball_pos += ball_vel # Move the ball.
ballrect.center = ball_pos
# Bounce when the ball touches the bottom of the screen.
if ballrect.bottom >= height - ground_pos:
# Just invert the y-velocity to bounce.
ball_vel.y *= -0.7 # Change this value to adjust the elasticity.
# Don't go below the ground.
ballrect.bottom = height - ground_pos
ball_pos.y = ballrect.centery
# Add the GRAVITY value to y_change, so that
# the object moves faster each frame.
y_change += GRAVITY
x += x_change
y += y_change
# Stop the object when it's near the bottom of the screen.
if y >= height - 100:
y = height - 100
y_change = 0
on_ground = True
if x == 0:
x = 5
elif x == 740:
x = 735
offset_blue = bluerect[0] - ballrect[0], bluerect[1] - ballrect[1]
overlap_blue = mask_ball.overlap(mask_blue, offset_blue)
if overlap_blue: # Blue collides with the ball.
ball_vel = Vector2(vel_blue) * 1.4
# Draw everything.
screen.fill(LIGHTBLUE)
pg.draw.line(screen, (0, 0, 0), (0, height-70), (width, height-70))
screen.blit(bluecar, (x, y))
screen.blit(BALL, ballrect)
pg.display.update()
clock.tick(60)
pg.quit()
You have to update the position of the blue rect as well each frame or it will stay at it's original position and the collision detection won't work.
Then I suggest getting rid of the x, y, x2, y2, x_change, y_change variables, since you can just use the vectors pos_blue and vel_blue.
When the player collides with the ball you can set the y-component of the ball's velocity to some negative value, so that it moves up (I just set the x-component to the player's velocity.x here if the player is moving).
ball_vel = Vector2(vel_blue.x, -17)
Note that you have to use surfaces with an alpha channel or the pygame.mask.from_surface won't work, therefore I pass pygame.SRCALPHA as the second argument to pygame.Surface (you could also call convert_alpha() or set_colorkey()).
import pygame as pg
from pygame.math import Vector2
pg.init()
LIGHTBLUE = pg.Color('lightskyblue2')
DARKBLUE = pg.Color(11, 8, 69)
screen = pg.display.set_mode((800, 600))
width, height = screen.get_size()
clock = pg.time.Clock()
# You need surfaces with an alpha channel for the masks.
bluecar = pg.Surface((60, 30), pg.SRCALPHA)
bluecar.fill((0,0,255))
BALL = pg.Surface((30, 30), pg.SRCALPHA)
pg.draw.circle(BALL, [0,0,0], [15, 15], 15)
ball_pos = Vector2(395, 15)
ballrect = BALL.get_rect(center=ball_pos)
ball_vel = Vector2(0, 0)
mask_blue = pg.mask.from_surface(bluecar)
mask_ball = pg.mask.from_surface(BALL)
pos_blue = Vector2(740, 500) # Just use the pos vector instead of x, y.
bluerect = bluecar.get_rect(center = pos_blue)
vel_blue = Vector2(0, 0) # Replace x_change, y_change with vel_blue.
# A constant value that you add to the y-velocity each frame.
GRAVITY = .5
on_ground = False
ground_y = height - 100
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_a:
vel_blue.x = -5
elif event.key == pg.K_d:
vel_blue.x = 5
elif event.key == pg.K_w:
if on_ground: # Only jump if the player is on_ground.
vel_blue.y = -12
on_ground = False
elif event.type == pg.KEYUP:
if event.key == pg.K_a and vel_blue.x < 0:
vel_blue.x = 0
elif event.key == pg.K_d and vel_blue.x > 0:
vel_blue.x = 0
ball_vel.y += GRAVITY # Accelerate downwards.
ball_pos += ball_vel # Move the ball.
ballrect.center = ball_pos # Update the rect.
# Bounce when the ball touches the bottom of the screen.
if ballrect.bottom >= ground_y:
# Just invert the y-velocity to bounce.
ball_vel.y *= -0.7 # Change this value to adjust the elasticity.
ball_vel.x *= .95 # Friction
# Don't go below the ground.
ballrect.bottom = ground_y
ball_pos.y = ballrect.centery
# Left and right wall collisions.
if ballrect.left < 0:
ball_vel.x *= -1
ballrect.left = 0
ball_pos.x = ballrect.centerx
elif ballrect.right > width:
ball_vel.x *= -1
ballrect.right = width
ball_pos.x = ballrect.centerx
# Add the GRAVITY value to vel_blue.y, so that
# the object moves faster each frame.
vel_blue.y += GRAVITY
pos_blue += vel_blue
bluerect.center = pos_blue # You have to update the rect as well.
# Stop the object when it's near the bottom of the screen.
if bluerect.bottom >= ground_y:
bluerect.bottom = ground_y
pos_blue.y = bluerect.centery
vel_blue.y = 0
on_ground = True
if bluerect.x < 0:
bluerect.x = 0
pos_blue.x = bluerect.centerx
elif bluerect.right > width:
bluerect.right = width
pos_blue.x = bluerect.centerx
offset_blue = bluerect[0] - ballrect[0], bluerect[1] - ballrect[1]
overlap_blue = mask_ball.overlap(mask_blue, offset_blue)
if overlap_blue: # Blue collides with the ball.
if vel_blue.x != 0: # Player is moving.
ball_vel = Vector2(vel_blue.x, -17)
else: # If the player is standing, I just update the vel.y.
ball_vel.y = -17
# Draw everything.
screen.fill(LIGHTBLUE)
pg.draw.line(screen, (0, 0, 0), (0, ground_y), (width, ground_y))
screen.blit(bluecar, bluerect) # Blit it at the rect.
screen.blit(BALL, ballrect)
pg.display.update()
clock.tick(60)
pg.quit()

Object bounce and movement [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have been making a game where 2 people try to score a goal on a net, but to do so, the ball must move and bounce. I would like the ball to move forward and upwards at a realistic angle, then bounce on the ground a few times before becoming stationary again. I'm not sure how to achieve this, my code is below, I really hope someone can edit it to work.
When I run the code, I get the following error
TypeError: unsupported operand type(s) for +=: 'pygame.math.Vector2' and 'int'(for the line "ball_vel += x2")
import pygame as pg
from pygame.math import Vector2
pg.init()
LIGHTBLUE = pg.Color('lightskyblue2')
screen = pg.display.set_mode((800, 600))
width, height = screen.get_size()
clock = pg.time.Clock()
pg.display.set_caption("Super Acrobatic Rocket Powered Battle Polygons(SARPBP)")
x = 740
y = 0
x2 = 370
y2 = 500
x_change = 0
y_change = 0
bluespeed = 5
on_ground = False
bluecar = pg.Surface((60, 30))
bluecar.fill((0,0,255))
BALL = pg.Surface((30, 30), pg.SRCALPHA)
pg.draw.circle(BALL, [0,0,0], [15, 15], 15)
ball_pos = Vector2(x2, y2)
ballrect = BALL.get_rect(center=ball_pos)
ball_vel = Vector2(0, 0)
ball_mask = pg.mask.from_surface(BALL)
mask_blue = pg.mask.from_surface(bluecar)
mask_ball = pg.mask.from_surface(BALL)
pos_blue = Vector2(x,y)
bluerect = bluecar.get_rect(center = pos_blue)
vel_blue = Vector2(bluespeed,0)
# A constant value that you add to the y_change each frame.
GRAVITY = .5
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_a:
x_change = -5
elif event.key == pg.K_d:
x_change = 5
elif event.key == pg.K_w:
if on_ground: # Only jump if the player is on_ground.
y_change = -12
on_ground = False
elif event.type == pg.KEYUP:
if event.key == pg.K_a and x_change < 0:
x_change = 0
elif event.key == pg.K_d and x_change > 0:
x_change = 0
# Add the GRAVITY value to y_change, so that
# the object moves faster each frame.
y_change += GRAVITY
x += x_change
y += y_change
#x += vel_blue
# Stop the object when it's near the bottom of the screen.
if y >= height - 100:
y = height - 100
y_change = 0
on_ground = True
if x == 0:
x = 5
elif x == 740:
x = 735
offset_blue = bluerect[0] - ballrect[0], bluerect[1] - ballrect[1]
overlap_blue = mask_ball.overlap(mask_blue, offset_blue)
if overlap_blue: # Blue collides with the ball.
ball_vel = Vector2(x_change) * 1.4
ball_vel += x2
# Draw everything.
screen.fill(LIGHTBLUE)
pg.draw.line(screen, (0, 0, 0), (0, height-70), (width, height-70))
screen.blit(bluecar, (x, y))
screen.blit(BALL, (x2,y2))
pg.display.update()
clock.tick(60)
pg.quit()
You can just invert the y component of the velocity vector when the ball touches the ground to make it bounce: ball_vel.y *= -1. Change the value by which you multiply the velocity to adjust the elasticity: ball_vel.y *= -0.94 # Lower elasticity.
import pygame as pg
from pygame.math import Vector2
pg.init()
LIGHTBLUE = pg.Color('lightskyblue2')
screen = pg.display.set_mode((800, 600))
width, height = screen.get_size()
clock = pg.time.Clock()
BALL = pg.Surface((30, 30), pg.SRCALPHA)
pg.draw.circle(BALL, [0,0,0], [15, 15], 15)
ball_pos = Vector2(370, 0)
ballrect = BALL.get_rect(center=ball_pos)
ball_vel = Vector2(0, 0)
ground_pos = 70
GRAVITY = .9
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
ball_vel.y += GRAVITY # Accelerate downwards.
ball_pos += ball_vel # Move the ball.
ballrect.center = ball_pos
# Bounce when the ball touches the bottom of the screen.
if ballrect.bottom >= height - ground_pos:
# Just invert the y-velocity to bounce.
ball_vel.y *= -0.94 # Change this value to adjust the elasticity.
# Don't go below the ground.
ballrect.bottom = height - ground_pos
ball_pos.y = ballrect.centery
# Draw everything.
screen.fill(LIGHTBLUE)
pg.draw.line(screen, (0, 0, 0), (0, height-70), (width, height-ground_pos))
screen.blit(BALL, ballrect)
pg.display.update()
clock.tick(60)
pg.quit()
The error says that you cannot add an int and Vector2 together directly. The program does not know how to. What you need to do instead is to add to the x value of the vector. Change the line ball_vel += x2 to ball_vel.x += x2.

pygame function only works once, doesn't loop

I have a pause menu for a game im working on for school. If the user clicks 'p' it launches the pause menu. And the pause menu has a function that if a user clicks a button the user will be launched back into the game. Problem is after they are launched into the game the 'p' function to pause doesn't work anymore. I'm not sure if i looped it correctly.
the pong game
import pygame
black = (0,0,0)
white = (255,255,255)
pygame.init()
size = 800,600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Basketball Shootout")
done = False
clock = pygame.time.Clock()
def player1(x1, y1, xsize, ysize):
pygame.draw.rect(screen, black, [x1, y1, xsize, ysize])
def player2(x2, y2, xsize, ysize):
pygame.draw.rect(screen, black, [x2,y2,xsize,ysize])
def ball(ballx, bally):
pygame.draw.circle(screen, black, [ballx,bally],20)
def Score1(score1):
font = pygame.font.Font("Minecraft.ttf" ,50)
text = font.render(str(score1), True, white)
screen.blit(text, [160, 550])
def Score2(score2):
font = pygame.font.Font("Minecraft.ttf" ,50)
text = font.render(str(score2), True, white)
screen.blit(text, [610, 550])
x1 = 20
y1 = 175
xsize = 35
ysize = 150
speed1 = 0
x2 = 740
y2 = 175
speed2 = 0
ballx = 550
bally = 250
speedx = 8
speedy = 5
score1 = 0
score2 = 0
bg = pygame.image.load("pongbg2.png")
rect1 = pygame.Rect(50,510,100,50)
def pausescreen():
import pausescreen
display_game = True
game_page = 1
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.draw.rect(screen, (255, 255, 255), rect1)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
speed1 = -10
if event.key == pygame.K_s:
speed1 = 10
if event.key == pygame.K_UP:
speed2 = -10
if event.key == pygame.K_DOWN:
speed2 = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
speed1 = 0
if event.key == pygame.K_s:
speed1 = 0
if event.key == pygame.K_UP:
speed2 = 0
if event.key == pygame.K_DOWN:
speed2 = 0
if event.key == pygame.K_p:
pausescreen()
screen.blit(bg, (0, 0))
player1(x1, y1, xsize, ysize)
player2(x2, y2, xsize, ysize)
ball(ballx,bally)
Score1(score1)
Score2(score2)
y1 += speed1
y2 += speed2
ballx += speedx
bally += speedy
if y1 < 0:
y1 = 0
if y1 > 350:
y1 = 350
if y2 < 0:
y2 = 0
if y2 > 350:
y2 = 350
if ballx+20 > x2 and bally-20 > y2 and bally+20 < y2+ysize and ballx < x2+3:
speedx = -speedx
if ballx-20 < x1+35 and bally-20 > y1 and bally+20 < y1+ysize and ballx > x1+38:
speedx = -speedx
if bally > 477 or bally < 23:
speedy = -speedy
if ballx < 13:
score2 += 1
ballx = 350
bally = 250
if ballx > 750:
score1 += 1
ballx = 350
bally = 250
pygame.display.flip()
clock.tick(60)
pygame.quit()
now here is my pause menu code.
import pygame
import sys
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.init()
# Set the height and width of the screen
size = [800, 600 ]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Basketball Shootout")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#Rectangles
rect1 = pygame.Rect(300,300,205,80)
rect2 = pygame.Rect(300,400,205,80)
#Font
font3 = pygame.font.Font("Minecraft.ttf", 40)
def playerpong():
import playerpong
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(BLACK)
pygame.draw.rect(screen, GREEN, rect1)
pygame.draw.rect(screen, RED, rect2)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if rect1.collidepoint(event.pos):
playerpong()
if rect2.collidepoint(event.pos):
pygame.quit()
clock.tick(60)
pygame.display.update()
pygame.quit()
The problem is that you are importing your pause screen from another program which creates a problem as you can import a library only once. You can try to put your pause screen code in the function instead of calling it but if you insist, you can put your pause_screen code in a function and do a from pausescreen import name_of_function so whenever you need to call that code just write name_of_funtion()

pygame - make a stickman jump using arrow keys but goes no higher than 10 units

the stickman I have is able to move and all, using the arrow keys, and but, when the up arrow key is pressed, I want him to only be able to go about 10 units every time the key is pressed, no matter how long it is pressed for. In other words I want him to jump, and have a limit to how high he can jump. I've tried a couple things but nothing has worked.
import pygame
def drawMan(screen,x,y):
#head
pygame.draw.ellipse(screen,BLACK,[0+x,0+y,10,10], 0)
#body
pygame.draw.line(screen,BLACK,[4+x,17+y],[4+x,7+y], 2)
#legs
pygame.draw.line(screen,BLACK,[4+x,17+y],[9+x,27+y], 2)
pygame.draw.line(screen,BLACK,[4+x,17+y],[-1+x,27+y], 2)
#arms
pygame.draw.line(screen,BLACK,[4+x,7+y],[8+x,17+y], 2)
pygame.draw.line(screen,BLACK,[4+x,7+y],[0+x,17+y], 2)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BORDER = (100,100,100)
pygame.init()
size = (800, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Jump")
done = False
clock = pygame.time.Clock()
pygame.mouse.set_visible(1)
xCoord = 11
yCoord = 463
xSpeed = 0
ySpeed = 0
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xSpeed = -3
if event.key == pygame.K_RIGHT:
xSpeed = 3
if event.key == pygame.K_UP:
ySpeed = -3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
xSpeed = 0
if event.key == pygame.K_RIGHT:
xSpeed = 0
if event.key == pygame.K_UP:
ySpeed = 3
if xCoord >= 780:
xSpeed = 0
xCoord -= 1
elif xCoord <= 13:
xSpeed = 0
xCoord += 1
elif yCoord > 465:
ySpeed = 0
yCoord -= 1
elif yCoord <= 13:
ySpeed = 0
yCoord += 1
else:
xCoord += xSpeed
yCoord += ySpeed
screen.fill(WHITE)
pygame.draw.line(screen, BORDER, [0,0],[800,0], 20)
pygame.draw.line(screen, BORDER, [0,0],[0,500], 20)
pygame.draw.line(screen, BORDER, [0,500],[800,500], 20)
pygame.draw.line(screen, BORDER, [800,500],[800,0], 20)
drawMan(screen,xCoord,yCoord)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Set a variable that allows him to jump. If the variable isn't True, then the jump key does nothing.
When he jumps, switch the variable to False. Don't reset it until he hits the ground again.
Pseudocode:
IF INPUT = "jump" AND can_jump == True THEN
can_jump = False
player.jump()
END IF
IF player.y == 0 and can_jump == False THEN
can_jump = True
END IF
dudee i know it is so late but i found out the answer for this and it is a simple thing
import pygame as game
import keyboard
game.init()
dis=game.display.set_mode((1280,720))
state=0
simpclr=(24,24,24)
white=(255,255,255)
posx=5
posy=5
a=0
jcd=1
clock=game.time.Clock()
while not state:
for event in game.event.get():
if event.type==game.QUIT:
state=1
dis.fill(white)
pl=game.Rect(posx,posy,20,20)
game.draw.rect(dis,simpclr,pl)
game.display.flip()
posy+=2
if keyboard.is_pressed('d'):
posx+=5
if jcd<10:
if keyboard.is_pressed(" "):
posy-=10
jcd+=1
if jcd<50 and jcd>=10:
jcd+=1
if jcd==50:
jcd=1
if posx==1230:
posx-=5
if posy==100:
posy-=5
game.display.flip()
clock.tick(60)
game.quit()

Categories

Resources