So I am trying to implement some collision detection in a little pygame game I am making. However, my code does not seem to be working right. Or I probably just don't know how to implement it. In this game, I have to get the player to the princess without running to goblin. Everything works right but I cannot seem to implement collision detection between player and goblin. Ideally, I would like player to go back to starting position if it hits a goblin. You can see I do have a isCollision function but when I try to call it, I get "NameError: name 'playerX' is not defined"
import pygame
import math
# Initialize the pygame
pygame.init()
# Setting up the screen and background
screen = pygame.display.set_mode((800,600))
# Title and Icon of window
pygame.display.set_caption("Get Princess")
icon = pygame.image.load('knight.png')
pygame.display.set_icon(icon)
#Princess Image
princessImg = pygame.image.load('princess.png')
princessImg = pygame.transform.scale(princessImg, (50,50))
princessX = 360
princessY = 20
princessX_change = 0
princessY_change = 0
class player():
def __init__(self, playerX, playerY, playerX_change, playerY_change):
self.playerX = playerX
self.playerY = playerY
self.playerX_change = playerX_change
self.playerY_change = playerY
self.playerImg = pygame.image.load('knight.png')
self.playerImg = pygame.transform.scale(self.playerImg, (50,50))
self.rect = pygame.Rect(32,32,16,16)
def pdraw(self):
screen.blit(self.playerImg, (self.playerX, self.playerY))
def pmovement(self):
self.playerX += self.playerX_change
self.playerY += self.playerY_change
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.playerY_change = -0.4
if event.key == pygame.K_DOWN:
self.playerY_change = 0.4
if event.key == pygame.K_LEFT:
self.playerX_change = -0.4
if event.key == pygame.K_RIGHT:
self.playerX_change = 0.4
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
self.playerX_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
self.playerY_change = 0
if self.playerX <= 0:
self.playerX = 0
elif self.playerX >= 750:
self.playerX = 750
if self.playerY <= 0:
self.playerY = 0
elif self.playerY >= 550:
self.playerY = 550
class goblin():
def __init__(self, goblinX, goblinY, goblinX_change):
self.goblinX = goblinX
self.goblinY = goblinY
self.goblinX_change = goblinX_change
self.goblinImg = pygame.image.load('goblin.png')
self.goblinImg = pygame.transform.scale(self.goblinImg,(50,50))
def draw(self):
screen.blit(self.goblinImg, (self.goblinX, self.goblinY))
def movement(self):
self.goblinX += self.goblinX_change
if self.goblinX <= 0 or self.goblinX >= 750:
self.goblinX_change = self.goblinX_change * -1
def princess(x,y):
screen.blit(princessImg, (x, y))
p = player(360, 520, 0, 0)
g = goblin(360,250, 0.10)
g1 = goblin(360, 280, 0.5)
g2 = goblin(360, 200, 0.7)
g3 = goblin(360, 160, 0.4)
goblinlist = [g, g1, g2, g3]
def isCollision(playerX, playerY, goblinX, goblinY):
dx = playerX - goblinY
dy = playerY - goblinY
distance = math.sqrt(math.pow(dx,2) + math.pow(dy,2))
if distance < 27:
p = player(360, 520, 0,0)
running = True
while running:
screen.fill((50,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
princess(princessX, princessY)
g.movement()
g.draw()
g1.movement()
g1.draw()
g2.movement()
g2.draw()
g3.movement()
g3.draw()
p.pmovement()
p.pdraw()
isCollision(p.playerX, p.playerY, g1.goblinX, g1.goblinY)
pygame.display.update()
isCollision is a function and playerX, playerY, goblinX, goblinY are the arguments of the function. You don't have a self argument. Usually self is the object in Methods.
Remove all the self. form the function isCollision:
def isCollision(playerX, playerY, goblinX, goblinY):
dx = playerX - goblinX
dy = playerY - goblinY
distance = math.sqrt(math.pow(dx, 2) + math.pow(dy, 2))
return distance < 27
Pass the coordinates of the player (p) and a goblin (g, g1, g2 or g3) to the function:
For instance:
if isCollision(p.playerX, p.playerY, g.goblinX, g.goblinY):
# do something
# [...]
Note, you can create a list of goblins and do the collision test in a loop:
goblin_list = [g, g1, g2, g3]
for gob in goblin_list:
if isCollision(p.playerX, p.playerY, gob.goblinX, gob.goblinY):
# [...]
You can even move and draw the goblins in a loop:
for gob in goblin_list:
gob.movement()
gob.draw()
You need to use the global statement, if you want to change a variable in global namespace:
def isCollision(playerX, playerY, goblinX, goblinY):
global p
dx = playerX - goblinX
dy = playerY - goblinY
distance = math.sqrt(math.pow(dx, 2) + math.pow(dy,2))
if distance < 27:
p = player(360, 520, 0,0)
Related
I rotate an image and I adjust the rect to the rotated image. When I start the program, the image starts moving, without any order by the program. There are, for testing, some pictures needed. I hope, as more experienced users, can take some standards.
import pygame
import sys
from pygame.constants import KEYUP
from pygame.constants import KEYDOWN
import math
import random
pygame.init()
cell_size = 40
cell_number = 20
breite = int(cell_size * cell_number )
hoehe = int( cell_size * cell_number )
screen = pygame.display.set_mode((breite,hoehe))
clock = pygame.time.Clock()
anzahl_gegenstaende = 10 # gehört zu landschaft
class MeinAuto(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(auto_img,(30,66)).convert_alpha()
self.rect = self.image.get_rect(center=(x,y))
self.rect.x = x
self.rect.y = y
self.mask = pygame.mask.from_surface(self.image )
self.wagen_winkel = 0
self.speed = 5
self.links = False
self.rechts = False
self.vor = False
self.zurueck = False
self.lenk_winkel = 0
self.block_vor = False
self.block_zurueck = False
def update(self):
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if self.vor or self.zurueck:
self.links = True
if event.key == pygame.K_RIGHT:
if self.vor or self.zurueck:
self.rechts = True
if event.key == pygame.K_UP:
self.vor = True
if event.key == pygame.K_DOWN:
self.zurueck = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
self.links = False
if event.key == pygame.K_RIGHT:
self.rechts = False
if event.key == pygame.K_UP:
self.vor = False
if event.key == pygame.K_DOWN:
self.zurueck = False
self.winkel_berechnung(1)
dx = math.cos(math.radians(self.wagen_winkel))
dy = math.sin(math.radians(self.wagen_winkel))
if self.vor and self.block_vor == False:
self.rect.y -= int(self.speed * dx)
self.rect.x -= int(self.speed * dy)
self.block_zurueck = False
elif self.zurueck and self.block_zurueck == False:
self.rect.y += int(self.speed * dx)
self.rect.x += int(self.speed * dy)
self.block_vor = False
if self.links:
self.lenk_winkel +=5
self.lenk_winkel=min(self.lenk_winkel,120)
elif self.rechts:
self.lenk_winkel -=1
self.lenk_winkel=max(self.lenk_winkel,-120)
if not self.links and not self.rechts: self.lenk_winkel = 0
def winkel_berechnung(self,dt):
if self.rechts:
self.wagen_winkel += self.lenk_winkel
while self.wagen_winkel < 0:
self.wagen_winkel += 360
elif self.links:
self.wagen_winkel += self.lenk_winkel
while self.wagen_winkel > 359:
self.wagen_winkel -= 360
class Lenkung(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(lenkrad_img,(120,120)).convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.wagen_winkel = 0
class Landschaft(pygame.sprite.Sprite):
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.mask = pygame.mask.from_surface(self.image )
x=random.randrange(60, breite -60)
y=random.randrange(200, hoehe - 200)
self.rect = self.image.get_rect(center =(x,y))
def zeichne_hintergrund():
background = pygame.image.load("Bilder/background_gelb.jpg")
screen.blit(background,(0,0))
def blitRotateCenter(image, left, top, angle):
rotated_image = pygame.transform.rotate(image, angle)
new_rect = rotated_image.get_rect(center = image.get_rect(center = (left, top)).center)
screen.blit(rotated_image, new_rect)
return new_rect
########## Bilder laden
auto_img = pygame.image.load("Bilder/car.png")
lenkrad_img = pygame.image.load("bilder/lenkrad.png")
######### Gruppen bilden
auto = MeinAuto(breite/2,hoehe-100)
auto_sprite = pygame.sprite.Group()
auto_sprite.add(auto)
lenkung = Lenkung(breite/2,60)
lenkung_sprite = pygame.sprite.Group()
lenkung_sprite.add(lenkung)
land = pygame.sprite.Group()
while len(land) < anzahl_gegenstaende:
ii = len(land)
img = pygame.image.load(f"Bilder/Gegenstaende/geg{ii}.png")
img = pygame.transform.scale(img,(100,100))
m = Landschaft(img)
if not pygame.sprite.spritecollide(m, land, False):
land.add(m)
while True:
clock.tick(6)
zeichne_hintergrund()
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
hits = pygame.sprite.spritecollide( auto, land, False, pygame.sprite.collide_mask)
for hit in hits:
pass
auto_sprite.update()
land.draw(screen)
new_auto_rect =blitRotateCenter(auto.image, auto.rect.x, auto.rect.y, auto.wagen_winkel)
auto.rect=new_auto_rect
new_auto_rect = new_auto_rect.inflate(-80,-50)
blitRotateCenter(lenkung.image, lenkung.rect.x, lenkung.rect.y, auto.lenk_winkel)
pygame.draw.rect(screen,(0,250,0),auto.rect,4)
pygame.draw.rect(screen,(250,250,0),new_auto_rect,1)
pygame.display.flip()
Instead of the upper left corner of the image, you have to pass the center of the image to the blitRotateCenter function:
new_auto_rect = blitRotateCenter(auto.image, auto.rect.x, auto.rect.y, auto.wagen_winkel)
new_auto_rect = blitRotateCenter(auto.image, auto.rect.centerx, auto.rect.centery, auto.wagen_winkel)
Simplify the code using the asterisk(*) operator:
new_auto_rect = blitRotateCenter(auto.image, *auto.rect.center, auto.wagen_winkel)
I have recently optimized the enemies in my game goblin() to work through an OOP approach, however, the boundaries that I set for movement() are not working. In this simple game, I have to get the knight aka player() to the princess without hitting the goblin(). When I did this without using an OOP approach, it worked perfectly and the goblin would bounce left and right across the screen. Now, it just goes to the right and keeps on going forever! Super frustrating because before I start adding all of my enemies, I want to have a class that is functional! Thanks!
import pygame
# Initialize the pygame
pygame.init()
# Setting up the screen and background
screen = pygame.display.set_mode((800,600))
# Title and Icon of window
pygame.display.set_caption("Get Princess")
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
#Player Image
playerImg = pygame.image.load('knight.png')
playerImg = pygame.transform.scale(playerImg, (50,50))
playerX = 360
playerY = 520
playerX_change = 0
playerY_change = 0
#Princess Image
princessImg = pygame.image.load('princess.png')
princessImg = pygame.transform.scale(princessImg, (50,50))
princessX = 360
princessY = 20
def player(x,y):
screen.blit(playerImg, (x, y))
def princess(x,y):
screen.blit(princessImg, (x, y))
class goblin():
def __init__(self, goblinX, goblinY):
self.goblinX = goblinX
self.goblinY = goblinY
self.goblinImg = pygame.image.load('goblin.png')
self.goblinImg = pygame.transform.scale(self.goblinImg,(50,50))
def draw(self):
screen.blit(self.goblinImg, (self.goblinX, self.goblinY))
def movement(self, goblinX_change):
self.goblinX_change = goblinX_change
self.goblinX += self.goblinX_change
if self.goblinX <= 0:
self.goblinX_change += 0.3
elif self.goblinX >= 750:
self.goblinX_change = -0.3
g = goblin(360,250)
running = True
while running:
screen.fill((50,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
playerY_change = -0.4
if event.key == pygame.K_DOWN:
playerY_change = 0.4
if event.key == pygame.K_LEFT:
playerX_change = -0.4
if event.key == pygame.K_RIGHT:
playerX_change = 0.4
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
playerX += playerX_change
playerY += playerY_change
if playerX <= 0:
playerX = 0
elif playerX >= 750:
playerX = 750
if playerY <= 0:
playerY = 0
elif playerY >= 550:
playerY = 550
player(playerX,playerY)
princess(princessX, princessY)
g.movement(0.3)
g.draw()
pygame.display.update()
goblinX_change is an attribute of goblin. movement is continuously called in the application loop. This sets the attribute to the initial value in each frame. The initial value has to be set in the constructor and not in the movement method:
class goblin():
def __init__(self, goblinX, goblinY, goblinX_change):
self.goblinX = goblinX
self.goblinY = goblinY
self.goblinX_change = 0.3
self.goblinImg = pygame.image.load('goblin.png')
self.goblinImg = pygame.transform.scale(self.goblinImg,(50,50))
def draw(self):
screen.blit(self.goblinImg, (self.goblinX, self.goblinY))
def movement(self):
self.goblinX += self.goblinX_change
if self.goblinX <= 0:
self.goblinX_change += 0.3
elif self.goblinX >= 750:
self.goblinX_change = -0.3
g = goblin(360, 250, 0.3)
running = True
while running:
# [...]
g.movement()
g.draw()
pygame.display.update()
So my code here has 2 goblins()'s bouncing left and right on the game window, and I have to try to get player() to the princess() without touching a goblin(). However, when I create instances of goblin(), they go to the right and bounce off the window given that goblinX_change is set to 0.3, but when they make it to the left side of the window the game crashes and I get TypeError: Invalif destination position for blit.
import pygame
# Initialize the pygame
pygame.init()
# Setting up the screen and background
screen = pygame.display.set_mode((800,600))
# Title and Icon of window
pygame.display.set_caption("Get Princess")
icon = pygame.image.load('knight.png')
pygame.display.set_icon(icon)
#Player Image
playerImg = pygame.image.load('knight.png')
playerImg = pygame.transform.scale(playerImg, (50,50))
playerX = 360
playerY = 520
playerX_change = 0
playerY_change = 0
#Princess Image
princessImg = pygame.image.load('princess.png')
princessImg = pygame.transform.scale(princessImg, (50,50))
princessX = 360
princessY = 20
def player(x,y):
screen.blit(playerImg, (x, y))
def princess(x,y):
screen.blit(princessImg, (x, y))
class goblin():
def __init__(self, goblinX, goblinY, goblinX_change):
self.goblinX = goblinX
self.goblinY = goblinY
self.goblinX_change = goblinX_change
self.goblinImg = pygame.image.load('goblin.png')
self.goblinImg = pygame.transform.scale(self.goblinImg,(50,50))
def draw(self):
screen.blit(self.goblinImg, (self.goblinX, self.goblinY))
def movement(self):
self.goblinX += self.goblinX_change
if self.goblinX <= 0:
self.goblinX_change += self.goblinX_change
elif self.goblinX >= 750:
self.goblinX_change = -self.goblinX_change
g = goblin(360,250, 0.3)
g1 = goblin(360, 280, 0.3)
running = True
while running:
screen.fill((50,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
playerY_change = -0.4
if event.key == pygame.K_DOWN:
playerY_change = 0.4
if event.key == pygame.K_LEFT:
playerX_change = -0.4
if event.key == pygame.K_RIGHT:
playerX_change = 0.4
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
playerX += playerX_change
playerY += playerY_change
if playerX <= 0:
playerX = 0
elif playerX >= 750:
playerX = 750
if playerY <= 0:
playerY = 0
elif playerY >= 550:
playerY = 550
player(playerX,playerY)
princess(princessX, princessY)
g.movement()
g.draw()
g1.movement()
g1.draw()
pygame.display.update()
When the goblinX reaches 0, you need to reverse the direction:
def movement(self):
self.goblinX += self.goblinX_change
if self.goblinX <= 0:
self.goblinX_change = -self.goblinX_change # update this line
self.goblinX = 0
elif self.goblinX >= 750:
self.goblinX_change = -self.goblinX_change
When the goblin is at the left border, the movement must become positive (abs(self.goblinX_change)) and when the goblin is at the right border, the movement must become negative (-abs(self.goblinX_change)):
class goblin():
# [...]
def movement(self):
self.goblinX += self.goblinX_change
if self.goblinX <= 0:
self.goblinX_change = abs(self.goblinX_change)
elif self.goblinX >= 750:
self.goblinX_change = -abs(self.goblinX_change)
Alternatively you can change the direction, if the goblin is at the left border and moves to the left, or is at the right border and moves to the right:
class goblin():
# [...]
def movement(self):
self.goblinX += self.goblinX_change
if (self.goblinX <= 0 and self.goblinX_change < 0) or \
(self.goblinX >= 750 and self.goblinX_change > 0):
self.goblinX_change *= -1
I recently started programming in pygame and I've been wondering why doesn't my isCollision function work. You don't really have to run the code, because you will need to download the pictures to make it execute. If you can, just tell my why the isCollision function doesn't work. In the mainloop where there is a for i in range(num_of_obstacles) loop there is the if iscollision statement. If you want to see what the program does, here are all the essential files:
Btw don't rewrite the entire code pls.]2[]3
Don't mind the comments cause theyre in polish.
Here is my code:
import pygame
import math
import random
#inicjowanie pygame (to trzeba zawsze dać)
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Kosmiczna Przygoda')
playericon = pygame.image.load('rocket.png')
player2icon = pygame.image.load('rocket.png')
backgroundImg = pygame.image.load('1083.jpg')
num_of_obstacles = 10
obstacleImg = []
obsX = [random.randint(0, 400) for i in range(num_of_obstacles // 2)]
obs2X = [random.randint(400, 800) for i in range(num_of_obstacles // 2)]
for i in obs2X:
obsX.append(i)
obsY = []
for i in range(num_of_obstacles):
obstacleImg.append(pygame.image.load('rectangle.png'))
for i in range(num_of_obstacles):
obsY.append(random.randint(50, 300))
# pierwsze koordynaty
PlayerX, PlayerY = 200, 480
Player2X, Player2Y = 500, 480
PlayerY_change, PlayerX_change = 1, 1
Player2Y_change, Player2X_change = 1, 1
def player(x,y,x2,y2):
screen.blit(playericon, (x, y))
screen.blit(player2icon, (x2, y2))
winFont = pygame.font.Font('freesansbold.ttf', 64)
won1, won2 = False, False
def player1Wins():
win_text = winFont.render('PLAYER 1 WON!',True,(255,255,255))
screen.blit(win_text,(30,30))
def player2Wins():
win_text = winFont.render('PLAYER 2 WON!',True,(255,255,255))
screen.blit(win_text,(150,30))
# wzór matematyczny na odległość koordynatów dwóch punktów (sprawdzabnie czy się dotykają)
def isCollision(obsX,obsY,pX,pY):
distance = math.sqrt(math.pow(obsX - pX, 2) + math.pow(obsY - pY, 2))
if distance >= 27:
return True
else:
return False
running = True
won = False
while running:
# tło (blit to rysowanie)
screen.blit(backgroundImg, (0, 0))
# event to wydarzenie zarejestrowane przez program
# jeżeli klikne krzyzyk w prawym gornym rogu to program sie zamknie
# jeżeli nacisne np strzalke w prawo to rakieta przesuwa się na ukos w prawo
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
PlayerX_change = -1
if event.key == pygame.K_d:
PlayerX_change = 1
if event.key == pygame.K_LEFT:
Player2X_change = -1
if event.key == pygame.K_RIGHT:
Player2X_change = 1
if event.key == pygame.K_w:
PlayerY_change = 2
if event.key == pygame.K_UP:
Player2Y_change = 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
PlayerY2_change = 0.75
if event.key == pygame.K_w:
PlayerY_change = 0.75
for enemy in range(num_of_obstacles):
if won:
screen.blit(obstacleImg[enemy], (2000, 2000))
else:
#if isCollision(obsX[enemy], obsY[enemy],PlayerX,PlayerY):
#player2Wins()
screen.blit(obstacleImg[enemy], (obsX[enemy], obsY[enemy]))
# Granice Ekranu
if PlayerX <= 0:
PlayerX = 0
elif PlayerX >= 736:
PlayerX = 736
if PlayerY <= 0:
won, won1 = True, True
PlayerY, Player2Y = 480, 480
PlayerX, Player2X = 200, 500
if Player2X <= 0:
Player2X = 0
elif Player2X >= 736:
Player2X = 736
if Player2Y <= 0:
won, won2 = True, True
PlayerY, Player2Y = 480, 480
PlayerX, Player2X = 200, 500
if won1:
player1Wins()
PlayerX_change, PlayerY_change = 0, 0
Player2X_change, Player2Y_change = 0, 0
if won2:
player2Wins()
PlayerX_change, PlayerY_change = 0, 0
Player2X_change, Player2Y_change = 0, 0
# Zmiana kordynatów rakiety
PlayerX += PlayerX_change
PlayerY -= PlayerY_change
Player2X += Player2X_change
Player2Y -= Player2Y_change
player(PlayerX, PlayerY, Player2X, Player2Y)
pygame.display.update()
Should you be checking if the distance is <= 27 rather than >= 27?
def isCollision(obsX, obsY, pX, pY):
distance = math.sqrt(math.pow(obsX - pX, 2) + math.pow(obsY - pY, 2))
return distance <= 27
While doing some test in python, one of the sprites in a Player class randomly started duplicating itself.. I can't figure it out.. (I realize it's probally something really simple)
Here's the code:
import pygame
from pygame.locals import *
import time
pygame.font.init()
myfont = pygame.font.SysFont("mirc", 25)
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
health = 10
keys = {"w":False, "a":False, "s":False, "d":False, " ":False}
class Thing:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [360, 240]
def draw(self, screen):
screen.blit(self.texture, tuple([int(e) for e in self.position]))
def move(self, direction, distance):
if direction == "UP":
self.position[1] -= distance
elif direction == "DOWN":
self.position[1] += distance
elif direction == "RIGHT":
self.position[0] += distance
elif direction == "LEFT":
self.position[0] -= distance
class Enemy:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [15, 110]
def draw(self, screen):
screen.blit(self.texture, tuple([int(e) for e in self.position]))
def move(self, distance):
if player.direction == "UP":
self.position[1] -= distance
elif player.direction == "DOWN":
self.position[0] -= distance
elif player.direction == "RIGHT":
self.position[1] += distance
elif player.direction == "LEFT":
self.position[1] += distance
done = False
black = (0, 0, 0)
player = Thing("2.png")
enemy = Enemy("1.png")
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_w:
keys["w"] = True
if event.key == K_a:
keys["a"] = True
if event.key == K_s:
keys["s"] = True
if event.key == K_d:
keys["d"] = True
if event.key == K_SPACE:
keys[" "] = True
if event.type == KEYUP:
if event.key == K_w:
keys["w"] = False
if event.key == K_a:
keys["a"] = False
if event.key == K_s:
keys["s"] = False
if event.key == K_d:
keys["d"] = False
if event.key == K_SPACE:
keys[" "] = False
#Consistent movement
if keys["w"]:
player.move("UP", 2)
if keys["a"]:
player.move("LEFT", 2)
if keys["s"]:
player.move("DOWN", 2)
if keys["d"]:
player.move("RIGHT", 2)
#if keys[" "]:
#Shoot..
#Walls - Player
if player.position[1] <= -2:
player.position[1] += 2
if player.position[1] >= 433:
player.position[1] -= 2
if player.position[0] <= -2:
player.position[0] += 2
if player.position[0] >= 690:
player.position[0] -= 2
#Walls - Enemy
if enemy.position[1] <= -2:
enemy.position[1] += 2
if enemy.position[1] >= 433:
enemy.position[1] -= 2
if enemy.position[0] <= -2:
enemy.position[0] += 2
if enemy.position[0] >= 690:
enemy.position[0] -= 2
#Text
label = myfont.render("Health: " + str(health), 50, (255, 255, 255))
screen.blit(label, (5, 5))
player.draw(screen)
pygame.display.flip()
pygame.quit()
Turns out my original answer was close - your problem is that you're simply drawing the image - you never fill the screen even though you've declared black = (0, 0, 0). You need to put screen.fill(black) before you start drawing everything else.
For the record, here is what a Minimal, Complete, and Verifiable example looks like:
import pygame
from pygame.locals import *
import time
pygame.font.init()
myfont = pygame.font.SysFont("mirc", 25)
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
class Thing:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [360, 240]
def draw(self, screen):
screen.blit(self.texture, self.position)
done = False
black = (0, 0, 0)
player = Thing(os.path.expanduser("~/Downloads/disapproval.png"))
x_direction = 1
y_direction = 0
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if player.position[0] < 400:
x_direction = 1
y_direction = 0
elif player.position[0] >= 400 and player.position[1] > 100:
x_direction = 0
y_direction = -1
else:
x_direction = 0
y_direction = 0
player.position[0] += x_direction
player.position[1] += y_direction
# Uncomment this line, and you'll fix your problem
#screen.fill(black)
player.draw(screen)
pygame.display.flip()
pygame.quit()
disapproval.png