Enemy move is wrong why? - python

I want to create a spaceship game to using pygame. I want to enemies movement like this:
first enemies moving x coordination and enemy x coordinate increasing on x (moving right)
if enemy coordinates x >= WIDHT , enemy coordinates y += 5 and enemy x coordinate is decreasing on x (moving left)
if enemy coordinates x <= 0 ,enemy coordinates y -= 5 and enemy x coordinate is increasing on x (moving right)
I want to move enemies like this, but I typed code and enemies not moving as I want:
import pygame
import random
import time
WIDTH , HEIGHT = (750, 600)
WIN = pygame.display.set_mode((WIDTH,HEIGHT))
BG_IMAGE = pygame.transform.scale(pygame.image.load("yeni_resim.jpg"),(WIDTH, HEIGHT))
CAPTION_IMAGE = pygame.image.load("spaceship.png")
ENEMY_IMAGE = pygame.image.load("enemy.png")
BULLET_IMAGE = pygame.image.load("bullet.png")
PLAYER_IMAGE = pygame.image.load("warship.png")
Creating Bullet Class
class Bullet:
def __init__(self, x, y, img):
self.x = x
self.y = y
self.img = img
self.mask = pygame.mask.from_surface(self.img)
def draw(self, window):
window.blit(self.img, (self.x, self.y))
def move(self, vel):
self.y += vel
def off_screen(self, height):
return not (self.y <= height and self.y >=0)
def collision(self, obj):
pass
And creating ship class(for warship and enemy)
class Ship:
def __init__(self, x, y):
self.x = x
self.y = y
self.ship_img = None
def draw(self, window):
window.blit(self.ship_img, (self.x, self.y))
def get_width(self):
return self.ship_img.get_width()
def get_height(self):
return self.ship_img.get_height()
class Player(Ship):
def __init__(self, x, y):
super().__init__(x, y)
self.ship_img = PLAYER_IMAGE
self.mask = pygame.mask.from_surface(self.ship_img)
def draw(self, window):
super().draw(window)
This is enemy class and i create def for enemy movement:
class Enemy(Ship):
def __init__(self, x, y):
super().__init__(x,y)
self.ship_img = ENEMY_IMAGE
self.mask = pygame.mask.from_surface(self.ship_img)
def move(self, vel):
self.x += vel
if self.x >= 684:
self.x -= vel
self.y += 5
elif self.x <= 0:
self.x += vel
self.y += 5
def main():
run = True
FPS = 60
clock = pygame.time.Clock()
player = Player(350, 500)
player_vel = 8
enemy = Enemy(350, 100)
enemy_vel = 5
def redraw_window():
WIN.blit(BG_IMAGE,(0,0))
player.draw(WIN)
enemy.draw(WIN)
pygame.display.update()
while run:
clock.tick(FPS)
redraw_window()
enemy.move(enemy_vel)
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and player.x + player_vel + player.get_width() < WIDTH:
player.x += player_vel
if keys[pygame.K_LEFT] and player.x - player_vel > 0:
player.x -= player_vel
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
main()

Try removing your move function and replacing it with this in the while loop:
enemy.x += enemy_vel
if enemy.x >= WIDTH - ENEMY_IMAGE.get_width() or enemy.x <= 0:
enemy_vel *= -1
enemy_y += 5

Related

How to move the player across a one background image?

