I'm having trouble making the paddles stay in the screen? [duplicate] - python

This question already has answers here:
Not letting the character move out of the window
(2 answers)
Closed 2 years ago.
I'm trying to make the paddles move up and down : 1 rectangle. moving with w/a/s/d keys 2 rectangle. with arrows. I'm having trouble making the paddles stay in the screen?
You will make two “paddles” (i.e. Rectangles), one on the left side and one on the right side of the screen. These rectangles should be taller than they are wide (i.e. Look like a paddle from a pong game). The paddle on the left should be able to move up and down using the w and s keys, the paddle on the right should move up and down using the up and down arrow keys. Both paddles should not be allowed to leave the top or bottom of the screen. (* for this assignment you are just creating the paddles and getting them moving properly,, no balls necessary). Try to avoid hardcoded values.
# import the necessary modules
import pygame
import sys
#initialize pygame
pygame.init()
# set the size for the surface (screen)
screen_h = 800
screen_w = 600
screen = pygame.display.set_mode((screen_h,screen_w),0)
# set the caption for the screen
pygame.display.set_caption("Template")
# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)
#initialize variables for player
#variables for first rectangle
R1x = 740
R1y = 300
R1w = 50
R1h = 132
R1dx = 0
R1dy = 0
#variables for second rectangle
R2x = 10
R2y = 300
R2w = 50
R2h = 132
R2dx = 0
R2dy = 0
#speed
speed = 3
screen.fill(BLACK)
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
if event.key == pygame.K_UP:
R1dx = 0
R1dy = -speed
elif event.key == pygame.K_DOWN:
R1dx = 0
R1dy = speed
if event.key == pygame.K_w:
R2dx = 0
R2dy = -speed
elif event.key == pygame.K_s:
R2dx = 0
R2dy = speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
R1dx = 0
R1dy = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
R2dx = 0
R2dy = 0
# move the x and y positions of the rectangles
oldR1x = R1x
oldR1y = R1y
R1x = R1x + R1dx
R1y = R1y + R1dy
if R1x >= screen_w-50:
R1x = oldR1x
R1y = oldR1y
if R1x<= 50:
R1x = oldR1x
R1y = oldR1y
if R1y>= screen_h-50:
R1x = oldR1x
R1y = oldR1y
if R1y<= 50:
R1x = oldR1x
R1y = oldR1y
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()
# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()

First of all you have swapped the screen width (screen_w) and the screen height (screen_h). It has to be:
# set the size for the surface (screen)
screen_w = 800
screen_h = 600
screen = pygame.display.set_mode((screen_w,screen_h),0)
The paddles move just up an down, so it sufficient to limit the y coordinate of the pddels to the range [0, screen_h-R1h]. Note, R1y respectively R2y are the top coordinate of the paddles:
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
Furthermore, the screen has to be cleared in the main application loop (screen.fill(BLACK)):
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
# [...]
# move the x and y positions of the rectangles
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
# clear screen
screen.fill(BLACK)
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()
Note, it the paddles would move along the x axis too (left, right), then the restriction of the x coordinate is similar:
R1x = max(0, min(screen_w-R1w, R1x + R1dx))
R2x = max(0, min(screen_w-R2w, R2x + R2dx))

Related

How do I implement sliding window algorithm on an image?

