how to use collide direct for multiple sprites - python

#sprites
import random, sys, time, math, pygame
from pygame.locals import *
from pygame import mixer # Load the required library
FPS = 30 # frames per second to update the screen
fpsClock = pygame.time.Clock()
WINWIDTH = 1500 # width of the program's window, in pixels
WINHEIGHT = 1000 # height in pixels
HALF_WINWIDTH = int(WINWIDTH / 2)
HALF_WINHEIGHT = int(WINHEIGHT / 2)
moveX,moveY=0,0
move2X,move2Y=0,0
GRASSCOLOR = (24, 255, 0)
WHITE = (255, 255, 255)
PURPLE = (128, 0, 128)
RED = (255, 0, 0)
pygame.init()
global FPSCLOCK, DISPLAYSURF, self
DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))
pygame.display.set_icon(pygame.image.load('god.png'))
pygame.display.set_caption('Smash Bros Melee')
BASICFONT = pygame.font.Font('freesansbold.ttf', 32)
class Sprite:
def __init__(self,x,y):
self.x=x
self.y=y
self.width=50
self.height=50
self.i0= pygame.image.load('ryanrenolds.jpeg')
self.timeTarget=10
self.timeNum=0
self.currentImage=0
def render(self):
DISPLAYSURF.blit(self.i0, (self.x, self.y))
player=Sprite(0,0)
class Sprite2:
def __init__(self,x,y):
self.x=x
self.y=y
self.width=50
self.height=50
self.i0= pygame.image.load('ArkhamKnight.png')
self.i1= pygame.image.load('Black-Panther.png')
self.timeTarget=10
self.timeNum=0
self.currentImage=0
def update(self):
self.timeNum+=1
if (self.timeNum==self.timeTarget):
if (self.currentImage==0):
self.currentImage+=1
else:
self.currentImage=0
self.timeNum=0
self.render()
def render(self):
if(self.currentImage==0):
DISPLAYSURF.blit(self.i0, (self.x, self.y))
else:
DISPLAYSURF.blit(self.i1, (self.x, self.y))
player2=Sprite2(200,300)
def checkCollision(Sprite, Sprite2):
col = Sprite.rect.colliderect(Sprite2.rect)
if col == True:
sys.exit()
while True:
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == K_a:
moveX = moveX - 0
elif event.key == K_d:
moveX == False
elif event.key == K_w:
moveY == False
elif event.key == K_s:
moveY == False
if (event.type==pygame.KEYDOWN):
if (event.key==pygame.K_a):
moveX = moveX - 5
elif (event.key==pygame.K_d):
moveX = moveX + 5
elif (event.key==pygame.K_w):
moveY = moveY - 5
elif (event.key==pygame.K_s):
moveY = moveY + 5
elif (event.key==pygame.K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYUP:
if event.key == K_LEFT:
move2X = move2X - 0
elif event.key == K_RIGHT:
move2X == False
elif event.key == K_UP:
move2Y == False
elif event.key == K_DOWN:
move2Y == False
if (event.type==pygame.KEYDOWN):
if (event.key==pygame.K_LEFT):
move2X = move2X - 5
elif (event.key==pygame.K_RIGHT):
move2X = move2X + 5
elif (event.key==pygame.K_UP):
move2Y = move2Y - 5
elif (event.key==pygame.K_DOWN):
move2Y = move2Y + 5
elif (event.key==pygame.K_o):
player=Sprite(0,0)
player2=Sprite2(200,300)
elif (event.key==pygame.K_ESCAPE):
pygame.quit()
sys.exit()
DISPLAYSURF.fill(PURPLE)
player.x+=moveX
player.y+=moveY
player2.x+=move2X
player2.y+=move2Y
player.render()
player2.update()
checkCollision(Sprite, Sprite2)
pygame.display.update()
fpsClock.tick(FPS)
pygame.quit()
sys.exit()
how do i get to wear my sprites will collide my collide direct code asks for three arguements when i used self in the parameters but when i took self out it says that class Sprite has no attribute 'rect'
This the error i keep getting how do i fix this to where my game works to where my sprites will exit the game if they collide with each other
Traceback (most recent call last):
File "C:\Python27\Sprites\sprites.py", line 159, in
checkCollision(Sprite, Sprite2)
File "C:\Python27\Sprites\sprites.py", line 88, in checkCollision
col = Sprite.rect.colliderect(Sprite2.rect)
AttributeError: class Sprite has no attribute 'rect'

You don't have the attribute rect in your Sprite class, which is causing this problem. You also need an attribute rect in your Sprite2 class. You can do this by using the get_rect() method.
You can do this in your Sprite class by entering this in the __init__(self)
self.rect = self.i0.get_rect()
And for the Sprite2 class you can do this (because displayed image can change, put this in the update().)
if self.currentImage == 0:
self.rect = self.i0.get_rect()
elif self.currentImage == 1:
self.rect = self.i1.get_rect()
I hope this helps.

Related

Second surface doesn't appear on screen until I freeze the game

I'm trying out Pygame and started with a classic, creating the Snake game, the issue is that I try to blit the 'apple' on the board but the apple doesn't appear up until I crash in the walls this is when I set fps = 0 and I freeze the game. I've noticed that when I increase the fps to something like 100 or more the apple starts appearing and disappearing.
import random
import pygame
class Game:
def __init__(self):
pygame.init()
self.board = pygame.display.set_mode((400, 400))
self.apple = Apple(self.board)
self.snake = Snake(self.board, self)
self.direction = 'right'
self.going = True
self.fps = 5
def play(self):
clock = pygame.time.Clock()
while self.going:
clock.tick(self.fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.going = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.direction = 'left'
if event.key == pygame.K_RIGHT:
self.direction = 'right'
if event.key == pygame.K_UP:
self.direction = 'up'
if event.key == pygame.K_DOWN:
self.direction = 'down'
self.apple.spawn()
self.snake.move(self.direction)
def game_over(self):
self.fps = 0
def get_fps(self):
return self.fps
class Snake:
def __init__(self, board, game):
self.board = board
self.image = pygame.Surface((10, 10))
self.game = game
self.length = 5
self.x = [10] * self.length
self.y = [10] * self.length
def move(self, direction):
for i in range(self.length-1, 0, -1):
self.x[i] = self.x[i-1]
self.y[i] = self.y[i-1]
if direction == 'right':
self.x[0] += 10
if direction == 'left':
self.x[0] -= 10
if direction == 'up':
self.y[0] -= 10
if direction == 'down':
self.y[0] += 10
if self.x[0] == self.board.get_width() or self.x[0] == -10 or\
self.y[0] == self.board.get_height() or self.y[0] == -10:
self.game.game_over()
if self.game.get_fps() != 0:
self.draw()
def draw(self):
self.board.fill((0, 255, 0))
for i in range(self.length):
self.board.blit(self.image, (self.x[i], self.y[i]))
pygame.display.flip()
class Apple:
def __init__(self, board):
self.board = board
self.image = pygame.Surface((10, 10))
self.image.fill(pygame.color.Color('red'))
self.x = random.randint(0, self.board.get_width())
self.y = random.randint(0, self.board.get_height())
def spawn(self):
self.board.blit(self.image, (self.x, self.y))
pygame.display.flip()
if __name__ == '__main__':
game = Game()
game.play()
Clear the display at the begin of the application loop and update the dispaly at the end of the application loop:
class Game:
# [...]
def play(self):
clock = pygame.time.Clock()
while self.going:
clock.tick(self.fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.going = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.direction = 'left'
if event.key == pygame.K_RIGHT:
self.direction = 'right'
if event.key == pygame.K_UP:
self.direction = 'up'
if event.key == pygame.K_DOWN:
self.direction = 'down'
self.board.fill((0, 255, 0)) # <---
self.apple.spawn()
self.snake.move(self.direction)
pygame.display.flip() # <---
class Snake:
# [...]
def draw(self):
# self.board.fill((0, 255, 0)) <-- DELETE
for i in range(self.length):
self.board.blit(self.image, (self.x[i], self.y[i]))
# pygame.display.flip() <-- DELETE
class Apple:
# [...]
def spawn(self):
self.board.blit(self.image, (self.x, self.y))
#pygame.display.flip() <-- DELETE
fill clears the entire Surface. Everything that was previously drawn is lost.
One update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.

Increasing Pygame Image size after collision?

So I'm just learning how to work with classes and getting them to work between each different class. I'm trying to design a game where the user moves around and picks up food and each time the user picks up a piece of food the size of the character increases. I've done something similar before but now that there are classes involved I seem to have a hard time finding which class this should be part of. I added within the sprite update method that if it collides with a cherry then the size of the player should increase by 5 pixels each time. using the code :
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
Each time the game runs the player size doesn't change and for some reason the game no longer ends after the player has eaten a certain amount of cherries so I was just wondering if I was using a wrong method of changing the size of the player perhaps there may be an easier way to do so? Heres the rest of the code incase it helps at all.
import pygame, glob, random, time
from pygame.locals import *
from LabelClass import *
# CONSTANTS
WIDTH = 400 # Window width
HEIGHT = 400 # Window height
BLACK = (0,0,0) # Colors
WHITE = (255,255,255)
BACKGR = BLACK # Background Color
FOREGR = WHITE # Foreground Color
FPS = 40 # Frames per second
pwidth = 40
pheight = 40
class Food:
def __init__(self,screen,centerx,centery):
self.screen = screen
self.surface = pygame.image.load('cherry.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
class Player:
def __init__(self, screen, centerx,
centery, speed, backcolor):
self.surface = pygame.image.load('player.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
self.speed = speed
self.screen = screen
self.backcolor = backcolor
self.dir = ''
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
def move(self):
if self.dir != '':
if self.dir == 'd' and self.rect.bottom < HEIGHT:
self.rect.top += self.speed
if self.dir == 'u' and self.rect.top > 0:
self.rect.top -= self.speed
if self.dir == 'l' and self.rect.left > 0:
self.rect.left -= self.speed
if self.dir == 'r' and self.rect.right < WIDTH:
self.rect.right += self.speed
def jump(self,top,left):
self.rect.top = top
self.rect.left = left
class SpritesGame:
def __init__(self,screen):
self.screen = screen
screen.fill(BLACK)
pygame.display.update()
music_file = getRandomMusic()
pygame.mixer.music.load(music_file)
pygame.mixer.music.play(-1,0.0)
self.music = True
self.Foods = [ ]
self.Eaten = 0
for i in range(20):
self.Foods.append(
Food(self.screen,
WIDTH*random.randint(1,9)//10,
HEIGHT*random.randint(1,9)//10))
for f in self.Foods:
f.draw()
self.Player = Player(screen,WIDTH//2,HEIGHT//2,6,BLACK)
self.PickUpSound = pygame.mixer.Sound('pickup.wav')
self.PlaySound = True
self.startTime = time.clock()
self.endTime = -1
self.Won = False
def update(self):
self.screen.fill(BLACK)
pickedUp = False
for f in self.Foods[:]:
if self.Player.rect.colliderect(f.rect):
self.Foods.remove(f)
self.Foods.append(Food(self.screen,WIDTH*random.randint(1,9)//10,HEIGHT*random.randint(1,9)//10))
pickedUp = True
self.Eaten += 1
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
#self.rect.center = center
print self.Eaten
if pickedUp and self.PlaySound:
self.PickUpSound.play()
for f in self.Foods:
f.draw()
if self.Eaten == 40:
self.Won = True
self.endTime = time.clock()
self.Player.move()
self.Player.draw()
pygame.display.update()
def toggleMusic(self):
self.music = not self.music
if self.music:
pygame.mixer.music.play(-1,0.0)
else:
pygame.mixer.music.stop()
def run(self):
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYDOWN: # Keeps moving as long as key down
if event.key == K_LEFT or event.key == ord('a'):
self.Player.dir = 'l'
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = 'r'
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = 'u'
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = 'd'
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
if event.key == K_ESCAPE:
stop = True
if event.key == K_LEFT or event.key == ord('a'): # End repetition.
self.Player.dir = ''
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = ''
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = ''
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = ''
if event.key == ord('x'):
top = random.randint(0,
HEIGHT - self.Player.rect.height)
left = random.randint(0,
WIDTH - self.Player.rect.width)
self.Player.jump(top,left)
if event.key == ord('m'):
self.toggleMusic()
if event.key == ord('p'):
self.PlaySound = not self.PlaySound
mainClock.tick(FPS)
self.update()
if self.Won:
stop = True # END OF WHILE
if self.Won:
self.screen.fill(BLACK)
pygame.display.update()
msg = (str((int(self.endTime)
-int(self.startTime)))
+" seconds to finish. Hit Q.")
L2 = Label(display,WIDTH//2,HEIGHT*7//8,26,msg,WHITE,BLACK)
L2.draw()
stop = False
while not stop:
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
pygame.event.get()
pygame.mixer.music.stop()
def getRandomMusic():
mfiles = glob.glob("*.wav")
mfiles.append(glob.glob("*.mid"))
r = random.randint(0,len(mfiles)-1)
return mfiles[r]
def OpeningScreen(screen):
screen.fill(BLACK)
pygame.display.update()
L1 = Label(display,WIDTH//2,HEIGHT*7//8,26,"Hit Q to Quit, P to Play.",WHITE, BLACK)
L1.draw()
# Properly initiate pygame
pygame.init()
# pygame.key.set_repeat(INT,INT)
# Set the clock up
mainClock = pygame.time.Clock()
# Initialize Display
display = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Sprites and Sounds V06')
OpeningScreen(display)
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYUP:
if event.key == ord('p'):
game = SpritesGame(display)
game.run()
OpeningScreen(display)
if event.key == ord('q'):
stop = True
pygame.quit()
Surface.get_rect() will always return a rect starting at (0,0), and you also are modifying SpritesGame.rect. I think you should change
self.rect = self.Player.surface.get_rect()
to
self.Player.rect.inflate_ip(5, 5)

Pygame animation using mutiple images overlapping/not working

import pygame
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("TEST2")
black=(0,0,0)
white=(255,255,255)
moveX,moveY=0,0
clock = pygame.time.Clock()
class Sprite:
def __init__(self,x,y):
self.x=x
self.y=y
self.width=100
self.height=110
self.i100 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite0.PNG")
self.i1 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite1.PNG")
self.i2 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite2.PNG")
self.i3 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite3.PNG")
self.i4 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite4.PNG")
self.i5 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite5.PNG")
self.i6 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite6.PNG")
self.i7 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite7.PNG")
self.i8 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite8.PNG")
self.i9 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite9.PNG")
self.i10 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite10.PNG")
self.i11 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite11.PNG")
self.timeTarget=10
self.timeNum=0
self.currentImage=0
def update(self):
self.timeNum+=1
if(self.timeNum==self.timeTarget):
if (self.currentImage==0):
self.currentImage+=1
else:
self.currentImage=0
self.timeNum=0
self.render()
def render(self):
if (self.currentImage==0):
window.blit(self.i100, (self.x,self.y))
else:
window.blit(self.i1, (self.x,self.y))
window.blit(self.i2, (self.x,self.y))
window.blit(self.i3, (self.x,self.y))
player=Sprite(110,100)
gameLoop = True
while gameLoop:
for event in pygame.event.get():
if event.type==pygame.QUIT:
gameLoop = False
if (event.type==pygame.KEYDOWN):
if (event.key==pygame.K_LEFT):
moveX = -3
if (event.key==pygame.K_RIGHT):
moveX = 3
if (event.key==pygame.K_UP):
moveY = -3
if (event.key==pygame.K_DOWN):
moveY = 3
if (event.type==pygame.KEYUP):
if (event.key==pygame.K_LEFT):
moveX=0
if (event.key==pygame.K_RIGHT):
moveX=0
if (event.key==pygame.K_UP):
moveY=0
if (event.key==pygame.K_DOWN):
moveY=0
window.fill(black)
player.x+=moveX
player.x+=moveY
player.update()
clock.tick(50)
pygame.display.flip()
pygame.quit()
What im doing is trying to animate 11 photos into an animation with pygame. this code works but when I run it the pictures seem to almost overlap. I did window.blit for the first few images and put them under else? I feel like I rendered them wrong. also I must add im really bad at picking up what people are trying to say and best learn from examples. Thanks!
BTW: your code could look like this:
I use my images in example but there are still lines with your images.
I use timer to change images.
You can press space to pause and escape to exit.
etc.
import pygame
#----------------------------------------------------------------------
class Sprite:
def __init__(self, x, y, curren_time):
self.rect = pygame.Rect(x, y, 100, 110)
self.images = []
#for x in range(12):
for x in range(1,4):
img = pygame.image.load("ball" + str(x) +".png")
#img = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite" + str(x) +".PNG")
self.images.append( img )
self.current_image = 0
self.time_num = 100 # miliseconds
self.time_target = curren_time + self.time_num
def update(self, curren_time):
if curren_time >= self.time_target:
self.time_target = curren_time + self.time_num
self.current_image += 1
if self.current_image == len(self.images):
self.current_image = 0
def render(self, window):
window.blit(self.images[self.current_image], self.rect)
#----------------------------------------------------------------------
# CONSTANS - uppercase
BLACK = (0 ,0 ,0 )
WHITE = (255,255,255)
#----------------------------------------------------------------------
# MAIN
def main():
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("TEST2")
move_x, move_y = 0, 0
clock = pygame.time.Clock()
curren_time = pygame.time.get_ticks()
player = Sprite(110,100, curren_time)
font = pygame.font.SysFont(None, 150)
pause_text = font.render("PAUSE", 1, WHITE)
pause_rect = pause_text.get_rect( center = window.get_rect().center ) # center text on screen
# mainloop
state_game = True
state_pause = False
while state_game:
curren_time = pygame.time.get_ticks()
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
state_game = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
state_game = False
elif event.key == pygame.K_SPACE:
state_pause = not state_pause
if event.key == pygame.K_LEFT:
move_x = -3
elif event.key == pygame.K_RIGHT:
move_x = 3
elif event.key == pygame.K_UP:
move_y = -3
elif event.key == pygame.K_DOWN:
move_y = 3
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
move_x = 0
elif event.key in (pygame.K_UP, pygame.K_DOWN):
move_y = 0
# moves
if not state_pause:
player.rect.x += move_x
player.rect.y += move_y
player.update(curren_time)
# draws
window.fill(BLACK)
player.render(window)
if state_pause:
window.blit(pause_text, pause_rect)
pygame.display.flip()
# FPS
clock.tick(50)
# the end
pygame.quit()
#----------------------------------------------------------------------
if __name__ == '__main__':
main()
ball1.png
ball2.png
ball3.png
By putting all those window.blit(...) calls one after another, you are drawing those three frames on top of each other. Even if your computer lagged for a second between each call, you still wouldn't see them individually because they all can't appear until pygame.display.flip() is called.
You should store the images in a list, and keep a counter like currentFrame that loops from 0 to number_of_frames-1 (or len(frames)-1). Then each frame of the game you do something like this:
class Player:
...
def draw(window):
window.blit(self.frames[self.currentFrame])

Pygame sprite touching

I am attempting to build a simple game with two sprites. I can't figure out how to add code that detects if a sprite is touching the other. I am also having trouble understanding the countless tutorials on this topic. If you could try and explain this to me as simply as possible that would be amazing!
import pygame
import sys
from pygame.locals import *
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
bg = black
square = pygame.image.load('square.png')
square1 = pygame.image.load('square1.png')
screen = pygame.display.set_mode((640, 400))
UP = 'UP'
DOWN = 'DOWN'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
direction = RIGHT
movex, movey, movex1, movey1 = 100, 100, 200, 200
class player1(pygame.sprite.Sprite):
"""Player 1"""
def __init__(self, xy):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('square.png')
self.rect = self.image.get_rect()
class player2(pygame.sprite.Sprite):
"""Player 2"""
def __init__(self, xy):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('square1.png')
self.rect = self.image.get_rect()
while True:
screen.fill(black)
collide = pygame.sprite.collide_mask(player1, player2)
if collide == True:
print 'collision!'
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_w:
movey -= 10
elif event.key == K_s:
movey += 10
elif event.key == K_a:
movex -= 10
elif event.key == K_d:
movex += 10
if event.key == K_UP:
movey1 -= 10
elif event.key == K_DOWN:
movey1 += 10
elif event.key == K_LEFT:
movex1 -= 10
elif event.key == K_RIGHT:
movex1 += 10
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(square, (movex, movey))
screen.blit(square1, (movex1, movey1))
pygame.display.update()
Some issues first:
pygame.sprite.collide_mask never returns True. It returns a point or None. So your check collide == True will never be evaluate to True
pygame.sprite.collide_mask excepts two Sprite instances, but you call it with class objects as arguments (collide_mask(player1, player2))
You only need pygame.sprite.collide_mask when you want to do pixel perfect collision detection
You actually don't use the classes player1 and player2 in the rest of your code
If you're using the Sprite class, a simply way for collision detection is to use the Group class. But since you only have two Sprites, you can simple check for an intersection of their Rects using colliderect.
I've updated your code to make use of the Sprite class:
import pygame
import sys
from pygame.locals import *
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((640, 400))
class Player(pygame.sprite.Sprite):
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect(x=x, y=y)
player1, player2 = Player('square.png', 100, 100), Player('square1.png', 200, 200)
players = pygame.sprite.Group(player1, player2)
while True:
screen.fill(black)
if player1.rect.colliderect(player2.rect):
print 'collision!'
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_w:
player1.rect.move_ip(0, -10)
elif event.key == K_s:
player1.rect.move_ip(0, 10)
elif event.key == K_a:
player1.rect.move_ip(-10, 0)
elif event.key == K_d:
player1.rect.move_ip(10, 0)
if event.key == K_UP:
player2.rect.move_ip(0, -10)
elif event.key == K_DOWN:
player2.rect.move_ip(0, 10)
elif event.key == K_LEFT:
player2.rect.move_ip(-10, 0)
elif event.key == K_RIGHT:
player2.rect.move_ip(10, 0)
if event.type == QUIT:
pygame.quit()
sys.exit()
players.draw(screen)
pygame.display.update()
Collision detection is a broad topic, but this should get you started.

How Would I Display the Score in this Simple Game?

I've tried using the blit function to paste it to the surface but that didn't work because I couldn't use a surface as a source for the score as I did with the player, enemy, and food variables. I also tried using self.score = Score((75, 575)) but that didn't work because for some reason it said "self" wasn't defined. How can I display the score onto the screen?
import os, sys
import pygame
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
WINDOWWIDTH = 1000
WINDOWHEIGHT = 700
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption("Avoid!")
BLACK = (0, 0, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
player = pygame.Rect(500, 300, 40, 40)
playerImage = pygame.Surface((40, 40))
enemy = pygame.Rect(300, 400, 20, 20)
enemyImage = pygame.Surface((20, 20))
enemyImage.fill((RED))
food = pygame.Rect(300, 500 , 20, 20)
foodImage = pygame.Surface((20, 20))
foodImage.fill((GREEN))
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVESPEED = 6
class Score(pygame.sprite.Sprite):
"""A sprite for the score."""
def __init__(self, xy):
pygame.sprite.Sprite.__init__(self)
self.xy = xy #save xy -- will center our rect on it when we change the score
self.font = pygame.font.Font(None, 50) # load the default font, size 50
self.color = (255, 165, 0) # our font color in rgb
self.score = 0 # start at zero
self.reRender() # generate the image
def update(self):
pass
def add(self, points):
"""Adds the given number of points to the score."""
self.score += points
self.reRender()
if player.colliderect(food):
return add
def reset(self):
"""Resets the scores to zero."""
self.score = 0
self.reRender()
def reRender(self):
"""Updates the score. Renders a new image and re-centers at the initial coordinates."""
self.image = self.font.render("%d"%(self.score), True, self.color)
self.rect = self.image.get_rect()
self.rect.center = self.xy
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
moveRight = False
moveLeft = True
if event.key == K_RIGHT:
moveLeft = False
moveRight = True
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == K_DOWN:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT:
moveRight = False
moveLeft = True
if event.key == K_RIGHT:
moveLeft = False
moveRight = True
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == K_DOWN:
moveUp = False
moveDown = True
windowSurface.fill(WHITE)
if moveDown and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUp and player.top > 0:
player.top -= MOVESPEED
if moveLeft and player.left > 0:
player.left -= MOVESPEED
if moveRight and player.right < WINDOWWIDTH:
player.right +=MOVESPEED
if player.colliderect(enemy):
pygame.quit()
sys.exit()
windowSurface.blit(playerImage, player)
windowSurface.blit(enemyImage, enemy)
windowSurface.blit(foodImage, food)
score = Score((75, 575))
pygame.display.update()
mainClock.tick(40)
Your problem isn't with blit or any other part of pygame; it is with your use of the self keyword. Self is a reference to an object's attributes. You do not call self.score outside of the Score class itself.
Instead, initialize a score object in the beginning of the game and add to the score as needed. This is how it should work:
# init Score object
my_score = Score((75, 575))
# add to score like this
my_score.add(5)
# access score attribute like this
# for simplicity, I print the value to the console
print my_score.score # not self.score!
print() outputs text to stdout (aka the command line). I thought your problem was just with self and that you understand the part about pygame.
Here is a code block I found online that does what you are trying to do:
font = pygame.font.Font(None, 36)
text = font.render("Pummel The Chimp, And Win $$$", 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2)
background.blit(text, textpos)

Categories

Resources