Apologies for asking so many questions recently. I'm just starting to get into pygame.
With my previous questions I don't think I've been wording it properly for what I am trying to do.
Here is a quick picture I did to try demonstrate
This is a single background image or map that I would like the player to move across. The red X is just a starting place for the character.
I'm try to make it so when I move the player the background will also follow as if the player is moving through the map. I've already limited the player from not being able to go off the borders of the actual screen. Just having a bit of trouble now trying to make it so the single image will move along the player and if the player reaches the end of the map picture movement stops. I have seen people use scrolling and duplicating the image when the player moves. I just want to see it to the single image that the player will move across. I don't want to worry about collisions just be able to get the movement working.
This is the code I am currently using:
from pygame.locals import *
from math import sin
pygame.display.set_caption("TEST")
clock = pygame.time.Clock()
time_passed = 0
class Player():
def __init__(self,x,y):
self.Image = pygame.image.load("myAvatar.png").convert()
self.x = 200
self.y = 200
def getX(self):
return self.rect.x
def getY(self):
return self.rect.y
def handle_keys(self,screenHeight,screenWidth):
key = pygame.key.get_pressed()
dist = 2
if key[K_LEFT] and self.x > 0:
self.x -= 500 * time_passed
if key[K_RIGHT] and self.x < screenWidth -20:
self.x += 500 * time_passed
if key[K_UP] and self.y > 0:
self.y -= 500 * time_passed
if key[K_DOWN] and self.y < screenHeight -20:
self.y += 500 * time_passed
def draw(self, game_window):
self.Image = pygame.transform.scale(self.Image,(20,20))
game_window.blit(self.Image, (int(self.x), int(self.y)))
class Map():
def __init__(self):
self.Image = pygame.image.load("test2.png").convert()
self.rect = self.Image.get_rect()
self.x = 0
self.y = 0
def draw(self, game_window,screenHeight,screenWidth):
self.x = min(max(self.x, player.x - 2 * screenWidth / 2), player.x - screenWidth / 2)
self.y = min(max(self.y, player.y -2 * screenHeight / 2), player.y - screenHeight / 2)
game_window.blit(self.Image,(-self.x,-self.y))
class Enemy():
def __init__ (self,x,y):
self.Image = pygame.image.load("WC.jpg").convert()
self.rect = self.Image.get_rect(topleft = (x,y))
def draw(self, game_window):
self.Image = pygame.transform.scale(self.Image,(20,20))
game_window.blit(self.Image, (self.rect.x, self.rect.y))
pygame.init()
clock = pygame.time.Clock()
screenWidth = 400
screenHeight = 400
game_window = pygame.display.set_mode((screenWidth,screenHeight))
player = Player(200,200)
map = Map()
enemy = Enemy(250,250)
leave = False
while not leave:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
player.handle_keys(screenHeight,screenWidth)
game_window.fill((0,0,0))
map.draw(game_window,screenHeight,screenWidth)
#enemy.draw(game_window)
player.draw(game_window)
pygame.display.update()
pygame.display.flip()
time_passed = clock.tick() / 1000
pygame.quit()
quit()
Thanks
Shay
The player's movement depends on the size of the map. The x and y attributes of the "player" store the position on the map and are limited to the size of the map (map_size). The player is always drawn in the center of the screen, except it is near the boarders of the map:
class Player():
def __init__(self, x, y):
self.Image = pygame.image.load("myAvatar.png").convert()
self.x = 200
self.y = 200
def handle_keys(self, map_size):
key = pygame.key.get_pressed()
self.x += (key[K_RIGHT] - key[K_LEFT]) * 500 * time_passed
self.y += (key[K_DOWN] - key[K_UP]) * 500 * time_passed
self.x = max(0, min(map_size[0]-20, self.x))
self.y = max(0, min(map_size[1]-20, self.y))
def draw(self, game_window, map_size):
window_size = game_window.get_size()
center = window_size[0] // 2, window_size[0] // 2
pos = [self.x, self.y]
for i in range(2):
if center[i] < pos[i] <= map_size[i]-center[i]:
pos[i] = center[i]
elif pos[i] > map_size[i] - center[i]:
pos[i] = window_size[i] - map_size[i] + pos[i]
game_window.blit(self.Image, (int(pos[0]), int(pos[1])))
The player's position on the map is centered in the window:
class Map():
def __init__(self):
self.Image = pygame.image.load("test2.png").convert()
def draw(self, game_window):
window_size = game_window.get_size()
map_size = self.Image.get_size()
x = max(0, min(map_size[0] - window_size[0], player.x - 200))
y = max(0, min(map_size[1] - window_size[1], player.y - 200))
game_window.blit(self.Image, (-x, -y))
Application loop:
leave = False
while not leave:
for event in pygame.event.get():
if event.type == pygame.QUIT:
leave = True
player.handle_keys(map.Image.get_size())
game_window.fill((0,0,0))
map.draw(game_window)
#enemy.draw(game_window)
player.draw(game_window, map.Image.get_size())
pygame.display.update()
pygame.display.flip()
time_passed = clock.tick() / 1000
pygame.quit()

Shooting Multiple Bullets in Pygame

