pscreenTest_Mouse&Collision.py
pscreenTest_Mouse&Collision.py
—
Python Source,
2Kb
File contents
#Example showing mouse input and collision detection
#An image is necessary for this example to work!
import pscreen
pscreen.LoadScreen((400, 400), False, "pygame")
#Make sure this points to the name of your image and it is in the same directory
#as your script
spriteName = "example_sprite.png"
#Load a sprite into slot 0
pscreen.SpriteLoad(spriteName, 0)
#Font write
pscreen.FontSelect("Arial", 16)
#Declare some variables to keep track of the mouse position
mouseX = 0
mouseY = 0
#Declare some variables to keep track of the sprite's top left corner
posX = 0
posY = 0
#Declare a sequence of rectangles
boxes = [(30, 40, 110, 70), (310, 230, 380, 260), (100, 240, 130, 270), (300, 40, 320, 80)]
#Game loop
while True:
#Clear the screen
pscreen.ClearScreen((0, 0, 0))
#Exit out of this loop if escape is pressed
if pscreen.KeyIsPressed("escape"):
break
#Compute the new position of our sprite
posX = (mouseX - pscreen.SpriteWidth(0) / 2)
posY = (mouseY - pscreen.SpriteHeight(0) / 2)
pscreen.FontWrite(5, 350, "Click and drag the left mouse button to move the sprite", (255, 255, 255, 255))
#Draw the sprite at this point
pscreen.SpriteRender(mouseX, mouseY, 0)
#Render our boxes
for i in range(0, len(boxes)):
box = boxes[i]
pscreen.Rectangle(box[0], box[1], box[2], box[3], (255, 0, 0, 255), 0)
pscreen.FontWrite((box[0] + box[2])/2 - 5, (box[1] + box[3])/2 - 5, str(i))
#If our sprite collides with any of the boxes, notify us
if pscreen.CollideRectangles(posX, posY, posX + pscreen.SpriteWidth(0), posY + pscreen.SpriteHeight(0), box[0], box[1], box[2], box[3]) == True:
pscreen.FontWrite(15, 370, "Collision with box " + str(i) + "!", (255, 255, 255, 255))
#If the left mouse button is pressed, save the mouse position off
if pscreen.MouseGetButtonL():
mouseX = pscreen.MouseGetX()
mouseY = pscreen.MouseGetY()
pscreen.UpdateScreen()
pscreen.UnloadScreen()


