Pygame bounce off ceiling acting strangely - pygame

I have been working on a pygame project where a player controls a rectangle that hits a ball. When the ball hit the side walls, it bounces off perfectly, same with the floor, but when it hits the top, it works very weirdly in a way I can't describe. If anyone wants to test this, my code is below, just hit the ball onto the roof and it will show what I am trying to explain. I would like it so you can't ram the ball into the ceiling so it goes off the screen and for it to be a clean bounce instead of what it dose right now and sort of rolls down if it touches the ceiling.
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
if ballrect.top <= 0:
# Just invert the y-velocity to bounce.
ball_vel.y *= 0.4 # Change this value to adjust the elasticity.
# 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()

Just set the ballrect.top coordinate to 1, so that it stays in the game area and also update the ball_pos.y afterwards.
if ballrect.top <= 0:
# Just invert the y-velocity to bounce.
ball_vel.y *= -0.4 # Change this value to adjust the elasticity.
ballrect.top = 1
ball_pos.y = ballrect.centery

Related

Cannot shoot more than one projectile

Shooting one bullet works but i can only shoot one and after that it stops working. I've tried to change my "bullet_fire" to False after KEYUP but this doesnt work either since then the bullet is only visible while i hold the arrow up key while the problem remain. How should i solve this problem?
Here is the code:
import pygame
pygame.init()
# Skärm
Screen = pygame.display.set_mode((1600, 900))
# Title och Logo
pygame.display.set_caption("Fjärt Spel")
icon = pygame.image.load('planet.png')
pygame.display.set_icon(icon)
# backround
backround = pygame.image.load("0000.png")
# player
playerIMG = pygame.image.load("soldier.png")
playerX = 350
playerY = 836
playerX_Change = 0
playerY_Change = 30
# enemy
enemyIMG = pygame.image.load("terrorist2.png")
enemyX = 500
enemyY = 810
enemyX_Change = 0
enemyY_Change = 0
# bullet
bulletIMG = pygame.image.load("pung(32x32).png")
bulletX = playerX
bulletY = playerY
bulletX_Change = 50
bulletY_Change = 0
bullet_fire = False
offScreen = 1600, 900
def player(x, y):
Screen.blit(playerIMG, (x, y))
def enemy(x, y):
Screen.blit(enemyIMG, (x, y))
Running = True
while Running:
Screen.fill((0, 0, 0))
# backround
Screen.blit(backround, (0, 0))
if bullet_fire == True:
Screen.blit(bulletIMG, (bulletX + 100, playerY))
bulletX += bulletX_Change
if bulletX > 1600:
bullet_fire == False
for event in pygame.event.get():
if event.type == pygame.QUIT:
Running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_Change = -10
if event.key == pygame.K_RIGHT:
playerX_Change = 10
if event.key == pygame.K_SPACE:
playerY_Change = -70
if event.key == pygame.K_UP:
bullet_fire = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_SPACE:
playerX_Change = 0
playerY_Change = 30
# Ha player innan fill!!
playerX += playerX_Change
playerY += playerY_Change
if playerX <= 0:
playerX = 0
elif playerX >= 1436:
playerX = 1436
if playerY <= 0:
playerY = 0
elif playerY >= 836:
playerY = 836
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
if bulletX > 1600:
bullet_fire == False
# ^^
This appears to want to set bullet_fire to False when it reaches a certain ordinate but, in reality, is comparing the two and throwing away the result. That means the first bullet you've fired is still going, has left the screen, and is probably halfway to Jupiter by now :-)
By way of example, this is similar to the following transcript:
>>> a = 7
>>> if a == 7:
... a == 14
... print(a)
...
False
7
You need to use == for comparison and = for assignment.
Keep in mind that's the likely cause of your issue. Since your question does not contain the code that decides whether a new bullet should be generated, it's a little hard to tell for sure. I'm therefore basing it on the assumption that one bullet at a time is all that's permitted (as in quite a few arcade games). Hence, if you never "destroy" the current bullet, you'll never be able to fire another one.
If that turns out to not be the case, you probably need to post more code so we can do an exhaustive analysis.
As an aside, I'm a little concerned about the physics involved in:
Screen.blit(bulletIMG, (bulletX + 100, playerY))
This appears to draw the bullet at the players current Y position meaning that, after the bullet is fired, it will track the player in some weird Einsteinian "spooky action at a distance" manner. While that makes the game a lot easier since you can direct the bullets after firing, I'm not convinced it will get a high score in the realism category :-)