I am making a simple variation of space invaders using pygame. Here is some working code:
import pygame, random, time, tkinter
pygame.init()
def main():
X = 672
Y = 500
win = pygame.display.set_mode((X,Y))
pygame.display.set_caption('Space Invaders')
class player(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.lives = 3
self.vel = 5
self.points = 0
self.explosionYN = False
self.explosionCount = 0
self.highScore = int(text)
def explosion(self, win):
if self.explosionYN:
win.blit(explosion[self.explosionCount], (self.x-20, self.y-30, 100, 100))
self.explosionCount += 1
if not self.explosionYN:
self.explosionCount = 0
if self.explosionCount + 1 > 6:
self.explosionYN = False
self.explosionCount = 0
def move(self, win):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and self.x > -1:
self.x -= self.vel
if keys[pygame.K_RIGHT] and self.x < 623:
self.x += self.vel
if keys[pygame.K_q]:
if self.x >= 623:
self.x = 0
if self.x < 0:
self.x = 623
class invader(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 1
def reset(self, win):
self.y = 0
self.x = random.randint(5, (X-35))
class bullet(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 0
def shoot(self, win):
laser.play(0)
self.x = ship.x + 22
self.y = ship.y
self.vel = 15
def reset(self, win):
self.vel = 0
self.y = 510
ship = player(X//2 - (0.5*52), 435, 52, 52)
alien = invader(random.randint(0,707),0,31,25)
bullet = bullet(750, 510, 5, 7)
while run:
pygame.time.delay(25)
alien.y += alien.vel
bullet.y -= bullet.vel
if alien.y > 500:
ship.explosionYN = True
ship.explosion(win)
loseLife.play(0)
if ship.explosionCount+ 1 >= 6:
win.fill((0,0,0))
pause()
ship.lives -= 1
alien.reset(win)
elif ship.lives <= 1:
test()
if bullet.y <= 0:
bullet.reset(win)
alien1 = pygame.draw.rect(win, (0,0,0), (alien.x,alien.y,31,25))
bullet1 = pygame.draw.rect(win, (0,100,255), (bullet.x, bullet.y, bullet.width, bullet.height))
if pygame.Rect.colliderect(alien1, bullet1):
ship.points += 1
if ship.highScore < ship.points:
ship.highScore += 1
bullet.reset(win)
kill.play(0)
alien.y = 0
alien.reset(win)
alien.vel += 0.5
ship.vel += 0.25
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
keys = pygame.key.get_pressed()
ship.move(win)
if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
bullet.shoot(win)
if keys[pygame.K_p]:
pause()
drawGame()
main()
I have omitted some code that I don't think is relevant
The problem is that only one bullet can be displayed on screen at a time.
So I tried this instead.
if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
bullet1 = pygame.draw.rect(win, (#stuff))
bullet.shoot(win)
But now the bullet doesn't show at all.
Literally nothing happens.
I have looked at some other posts but as I am new to pygame I can't make head or tail of them.(Multiple Bullets pygame)
What is an easy and effiecient way to be able show multiple bullets on pygame?
thanks.
The typical way that this is done is by creating a list of bullets.
bullets = []
Then when you fire a bullet you add it to the list
bullets.append(Bullet(750, 510, 5, 7))
And inside your while loop, you will update and redraw each bullet in turn using a for loop to iterate over each bullet
for bullet in bullets:
bullet.y -= bullet.vel # Move Bullet
# Draw bullet
# Check for collision with player/enemy
This obviously isn't a complete code listing but hopefully it is enough to get you started.
You'll also end up having to create a list of enemies too if you want to create a space invaders clone.
You may find the recently released book "Code the Classics" from the Raspberry Pi Foundation helpful as it explains how to create some classic games using Pygame. It's a free download (or you can buy the hardcopy)
Edit: Consider following the Python style guide PEP-8 and renaming your classes to be title case. For example
class bullet():
should be
class Bullet():
This will help with any confusion between the variable bullet and the class of the same name.

How to fix strange rendering issue in 2d pygame using math [duplicate]

Apologies for asking so many questions recently. I'm just starting to get into pygame.
With my previous questions I don't think I've been wording it properly for what I am trying to do.
Here is a quick picture I did to try demonstrate
This is a single background image or map that I would like the player to move across. The red X is just a starting place for the character.
I'm try to make it so when I move the player the background will also follow as if the player is moving through the map. I've already limited the player from not being able to go off the borders of the actual screen. Just having a bit of trouble now trying to make it so the single image will move along the player and if the player reaches the end of the map picture movement stops. I have seen people use scrolling and duplicating the image when the player moves. I just want to see it to the single image that the player will move across. I don't want to worry about collisions just be able to get the movement working.
This is the code I am currently using:
from pygame.locals import *
from math import sin
pygame.display.set_caption("TEST")
clock = pygame.time.Clock()
time_passed = 0
class Player():
def __init__(self,x,y):
self.Image = pygame.image.load("myAvatar.png").convert()
self.x = 200
self.y = 200
def getX(self):
return self.rect.x
def getY(self):
return self.rect.y
def handle_keys(self,screenHeight,screenWidth):
key = pygame.key.get_pressed()
dist = 2
if key[K_LEFT] and self.x > 0:
self.x -= 500 * time_passed
if key[K_RIGHT] and self.x < screenWidth -20:
self.x += 500 * time_passed
if key[K_UP] and self.y > 0:
self.y -= 500 * time_passed
if key[K_DOWN] and self.y < screenHeight -20:
self.y += 500 * time_passed
def draw(self, game_window):
self.Image = pygame.transform.scale(self.Image,(20,20))
game_window.blit(self.Image, (int(self.x), int(self.y)))
class Map():
def __init__(self):
self.Image = pygame.image.load("test2.png").convert()
self.rect = self.Image.get_rect()
self.x = 0
self.y = 0
def draw(self, game_window,screenHeight,screenWidth):
self.x = min(max(self.x, player.x - 2 * screenWidth / 2), player.x - screenWidth / 2)
self.y = min(max(self.y, player.y -2 * screenHeight / 2), player.y - screenHeight / 2)
game_window.blit(self.Image,(-self.x,-self.y))
class Enemy():
def __init__ (self,x,y):
self.Image = pygame.image.load("WC.jpg").convert()
self.rect = self.Image.get_rect(topleft = (x,y))
def draw(self, game_window):
self.Image = pygame.transform.scale(self.Image,(20,20))
game_window.blit(self.Image, (self.rect.x, self.rect.y))
pygame.init()
clock = pygame.time.Clock()
screenWidth = 400
screenHeight = 400
game_window = pygame.display.set_mode((screenWidth,screenHeight))
player = Player(200,200)
map = Map()
enemy = Enemy(250,250)
leave = False
while not leave:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
player.handle_keys(screenHeight,screenWidth)
game_window.fill((0,0,0))
map.draw(game_window,screenHeight,screenWidth)
#enemy.draw(game_window)
player.draw(game_window)
pygame.display.update()
pygame.display.flip()
time_passed = clock.tick() / 1000
pygame.quit()
quit()
Thanks
Shay
The player's movement depends on the size of the map. The x and y attributes of the "player" store the position on the map and are limited to the size of the map (map_size). The player is always drawn in the center of the screen, except it is near the boarders of the map:
class Player():
def __init__(self, x, y):
self.Image = pygame.image.load("myAvatar.png").convert()
self.x = 200
self.y = 200
def handle_keys(self, map_size):
key = pygame.key.get_pressed()
self.x += (key[K_RIGHT] - key[K_LEFT]) * 500 * time_passed
self.y += (key[K_DOWN] - key[K_UP]) * 500 * time_passed
self.x = max(0, min(map_size[0]-20, self.x))
self.y = max(0, min(map_size[1]-20, self.y))
def draw(self, game_window, map_size):
window_size = game_window.get_size()
center = window_size[0] // 2, window_size[0] // 2
pos = [self.x, self.y]
for i in range(2):
if center[i] < pos[i] <= map_size[i]-center[i]:
pos[i] = center[i]
elif pos[i] > map_size[i] - center[i]:
pos[i] = window_size[i] - map_size[i] + pos[i]
game_window.blit(self.Image, (int(pos[0]), int(pos[1])))
The player's position on the map is centered in the window:
class Map():
def __init__(self):
self.Image = pygame.image.load("test2.png").convert()
def draw(self, game_window):
window_size = game_window.get_size()
map_size = self.Image.get_size()
x = max(0, min(map_size[0] - window_size[0], player.x - 200))
y = max(0, min(map_size[1] - window_size[1], player.y - 200))
game_window.blit(self.Image, (-x, -y))
Application loop:
leave = False
while not leave:
for event in pygame.event.get():
if event.type == pygame.QUIT:
leave = True
player.handle_keys(map.Image.get_size())
game_window.fill((0,0,0))
map.draw(game_window)
#enemy.draw(game_window)
player.draw(game_window, map.Image.get_size())
pygame.display.update()
pygame.display.flip()
time_passed = clock.tick() / 1000
pygame.quit()

Collision Detection Not Working - PyGame

I'm working in a game, and in this game an object falls from the top of the game screen and the player at the bottom of the screen has to hit the object falling. When the player hits the falling object, the player's width and height needs to increase. When I tested the code, the collision worked when the player hit the falling object from the side, but the collision didn't work when the player hit the falling object in the middle. Can someone help me?
PYTHON
# IMPORTS
import pygame, random
# GLOBALS
global screen, displayW, displayH
global clock, FPS
global end, food, player
# SETGLOBALVALUES
def setGlobalValues():
global screen, displayW, displayH
global clock, FPS
global end, food, player
displayW = 800
displayH = 600
screen = pygame.display.set_mode((displayW, displayH))
clock = pygame.time.Clock()
FPS = 60
end = False
food = Food()
player = Player()
# MAIN
def main():
pygame.init()
setGlobalValues()
setup()
gameLoop()
quitGame()
# GAMELOOP
def gameLoop():
global end, player
while not end:
for event in pygame.event.get():
# ONCLICK QUIT
if event.type == pygame.QUIT:
end = True;
# KEYDOWN
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.velX -= 10
if event.key == pygame.K_RIGHT:
player.velX += 10
# KEYUP
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.velX = 0
if event.key == pygame.K_RIGHT:
player.velX = 0
draw()
animate()
collision()
setFPS()
# DRAW
def draw():
global screen, food, player
# fill background
screen.fill((255, 255, 255))
player.draw()
food.draw()
# update
pygame.display.update()
# ANIMATE
def animate():
global food, player
food.animate()
player.animate()
# COLLISION
def collision():
global player, food;
player.collision()
food.collision();
# SETFPS
def setFPS():
global clock, FPS
clock.tick(FPS);
# CLASSES
class Food():
def __init__(self, img="", x=0, h=0, w=0, velY=0, color=()):
global displayW
self.img = pygame.image.load("assets/img/rsz_burger.png")
self.w = 30
self.h = 30
self.x = random.randrange(0, displayW - self.w)
self.y = -100
self.velY = 3
self.color = (255, 0, 0)
def draw(self):
global screen
screen.blit(self.img, (self.x, self.y))
def animate(self):
self.y += self.velY
if self.y >= displayW:
self.reset()
def collision(self):
global displayW, displayH
# collision with player
if self.y >= player.y and self.y <= player.y + player.h and self.x >= player.x and self.x <= player.x + player.w:
player.w += player.increase
player.h += player.increase
player.y - player.increase
print(player.w)
self.reset()
def reset(self):
self.y = -100
self.x = random.randrange(0, displayW - self.w)
self.velY += 1
screen.blit(self.img, (self.x, self.y))
class Player():
def __init__(self, x=0, y=0, velX=0, velY=0, w=0, h=0, increase=0, color=()):
global displayW, displayH
self.w = 20
self.h = 20
self.x = displayW / 2 - self.w / 2
self.y = displayH - 100
self.velX = 0
self.velY = 0
self.increase = 2
self.color = (0, 0, 0)
def draw(self):
global screen
pygame.draw.ellipse(screen, self.color, (self.x, self.y, self.w, self.h))
def animate(self):
self.x += self.velX
self.y += self.velY
def collision(self):
global displayW
# collision to walls
if self.x <= 0:
self.velX = 0
elif self.x + self.h >= displayW:
self.velX = 0
# SETUP
def setup():
pygame.display.set_caption("Food Catcher")
# QUIT GAME
def quitGame():
pygame.quit()
quit()
# CALL MAIN
if __name__ == "__main__":
main()
The problem was that had to minus the player's width
Before:
if self.y >= player.y and self.y <= player.y + player.h and self.x >= player.x and self.x <= player.x + player.w:
player.w += player.increase
player.h += player.increase
player.y - player.increase
After:
if self.y >= player.y - player.h and self.y <= player.y + player.h and self.x >= player.x - player.w and self.x <= player.x + player.w:
player.w += player.increase
player.h += player.increase
player.y - player.increase
I forgot that the objects x and y start at the top left.

python error 'global name 'player' is not defined'

ive been learning python on my own for the past cople months and ive started making games about a weak ago (with pygame) and i have absolutly no idea what i did wrong
this is my code (btw im making pong):
import pygame
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('pong')
clock = pygame.time.Clock()
FPS = 60
class Player():
def __init__(self):
self.padWid = 8
self.padHei = 64
self.x = display_width - 16
self.y = (display_height/2) - (self.padHei/2)
self.speed = 3
self.score = 0
self.scoreFont = pygame.font.Font('freesansbold.ttf', 40)
def scoring(self):
self.text = self.scoreFont.render(str(self.score),True,white)
gameDisplay.blit(self.text, [(display_width * 0.75),30])
def movement(self):
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
self.y -= self.speed
elif key[pygame.K_DOWN]:
self.y += self.speed
if self.y <= 0:
self.y = 0
elif self.y >= display_height - self.padHei:
self.y = display_height - self.padHei
def draw(self):
pygame.draw.rect(gameDisplay, white, [self.x, self.y, self.padWid, self.padHei])
class Enemy():
def __init__(self):
self.padWid = 8
self.padHei = 64
self.x = 16
self.y = (display_height/2) - (self.padHei/2)
self.speed = 3
self.score = 0
self.scoreFont = pygame.font.Font('freesansbold.ttf', 40)
def scoring(self):
self.text = self.scoreFont.render(str(self.score),True,white)
gameDisplay.blit(self.text, [(display_width * 0.23),30])
def movement(self):
key = pygame.key.get_pressed()
if key[pygame.K_w]:
self.y -= self.speed
elif key[pygame.K_s]:
self.y += self.speed
if self.y <= 0:
self.y = 0
elif self.y >= display_height - self.padHei:
self.y = display_height - self.padHei
def draw(self):
pygame.draw.rect(gameDisplay, white, [self.x, self.y, self.padWid, self.padHei])
class Ball():
def __init__(self):
self.x = display_width/2
self.y = display_height/2
self.radius = 4
self.x_speed = -3
self.y_speed = 3
def movement(self):
self.x += self.x_speed
self.y += self.y_speed
if self.y <= self.radius or self.y >= display_height - self.radius:
self.y *= -1
if self.x + self.radius >= display_width:
self.__init__()
enemy.score += 1
elif self.x - self.radius <= 0:
self.__init__()
player.score += 1
for n in range(-self.radius, [player.padHei + self.radius]):
if self.y == player.y + n:
if self.x + self.radius >= player.x:
self.x_speed *= -1
break
n += 1
for n in range(-self.radius, [enemy.padHei + self.radius]):
if self.y == player.y + n:
if self.x - self.radius <= enemy.x + enemy.w:
self.x_speed *= -1
break
n += 1
def draw(self):
pygame.draw.circle(gameDisplay, white, [self.x, self.y], self.radius)
def game_loop():
running = True
player = Player()
enemy = Enemy()
ball = Ball()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
player.movement()
enemy.movement()
ball.movement()
player.draw()
enemy.draw()
ball.draw()
player.scoring()
enemy.scoring()
pygame.display.update()
game_loop()
I always get the following error:
Traceback (most recent call last):
File "C:\programs\python pong\pong.py", line 159, in <module>
game_loop()
File "C:\programs\python pong\pong.py", line 148, in game_loop
ball.movement()
File "C:\programs\python pong\pong.py", line 112, in movement
for n in range(-self.radius, [player.padHei + self.radius]):
NameError: global name 'player' is not defined
You create playerin the function game_loop(), but this variable is local, so you are not able to see it outside that function.
Pass the player as an argument in the ball.movement() function.
In this way:
def movement(self, player):
self.x += self.x_speed
self.y += self.y_speed
...
...
ball.movement(player)

Categories

Resources