I'm making the Super Mario Bros. game on python using the pygame library. I wanted to fit only a portion of the map of mario bros level and I have no idea how am I supposed to do that. One of my seniors told me that I could use the sliding window algorithm. However, the problem is I don't know how to implement this algorithm on the image. If I can get any help that would be really appreciated.mario level world 1-1
I have also been able to print out the map to a suitable scaling:
map on code
edit: I am sorry I did not post my code. here it is:
import pygame
import pygame.transform
i = pygame.init()
X = 640
Y = 480
Window = pygame.display.set_mode ((X, Y))
pygame.display.set_caption ("Game")
Mario_Standing_Left = pygame.image.load("F:\\Mario in Python\\Mario_Standing_Left.png")
Mario_Standing_Right = pygame.image.load("F:\\Mario in Python\\Mario_Standing_Right.png")
x = 50
y = 430
width = 40
height = 60
speed = 5
isjump = False
jumpcount = 10
left = False
right = False
WalkCount = 0
ScreenWidth = X - width - speed
ScreenHeight = Y - height - speed
isjump = False
jumpcount = 10
run = True
while run:
pygame.time.delay (50) #time in pygame measured in milliseconds
for event in pygame.event.get ():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > speed:
x -= speed
if keys[pygame.K_RIGHT] and x <= ScreenWidth:
x += speed
if not (isjump):
if keys[pygame.K_SPACE]:
isjump = True
else:
if jumpcount >= -10:
neg = 1
if jumpcount < 0:
neg = -1
y -= (jumpcount ** 2) * 0.5 * neg
jumpcount -= 1
else:
isjump = False
jumpcount = 10
Window.fill ((0,0,0))
#(surface, (the window defined above, (colour), (the object being drawn)))
pygame.display.update()
world = pygame.image.load('World 1-1.png').convert()
world = pygame.transform.smoothscale(world,(8750,1400))
while True:
Window.blit(world,(0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
You should use area in blit(..., area=...) to display only some part of world
I use area = pygame.Rect(0, 300, SCREEN_WIDTH, SCREEN_HEIGHT) to keep information what area to display. And I change area.x to scroll it right and left.
import pygame
# --- constants --- # PEP8: all constants directly after imports
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
FPS = 60
# --- main --- # PEP8: `lower_case_names` for variables
pygame.init()
window = pygame.display.set_mode ((SCREEN_WIDTH, SCREEN_HEIGHT))
world_image = pygame.image.load('World 1-1.png').convert()
world_image = pygame.transform.smoothscale(world_image, (8750,1400))
world_rect = world_image.get_rect()
area = pygame.Rect(0, 300, SCREEN_WIDTH, SCREEN_HEIGHT)
direction = 'right'
# - mainloop -
clock = pygame.time.Clock()
run = True
while run:
for event in pygame.event.get ():
if event.type == pygame.QUIT:
run = False
if direction == 'right':
# move right
area.x += 2
# change direction
if area.right > world_rect.right:
area.right = world_rect.right
direction = 'left'
else:
# move left
area.x -= 2
# change direction
if area.left < world_rect.left:
area.left = world_rect.left
direction = 'right'
#window.fill((0, 0, 0))
window.blit(world_image, (0,0), area=area)
pygame.display.flip()
clock.tick(FPS) # keep speed 60 FPS (Frames Per Second)
# - end -
pygame.quit()
PEP 8 -- Style Guide for Python Code
EDIT:
If you will have other elements then you may need to create Surface with size of world to blit world and other elements before on this surface and later display it in window using area.
import pygame
# --- constants ---
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
FPS = 60
# --- main --- # PEP8: `lower_case_names` for variables
pygame.init()
window = pygame.display.set_mode ((SCREEN_WIDTH, SCREEN_HEIGHT))
window_rect = window.get_rect()
world_image = pygame.image.load('World 1-1.png').convert()
world_image = pygame.transform.smoothscale(world_image, (8750,1400))
world_rect = world_image.get_rect()
player_image = pygame.Surface((40, 40))
player_image.fill((255, 0, 0)) # red
player_rect = player_image.get_rect(centerx=window_rect.centerx, centery=window_rect.centery+300 )
area = pygame.Rect(0, 300, SCREEN_WIDTH, SCREEN_HEIGHT)
direction = 'right'
buffer = pygame.Surface(world_rect.size)
# - mainloop -
clock = pygame.time.Clock()
run = True
while run:
for event in pygame.event.get ():
if event.type == pygame.QUIT:
run = False
if direction == 'right':
# move right
area.x += 5
player_rect.x += 5
# change direction
if area.right > world_rect.right:
area.x -= 5
player_rect.x -= 5
#area.right = world_rect.right
direction = 'left'
else:
# move left
area.x -= 5
player_rect.x -= 5
# change direction
if area.left < world_rect.left:
area.x += 5
player_rect.x += 5
#area.left = world_rect.left
direction = 'right'
#player_rect.center = area.center
buffer.blit(world_image, (0,0))
buffer.blit(player_image, player_rect)
# ---
#window.fill((0, 0, 0))
window.blit(buffer, (0,0), area=area)
pygame.display.flip()
clock.tick(FPS) # keep speed 60 FPS (Frames Per Second)
# - end -
pygame.quit()

Problem with simple python game using a pygame libray

I'm new at Python and Pygame and I started making a simple game, something like a tennis game, but every time ball is under the rectangle jumping +-5 pixels and blocking. I think the problem is with pXY and bXY.
import sys, pygame
from pygame.locals import *
pygame.init()
pygame.display.set_mode((500,500)) # ustawiwanie wielkosci
pygame.display.set_caption(("little shit")) #ustawianie nazwy
okienko = pygame.display.get_surface() # pobieranie płaszczyzny
# obiekt
prostokat = pygame.Surface((80,20)) # tworzenie prostokąta / tulpa, szerokość / wysokość
prostokat.fill((128, 15, 220)) # zmiana koloru prostokąta / r:g:b
pXY = prostokat.get_rect() # pobranie wymiarów prostokąta
pXY.x = 225 # wartość x
pXY.y = 460 # wartość y
kolko = pygame.image.load("./ball.png")
bXY = kolko.get_rect()
bXY.x = 120 # POŁOŻENIE OBIEKTU
bXY.y = 200 # POŁOŻENIE OBIEKTU
bx,by = 5,5 # o ile sie przesuwamy
px = 3
bAB = kolko.get_rect()
bA = 25
bB = 25
kolko = pygame.transform.scale(kolko,(bA,bB))
pygame.display.flip() # wyświetlenie/odrysowanie całego okna
fps = pygame.time.Clock() # ile czasu minęło od wykonywania instrukcji
while True:
okienko.fill((128, 128, 128)) # zmiana koloru płaszczyzny na szary
pXY.x += px
if pXY.x > 420 or pXY.x < 0:
px *= -1
okienko.blit(prostokat, pXY)
bXY.x +=bx
if bXY.x > 475 or bXY.x < 0:
bx*= -1
bXY.y +=by
if bXY.y > 475 or bXY.y < 0:
by*= -1
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by=5
okienko.blit(kolko, bXY)
pygame.display.update() # update okienka
fps.tick(30) # odswiezanie obrazu, 30 fps
for zdarzenie in pygame.event.get():
if zdarzenie.type == pygame.QUIT:
pygame.quit()
exit()
if zdarzenie.type == KEYDOWN:
if zdarzenie.key == K_LEFT:
px=-7
if zdarzenie.key == K_RIGHT:
px=7
while True: # pętla do zamykania okienka
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
When the ball is under the rectangle, jumping +- 5 pixels and blocking, the ball can't leave this area when is on the left
Your collision detection logic will not give physically accurate results. For example, no matter where the ball collides with the paddle it will always start moving downward at 5 pixels/frame. This means that the ball will pass through the paddle when it collides hits from above but it will 'bounce' if it hits from below. That is what causes the ball to behave the way it does. This line is where the velocity is set if the paddle and ball are colliding:
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by=5
A slightly better approach would be to reverse the direction of the ball if it collides with the paddle. But this still makes the ball only reverse direction in the y-axis no matter where on the paddle the ball collides (top, bottom, left, right). The code above can be changed to this code to get this effect:
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by*=-1
This final chunk of code is cleaned up a bit and translated to English. It uses the second block of code from above to bounce the ball off the paddle:
import sys
import pygame
pygame.init()
window = pygame.display.set_mode((500, 500))
pygame.display.set_caption('new caption')
paddle = pygame.Surface((80, 20))
paddle.fill((128, 15, 220))
paddle_rect = paddle.get_rect()
paddle_rect.x = 225
paddle_rect.y = 460
ball = pygame.Surface((25, 25))
ball.fill((255, 0, 0))
ball_rect = ball.get_rect()
ball_rect.x = 120
ball_rect.y = 200
ball_velocity_x = 5
ball_velocity_y = 5
paddle_velocity_x = 3
clock = pygame.time.Clock()
while True:
# event processing code
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
paddle_velocity_x = -7
elif event.key == pygame.K_RIGHT:
paddle_velocity_x = 7
# update code
# update the position of the paddle and bounce it off the edges of the window
paddle_rect.x += paddle_velocity_x
if paddle_rect.x > 420 or paddle_rect.x < 0:
paddle_velocity_x *= -1
# update the position of the ball and bounce it off th eedges of the window
ball_rect.x += ball_velocity_x
ball_rect.y += ball_velocity_y
if ball_rect.x > 475 or ball_rect.x < 0:
ball_velocity_x *= -1
if ball_rect.y > 475 or ball_rect.y < 0:
ball_velocity_y *= -1
if paddle_rect.colliderect(ball_rect):
ball_velocity_y *= -1
# drawing code
window.fill((128, 128, 128))
window.blit(paddle, paddle_rect)
window.blit(ball, ball_rect)
pygame.display.update()
clock.tick(30)

How to detect collision to stay within box

So how would I be able to keep the green rectangle from getting outside of the box I have provided? If possible without using any classes. I would like to make a small map for levels within the given window so is there any way I can keep the rectangle from slipping through the lines? Or is it possible to force the rectangle to stop moving after hitting a certain point?
import pygame
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
#Functions
def drawSquare(screen, x, y):
pygame.draw.rect(screen, BLACK, [x, y, 21, 21])
pygame.draw.rect(screen, GREEN, [3+x, 3+y, 15, 15])
def drawMap():
pygame.draw.rect(screen, BLACK, [0, 1, 100, 100],5)
pygame.init()
# Set the width and height of the screen [width, height]
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("")
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#Loading pictures
#Variables
# Speed in pixels per frame
x_speed = 0
y_speed = 0
# Current position
x_coord = 10
y_coord = 10
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key. If so
# adjust speed.
if event.key == pygame.K_LEFT:
x_speed = -3
elif event.key == pygame.K_RIGHT:
x_speed = 3
if x_coord > 200:
x_speed = 0
elif event.key == pygame.K_UP:
y_speed = -3
elif event.key == pygame.K_DOWN:
y_speed = 3
elif event.type == pygame.KEYUP:
# If it is an arrow key, reset vector back to zero
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
x_coord = x_coord + x_speed
y_coord = y_coord + y_speed
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# --- Drawing code should go here
screen.fill(WHITE)
drawSquare(screen, x_coord, y_coord)
drawMap()
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(45)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
If I understand your question, you want to keep the square you are drawing within the view bounds. I think this will do it for you (the top two lines are already in your code above, just to show where this would go).
x_coord = x_coord + x_speed
y_coord = y_coord + y_speed
# consider moving these to the top and using them in your drawMap function
map_x = 0
map_y = 1
map_width = 100
map_height = 100
x_coord = max(map_x, x_coord)
y_coord = max(map_y, y_coord)
# coordinates must be less than size of container
# the 21 here is the size of the square you are drawing
# consider making it a variable rather than hard coded number
x_coord = min(x_coord, map_width - 21)
y_coord = min(y_coord, map_heigh - 21)
While I think if you keep on this course (avoiding using classes/using global variables) you will find your code will become unmaintainable.

pygame sample code with events

I can not seem to find the bug in my program. The program will run without errors however, my paddle image will not move. I have spent hours researching and tried multiple different changes. I am using python 3.4.1. My goal is to create a paddle game of sorts. Thank you.
# Python game
import pygame
import sys
pygame.init()
ball_image = pygame.image.load("ball.png")
ballrect = ball_image.get_rect()
paddle_image = pygame.image.load("paddle.png")
paddlerect = paddle_image.get_rect()
screen_w = 825
screen_h = 727
size = [screen_w, screen_h]
speed = [1, 1]
black = (0, 0, 0)
blue = (0,0,255)
screen = pygame.display.set_mode(size)
class paddle(object):
paddle_speed = [0, 0]
paddle_speed_d = [0, -1]
paddle_speed_u = [0, 1]
image = paddle_image
rect = image.get_rect()
x = 20
y = screen_h / 2
w = rect.width
h = rect.height
def __init__(self, side):
self.side = side
if side == "l":
x == width - 20 - w
def move_d(self):
self.rect.move(self.paddle_speed_d)
def move_u(self):
self.rect.move(self.paddle_speed_u)
pad1 = paddle("r")
#pad2 = paddle("l")
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
pad1.move_d()
if event.key == pygame.K_UP:
pad1.move_u()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > screen_w:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > screen_h:
speed[1] = -speed[1]
#if ballrect.bottom == 0:
#ballrect.y = screen_h
#if ballrect.top == screen_h:
#ballrect.bottom = 0
screen.fill(black)
screen.blit(ball_image, ballrect)
screen.blit(pad1.image, pad1.rect)
pygame.display.flip()
pygame.time.wait(1)
From the documentation:
move()
Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative.
move_ip()
Same as the Rect.move() method, but operates in place.
If you change self.rect.move(self.paddle_speed_d) to self.rect.move_ip(self.paddle_speed_d) in move_d(), that should do the trick (likewise for move_u().
(This still leaves the problem that move_d() is only called on key down. This means you have to repeatedly press the down key to move your paddle. This may be what you want, but if it's not, consider having an update function move the paddle on every loop, and have move_d() and move_u() set the velocity of the paddle.)
Thanks for trying to help, but I discovered my problem. The format in which I saved my image was not showing movement. I changed my image and now it works.

Pygame sprite assistance

I've basically just started developing with PyGame and I am having trouble with the whole Sprite concept. I have been looking every where for guides on how to use it, I just can't seem to find any. I would like to know the basic concept of how it all works. This is the code I have been working on:
#!/usr/bin/python
import pygame, sys
from pygame.locals import *
size = width, height = 320, 320
clock = pygame.time.Clock()
xDirection = 0
yDirection = 0
xPosition = 32
yPosition = 256
blockAmount = width/32
pygame.init()
screen = pygame.display.set_mode(size)
screen.fill([0, 155, 255])
pygame.display.set_caption("Mario Test")
background = pygame.Surface(screen.get_size())
mainCharacter = pygame.sprite.Sprite()
mainCharacter.image = pygame.image.load("data/character.png").convert()
mainCharacter.rect = mainCharacter.image.get_rect()
mainCharacter.rect.topleft = [xPosition, yPosition]
screen.blit(mainCharacter.image, mainCharacter.rect)
grass = pygame.sprite.Sprite()
grass.image = pygame.image.load("data/grass.png").convert()
grass.rect = grass.image.get_rect()
for i in range(blockAmount):
blockX = i * 32
blockY = 288
grass.rect.topleft = [blockX, blockY]
screen.blit(grass.image, grass.rect)
grass.rect.topleft = [64, 256]
screen.blit(grass.image, grass.rect.topleft )
running = False
jumping = False
falling = False
standing = True
jumpvel = 22
gravity = -1
while True:
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
running = True
xRun = -5
elif event.key == K_RIGHT:
running = True
xRun = 5
elif event.key == K_UP or event.key == K_SPACE:
jumping = True
elif event.type == KEYUP:
if event.key == K_LEFT or event.key == K_RIGHT:
running = False
if running == True:
xPosition += xRun
if mainCharacter.rect.right >= width:
xPosition = xPosition - 10
print "hit"
running = False
elif mainCharacter.rect.left <= 0:
xPosition = xPosition + 10
print "hit"
running = False
screen.fill([0, 155, 255])
for i in range(blockAmount):
blockX = i * 32
blockY = 288
grass.rect.topleft = [blockX, blockY]
screen.blit(grass.image, grass.rect)
grass.rect.topleft = [64, 64]
screen.blit(grass.image, grass.rect.topleft )
if jumping:
yPosition -= jumpvel
print jumpvel
jumpvel += gravity
if jumpvel < -22:
jumping = False
if mainCharacter.rect.bottom == grass.rect.top:
jumping = False
if not jumping:
jumpvel = 22
mainCharacter.rect.topleft = [xPosition, yPosition]
screen.blit(mainCharacter.image,mainCharacter.rect)
clock.tick(60)
pygame.display.update()
basically I just want to know how to make these grass blocks into sprites in a group, so that when I add my player (also a sprite) I can determine whether or not he is in the air or not through the collision system. Can someone please explain to me how I would do this. All I am looking for is basically a kick starter because some of the documentation is quite bad in my opinion as it doesn't completely tell you how to use it. Any help is greatly appreciated :)
In Pygame, sprites are very minimal. They consist of two main parts: an image and a rect. The image is what is displayed on the screen and the rect is used for positioning and collision detection. Here's an example of how your grass image could be made into a Sprite:
grass = pygame.image.load("grass.png")
grass = grass.convert_alpha()
grassSprite = new pygame.sprite.Sprite()
grassSprite.image = grass
#This automatically sets the rect to be the same size as your image.
grassSprite.rect = grass.get_rect()
Sprites are pretty pointless on their own, since you can always keep track of images and positions yourself. The advantage is in using groups. Here's an example of how a group might be used:
myGroup = pygame.sprite.Group()
myGroup.add([sprite1,sprite2,sprite3])
myGroup.update()
myGroup.draw()
if myGroup.has(sprite2):
myGroup.remove(sprite2)
This code creates a group, adds three sprites to the group, updates the sprites, draws them, checks to see if sprite2 is in the group, then removes the sprite. It is mostly straight forward, but there are some things to note:
1) Group.add() can take either a single sprite or any iterable collection of sprites, such as a list or a tuple.
2) Group.update() calls the update methods of all the Sprites it contains. Pygame's Sprite doesn't do anything when its update method is called; however, if you make a subclass of Sprite, you can override the update method to make it do something.
3) Group.draw() blits the images of all the Group's Sprites to the screen at the x and y positions of their rects. If you want to move a sprite, you change its rect's x and y positions like so: mySprite.rect.x = 4 or mySprite.rect.y -= 7
One way to use Groups is to create a different group for each level. Then call the update and draw method of whichever group represents the current level. Since nothing will happen or be displayed unless those methods are called, all other levels will remain "paused" until you switch back to them. Here's an example:
levels = [pygame.sprite.Group(),pygame.sprite.Group(),pygame.sprite.Group()]
levels[0].add(listOfLevel0Sprites)
levels[1].add(listOfLevel1Sprites)
levels[2].add(listOfLevel2Sprites)
currentLevel = 0
while(True):
levels[currentLevel].update()
levels[currentLevel].draw()
I know this question is somewhat old, but I hope you still find it helpful!

Categories

Resources