pygame the next surface does not move as expected path

I'm new to pygame, and I'm trying to practice skill with 'Plants and Zombies', but here comes a problem when I run the code: the next bullet does not move to the edge of the screen, it ends at a point at which the previous bullet collide with a zombie. I can NOT find out where is the problem, hope someone can help me out. Just run main.py, click on a top menu(weapon), right click on any point of a grass, u'll know the problem.
project directory:
helper.py:
import os
from PIL import Image
import pygame
current_dir = os.getcwd()
def get_path(image_name):
return os.path.join(current_dir, "resource", image_name)
def get_image_size(image_name):
with Image.open(get_path(image_name)) as im:
return im.size
def load_image_source(image_name, with_bullet=False):
if with_bullet:
bullet_name = "bullet_"+image_name.replace("shooter_", "")
return pygame.image.load(get_path(image_name)), pygame.image.load(get_path(bullet_name))
else:
return pygame.image.load(get_path(image_name))
def load_all_shooters():
weapon = {"selected": [], "unselected": []}
shooter_dir = os.path.join(current_dir, "resource")
for shooter in os.listdir(shooter_dir):
if "shooter" in shooter:
if "selected" in shooter:
weapon["selected"].append(shooter)
else:
weapon["unselected"].append(shooter)
weapon["selected"] = sorted(weapon["selected"])
weapon["unselected"] = sorted(weapon["unselected"])
return weapon
def get_nearest_position(source_list, target_number):
return min(source_list, key=lambda x: abs(x - target_number))
config.py:
LINES = 5
ZOMBIE_SPEED_X = 1
ZOMBIE_REFRESH_TIME = 3000
BULLET_REFRESH_TIME = 1000
BULLET_SPEED = 3
SHOOTER_SIZE = (50, 50)
main.py:
import pygame
import sys
import random
from ZombiesVSPlants.common.helper import get_nearest_position, load_image_source, load_all_shooters, get_image_size, get_path, get_path
from ZombiesVSPlants.config.config import BULLET_SPEED, BULLET_REFRESH_TIME, ZOMBIE_REFRESH_TIME, SHOOTER_SIZE, ZOMBIE_SPEED_X, LINES
pygame.init()
# top weapon menu
menu_height = 60
# get background grass and other resource path and size...
background_grass_path = get_path("background_grass.png")
zombie_path = get_path("enemy_zombie.png", )
single_line_height = get_image_size("background_grass.png")[1]
zombie_size = get_image_size("enemy_zombie.png")
# screen size
screen_height = LINES*single_line_height+menu_height
screen_width = 800
# background colour, zombie speed
background_color = 255, 255, 255
ZOMBIE_SPEED = [-ZOMBIE_SPEED_X, 0]
# others
LINES_LIST = [i for i in range(1, LINES+1)]
zombie_start_x = screen_width-zombie_size[0]
zombie_start_y = (single_line_height-zombie_size[1])/2
shooter_centered_position__list_y = [line*single_line_height+zombie_start_y+menu_height for line in range(5)]
# resource boom
boom = load_image_source("boom.png")
# dragging and other global variables
dragging = False
mouse_follow = None
mouse_follow_rect = None
added_shooters = []
shooter_bullets = []
bullets_rect = []
collide_zombies = []
collide_bullets = []
# screen size
screen = pygame.display.set_mode((screen_width, screen_height))
# load top weapon surface
res = load_all_shooters()
menu_start_position = 5, 5
menu_shooters = [load_image_source(unselected_shooter, with_bullet=True) for unselected_shooter in res["unselected"]]
menu_shooters_selected = [load_image_source(selected_shooter) for selected_shooter in res["selected"]]
menu_shooters_rect = [pygame.Rect(menu_start_position[0]+55*i, menu_start_position[1], SHOOTER_SIZE[0], SHOOTER_SIZE[1]) for i in range(len(menu_shooters))]
# background grass surface
grass = load_image_source(background_grass_path)
grass_rect = [pygame.Rect(0, i * single_line_height+menu_height, screen_width, single_line_height) for i in range(LINES)]
# the very first zombie surface
zombie = load_image_source(zombie_path)
zombies_rect = [pygame.Rect(zombie_start_x, zombie_start_y+menu_height, zombie_size[0], zombie_size[1])]
# ZOMBIE_REFRESH_TIME
NEW_ZOMBIE_EVENT = pygame.USEREVENT+1
pygame.time.set_timer(NEW_ZOMBIE_EVENT, ZOMBIE_REFRESH_TIME)
# BULLET_REFRESH_TIME
NEW_BULLET_EVENT = pygame.USEREVENT+2
pygame.time.set_timer(NEW_BULLET_EVENT, BULLET_REFRESH_TIME)
while 1:
screen.fill(background_color)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# left click on a top menu(weapon), dragging is enabled
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for i in range(len(menu_shooters)):
if menu_shooters_rect[i].collidepoint(event.pos):
dragging = not dragging
mouse_follow = menu_shooters[i]
# right click when dragging, new weapon will be set on a point
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
x = event.pos[0]
if event.pos[1] > menu_height and dragging:
dragging = not dragging
y = get_nearest_position(shooter_centered_position__list_y, event.pos[1])
added_shooters.append([mouse_follow[0], x, y])
shooter_bullets.append([x, y, mouse_follow[1]])
# spawn new bullet
if event.type == NEW_BULLET_EVENT:
for j in range(len(shooter_bullets)):
bullets_rect.append([shooter_bullets[j][2], pygame.Rect(shooter_bullets[j][0], shooter_bullets[j][1], 15, 15)])
# spawn new zombie
if event.type == NEW_ZOMBIE_EVENT:
# random in roads that new zombies will appear
new_zombies_count = random.randint(1, LINES)
new_zombies_lines = random.sample(LINES_LIST, new_zombies_count)
# add to zombies list
for line in new_zombies_lines:
new_zombie_rect = pygame.Rect(zombie_start_x, line * single_line_height + zombie_start_y + menu_height, zombie_size[0], zombie_size[1])
zombies_rect.append(new_zombie_rect)
# blit top weapons menu
for i in range(len(menu_shooters)):
menu_rect = menu_shooters_rect[i]
screen.blit(menu_shooters[i][0], menu_rect)
# blit selected weapon if mouse hover on a weapon menu
for i in range(len(menu_shooters)):
if menu_shooters_rect[i].collidepoint(pygame.mouse.get_pos()):
screen.blit(menu_shooters_selected[i], menu_shooters_rect[i])
# blit background grass
for r in grass_rect:
screen.blit(grass, r)
# blit all the weapons on the grass
for new in added_shooters:
shooter_rect = pygame.Rect(new[1], new[2], 50, 50)
screen.blit(new[0], shooter_rect)
# blit bullets
for j in range(len(bullets_rect)):
bullets_rect[j][1].x += 1
screen.blit(bullets_rect[j][0], bullets_rect[j][1])
# blit zombies
for i in range(len(zombies_rect)):
zombies_rect[i].x -= ZOMBIE_SPEED_X
screen.blit(zombie, zombies_rect[i])
# blit weapon follows mouse move position
if dragging and mouse_follow[0]:
pos_follow_mouse = pygame.mouse.get_pos()
mouse_follow_rect = pygame.Rect(pos_follow_mouse[0], pos_follow_mouse[1], 50, 50)
screen.blit(mouse_follow[0], mouse_follow_rect)
# collide between zombie and bullet
for i in range(len(bullets_rect)):
for j in range(len(zombies_rect)):
if bullets_rect[i][1].colliderect(zombies_rect[j]):
print("collide!")
screen.blit(boom, zombies_rect[j])
collide_bullets.append(bullets_rect[i])
collide_zombies.append(zombies_rect[j])
bullets_rect = [i for i in bullets_rect if i not in collide_bullets]
zombies_rect = [j for j in zombies_rect if j not in collide_zombies]
pygame.display.flip()
I now got a compromise like solution, when need to remove surface in a collide between 2 rects in 2 lists, just draw the 2 lists in 2 separate for loop and remove the collided rect in another for loop, the demo code would be:
# draw bullets
for b in bullets_rect:
b_r = b[1]
b_r.x += BULLET_SPEED
screen.blit(b[0], b_r)
# draw zombies
for z in zombies_rect:
z.x += -ZOMBIE_SPEED_X
screen.blit(zombie, z)
# when collide, use list.remove to remove collided rect
for i, j in itertools.product(bullets_rect, zombies_rect):
b_r = i[1]
z_r = j
if z_r.contains(b_r):
# when collide, remove the collided rect
screen.blit(boom, z_r)
bullets_rect.remove(i)
zombies_rect.remove(j)
FYI.

collision detection in snake game

I have tried to make a snake game using python's pygame. What I did was create 2 segments in the start at a particular distance this will be my snake and as it eats more objects it will grow. But I want my game to end when the snakes head collides with any other segment. I used sprite collide method to detect collision between snakes head(here snake_segment[0]) and the segment group.Here's the code which is relevant to my problem
class Segment(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([segment_width,segment_height])
self.image.fill(black)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# we create the apple object here
class Apple(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.transform.scale(apple1,(25,25))
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(30,screen_width-30)
self.rect.y = random.randrange(30,screen_height-30)
# we create the function for sprites so that we can manage all the sprites
all_sprites = pygame.sprite.Group()
segment_group = pygame.sprite.Group()
snake_segment = [] # we create this list to store all thhe segments
for i in range(0,2):
x = 250 - (segment_width+ segement_margin)*i
y= 30
segments =Segment(x,y)
snake_segment.append(segments)
all_sprites.add(segments)
segment_group.add(segments)
apple_group = pygame.sprite.Group()
apple =Apple()
apple_group.add(apple)
all_sprites.add(apple)
running = True
while running:
# we tweak the fps here
clock.tick(fps)
# we keep track of all the events here
for event in pygame.event.get():
# if the user wishes to quit
if event.type == pygame.QUIT:
running = False
# we set the movement of the segments
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = (segment_height + segement_margin)*-1
x_change=0
if event.key == pygame.K_DOWN:
y_change = (segment_height + segement_margin)
x_change= 0
if event.key == pygame.K_LEFT:
x_change = (segment_width + segement_margin)*-1
y_change = 0
if event.key == pygame.K_RIGHT:
x_change = (segment_width + segement_margin)
y_change = 0
# we remove the last element of the snake segment
old_segment = snake_segment.pop()
all_sprites.remove(old_segment)
# we add the new element on the top of the snake
x = snake_segment[0].rect.x + x_change
y = snake_segment[0].rect.y + y_change
segment = Segment(x,y)
snake_segment.insert(0,segment)
all_sprites.add(segment)
# here we detect collison between apple group and snake sprite and make changes
eat_coll = pygame.sprite.spritecollide(snake_segment[0],apple_group,True)
if eat_coll:
x = snake_segment[-1].rect.x - x_change
y = snake_segment[-1].rect.y - y_change
segment = Segment(x,y)
snake_segment.insert(-1,segment)
segment_group.add(segment)
apple = Apple()
apple_group.add(apple)
all_sprites.add(apple)
bite_sound.play()
snake_coll = pygame.sprite.spritecollide(snake_segment[0],segment_group,False)
if snake_coll:
running = False
# update each sprite
all_sprites.add(segment)
# here we fill the background
screen.blit(background_image,background_rect)
all_sprites.draw(screen)
# we will update the screen
pygame.display.update()
Just check if the snakes head is inside the snakes body.
def self_collision(self):
"""
Return True if head is inside the body
"""
return self.snake_segnment[0] in self.snake_segment[1:]

Pygame sin,cos,tan caculating circular movement path

I have been struggling for few days know trying to figure out how to make for example a image move in circular path. I have looked other posts here but i just can't get it.
So how do i move image in circular path. My code only moves my image 45 degrees and stops then. I would need it to go full circle and continue doing it.
Current Code:
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
CENTER = (200, 200)
RADIUS = 100
x = 0
y = 0
satelliteCenter = (CENTER[0]+RADIUS, CENTER[1])
run = 1
while run == 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = 0
pygame.quit()
mouse = pygame.mouse.get_pos()
vector = x-CENTER[0], y-CENTER[1]
x +=1
distance = (vector[0]**2 + vector[1]**2)**0.5
if distance > 0:
scalar = RADIUS / distance
satelliteCenter = (
int(round( CENTER[0] + vector[0]*scalar )),
int(round( CENTER[1] + vector[1]*scalar )) )
screen.fill((255,255,255))
pygame.draw.circle(screen, (71,153,192), CENTER, RADIUS)
pygame.draw.circle(screen, (243,79,79), satelliteCenter, 16)
pygame.display.update()
You can just use a pygame.math.Vector2 and rotate it each frame, scale it by the radius and add it to the CENTER position to get the current center of the small circle.
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
CENTER = (200, 200)
RADIUS = 100
# A unit vector pointing to the right.
direction = pygame.math.Vector2(1, 0)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
direction.rotate_ip(4) # By 4 degrees.
# Normalize it, so that the length doesn't change because
# of floating point inaccuracies.
direction.normalize_ip()
# Scale direction vector, add it to CENTER and convert to ints.
ball_pos = [int(i) for i in CENTER+direction*RADIUS]
screen.fill((255,255,255))
pygame.draw.circle(screen, (71,153,192), CENTER, RADIUS)
pygame.draw.circle(screen, (243,79,79), ball_pos, 16)
pygame.display.update()
clock.tick(30)
Edit: If you want the red ball to follow the mouse, then your example actually works if you set x and y to the mouse pos x, y = pygame.mouse.get_pos().
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
CENTER = (200, 200)
RADIUS = 100
x = 0
y = 0
satelliteCenter = (CENTER[0]+RADIUS, CENTER[1])
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
x, y = pygame.mouse.get_pos()
vector = x-CENTER[0], y-CENTER[1]
distance = (vector[0]**2 + vector[1]**2)**0.5
if distance > 0:
scalar = RADIUS / distance
satelliteCenter = (
int(round( CENTER[0] + vector[0]*scalar )),
int(round( CENTER[1] + vector[1]*scalar ))
)
screen.fill((255,255,255))
pygame.draw.circle(screen, (71,153,192), CENTER, RADIUS)
pygame.draw.circle(screen, (243,79,79), satelliteCenter, 16)
pygame.display.update()

Difficulty with movement in game close to Pong (pygame)

Note: I am really new in programming.
At first, I am just going to post the code I have written:
import pygame
import random
pygame.init()
screen = pygame.display.set_mode([640, 480])
paddle = pygame.image.load("pulgake.png")
pygame.display.set_caption("PONG!")
WHITE = [0, 0, 0]
back = pygame.image.load("taust.png")
screen.blit(back, (0, 0))
screen.blit(paddle, (600, 240))
pygame.display.flip()
xpaddle = 600
ypaddle = 240
delay = 10
interval = 10
pygame.key.set_repeat(delay, interval)
class Ball:
def __init__(self):
self.pos = [0,0]
self.velocity = [1,0]
def move():
self.pos[0] += self.velocity[0]
self.pos[1] += self.velocity[1]
if self.pos[0] > 10:
self.pos[0] *= -1
elif self.pos[1] > 470: # My background has a frame
self.pos[1] *= -1
elif self.pos[1] < 10:
self.pos[1] *= -1
elif self.pos[0] > 605:
False
def draw(screen):
pygame.draw.circle(screen,WHITE,self.pos,15)
pall = Ball()
while True:
pall.move()
screen.blit(back, (0,0))
screen.blit(paddle, (xpaddle, ypaddle))
pygame.display.flip()
for i in pygame.event.get():
if i.type == pygame.QUIT:
sys.exit()
elif i.type == pygame.KEYDOWN:
if i.key == pygame.K_UP:
ypaddle = ypaddle - 10
if ypaddle < 10:
ypaddle = 10
elif i.key == pygame.K_DOWN:
ypaddle = ypaddle + 10
if ypaddle > 410:
ypaddle = 410
I am getting this error-
line 44, in <module>
pall.move()
TypeError: move() takes no arguments (1 given)
So, I want to get a ball that bounces off the walls (and paddle as well, but I don't know yet how)
Also, I would be really grateful if somebody helps me to get a stopwatch in this game, showing time "survived".
EDIT: added def move(self)
Now, a bigger problem occured:
draw() and move() - global name"self" not defined.
I really can't figure out this one.
You are calling ball.move which doesn't exist, because move needs to be indented once more.
If you want "do stuff while key is held down" You can use getkeystate and use KEYDOWN events when you want 'do stuff once, when key is pressed'
see both here: https://stackoverflow.com/a/13207525/341744