I've been working on this project about tanks (based on game Tank Trouble) and I'm wondering how I can move forward after I change angle of the sprite. Also if you know how I can make my bullets ricochet from the walls. I will really appreciate any help given. Thank you!
Here is my tank and bullet:
Here is code of the game:
import sys
import pygame
class Game:
def __init__(self):
self.run = True
self.screen_width = 1060
self.screen_height = 798
self.image = pygame.image.load("sprites/background/background1.png")
self.image = pygame.transform.scale(self.image, (self.screen_width, self.screen_height))
self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
# all_sprites is used to update and draw all sprites together.
self.all_sprites = pygame.sprite.Group()
# for collision detection with enemies.
self.bullet_group = pygame.sprite.Group()
self.tank = Tank()
self.all_sprites.add(self.tank)
bullet = Bullet(self.tank)
self.bullet_group.add(bullet)
self.all_sprites.add(bullet)
def handle_events(self):
keys = pygame.key.get_pressed()
self.tank.handle_events()
if keys[pygame.K_UP]:
self.tank.rect.centery -= 5
if keys[pygame.K_DOWN]:
self.tank.rect.centery += 5
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.run = False
if event.key == pygame.K_SPACE:
bullet = Bullet(self.tank)
self.bullet_group.add(bullet)
self.all_sprites.add(bullet)
def update(self):
# Calls `update` methods of all contained sprites.
self.all_sprites.update()
def draw(self):
self.screen.blit(self.image, (0, 0))
self.all_sprites.draw(self.screen) # Draw the contained sprites.
pygame.display.update()
class Tank(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("sprites/player/player_tank.png")
self.org_image = self.image.copy()
# A nicer way to set the start pos with `get_rect`.
self.rect = self.image.get_rect(center=(70, 600))
self.angle = 0
self.direction = pygame.Vector2(1, 0)
self.pos = pygame.Vector2(self.rect.center)
def handle_events(self):
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
self.angle += 3
if pressed[pygame.K_RIGHT]:
self.angle -= 3
self.direction = pygame.Vector2(1, 0).rotate(-self.angle)
self.image = pygame.transform.rotate(self.org_image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
class Bullet(pygame.sprite.Sprite):
def __init__(self, tank):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("sprites/bullet/bullet.png")
self.image = pygame.transform.scale(self.image, (16, 16))
self.rect = self.image.get_rect()
self.rect.centerx = tank.rect.centerx + 3 # How much pixels from tank turret on x axis
self.rect.centery = tank.rect.centery - 25 # How much pixels from tank turret on y axis
def update(self):
self.rect.y -= 10 # Move up 10 pixels per frame.
def main():
pygame.init()
pygame.display.set_caption('Tank Game')
clock = pygame.time.Clock()
game = Game()
while game.run:
game.handle_events()
game.update()
game.draw()
clock.tick(60)
if __name__ == '__main__':
main()
pygame.quit()
sys.exit()
To move the tank in the direction which is faced, wirte a method, that computes a direction vector, dependent on an velocity argument and the self.angle attribute. The nagle and the velocity define a vector by Polar coordinats.
Add the vector to it's current position (self.pos). Finally update the self.rect attribute by the position:
class Tank(pygame.sprite.Sprite):
# [...]
def move(self, velocity):
direction = pygame.Vector2(0, velocity).rotate(-self.angle)
self.pos += direction
self.rect.center = round(self.pos[0]), round(self.pos[1])
Invoke the method when up or down is pressed:
class Game:
# [...]
def handle_events(self):
# [...]
if keys[pygame.K_UP]:
self.tank.move(-5)
if keys[pygame.K_DOWN]:
self.tank.move(5)
The movement direction of the bullets can be computed similar:
class Bullet(pygame.sprite.Sprite):
def __init__(self, tank):
#[...]
self.rect = self.image.get_rect()
self.angle = tank.angle
self.pos = pygame.Vector2(tank.pos)
self.rect.center = round(self.pos.x), round(self.pos.y)
self.direction = pygame.Vector2(0, -10).rotate(-self.angle)
def update(self):
self.pos += self.direction
self.rect.center = round(self.pos[0]), round(self.pos[1])
To make the bullet bounce, you have to reflect the direction when the bullet hits a border:
class Bullet(pygame.sprite.Sprite):
# [...]
def update(self):
self.pos += self.direction
self.rect.center = round(self.pos.x), round(self.pos.y)
if self.rect.left < 0:
self.direction.x *= -1
self.rect.left = 0
self.pos.x = self.rect.centerx
if self.rect.right > 1060:
self.direction.x *= -1
self.rect.right = 1060
self.pos.x = self.rect.centerx
if self.rect.top < 0:
self.direction.y *= -1
self.rect.top = 0
self.pos.y = self.rect.centery
if self.rect.bottom > 798:
self.direction.y *= -1
self.rect.right = 798
self.pos.y = self.rect.centery
Related
I have been trying to create a game form scratch in Python using Pygame. I followed a tutorial for the most part and have hit a wall. The game is a simple platformer and I'm having trouble adding in collisions. I have looked at many other examples but cant seem to find where abouts to add in the pygame.sprite.collide_rect command and how to get it to stop the players y velocity so that he stops ontop of a platform. Any help would be greatly appreciated! Thanks.
The code
import random
import pygame as pg
pg.init()
icon = pg.image.load("soldier.png")
pg.display.set_icon(icon)
backgroundimage = pg.image.load("background.png")
FPS = 50
Width = 512
Height = 384
Red = (255, 0, 0)
#vec = pg.math.Vector2
class platform(pg.sprite.Sprite):
def __init__(self, x, y):
pg.sprite.Sprite.__init__(self)
self.image = pg.image.load("plat.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
class Player(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.image = pg.image.load("Spaceman.png")
self.rect = self.image.get_rect()
self.rect.center = (Width / 2, Height / 2)
self.vx = 0
self.vy = 0
#self.pos = vec(Width / 2, Height / 2)
self.acc = 0.2
def update(self):
self.vy = self.vy + self.acc
self.vx = 0
#self.acc = vec(0, 0.5)
keys = pg.key.get_pressed()
if keys[pg.K_SPACE]:
while self.vy > 0:
self.vy = -5 + self.acc
if keys[pg.K_LEFT]:
self.vx = -5
self.image = pg.image.load("Spaceman2.png")
if keys[pg.K_RIGHT]:
self.vx = 5
self.image = pg.image.load("Spaceman.png")
self.rect.x += self.vx
self.rect.y += self.vy
if self.rect.left > Width:
self.rect.right = 0
if self.rect.right < 0:
self.rect.left = Width
class Game:
def __init__(self):
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode((Width,Height))
pg.display.set_caption("OH NOOOO")
self.clock = pg.time.Clock()
self.running = True
def new(self):
self.all_sprites = pg.sprite.Group()
self.platforms = pg.sprite.Group()
self.soldier = pg.sprite.Group()
self.player = Player()
self.all_sprites.add(self.player)
self.soldier.add(self.player)
p1 = platform(200, 200)
self.all_sprites.add(p1)
self.platforms.add(p1)
self.run()
def run(self):
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
def update(self):
self.screen.blit(backgroundimage,[0,0])
self.all_sprites.update()
def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
def draw(self):
self.all_sprites.draw(self.screen)
pg.display.flip()
def show_start_screen(self):
pass
def show_go_screen(self):
pass
g = Game()
g.show_start_screen()
while g.running:
g.new()
g.show_go_screen()
pg.quit()
This is all of the code so far and I've made three groups within this code; all_sprites, soldier and platforms but cant figure out how to make soldier and platforms groups collide. Any help is greatly appreciated thanks!
Use pygame.sprite.groupcollide() to detect the collision of pygame.sprite.Sprite objects in 2 separate pygame.sprite.Groups:
if pygame.sprite.groupcollide(self.soldier, self.platforms, False, Fasle):
print("hit")
I want to flip these sprites so that they're facing left. That way I can use the sprite images for my player running left when I press K_LEFT. Currently have it where if you press the right arrow your player moves right and animates.
self.sprites = []
self.sprites.append(py.image.load('I1.png'))
self.sprites.append(py.image.load('R0.png'))
self.sprites.append(py.image.load('R1.png'))
self.sprites.append(py.image.load('R2.png'))
self.sprites.append(py.image.load('R3.png'))
self.sprites.append(py.image.load('R4.png'))
self.sprites.append(py.image.load('R5.png'))
self.current_sprite = 0
self.image = self.sprites[self.current_sprite]
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.hit_rect = PLAYER_RECT_HIT
self.hit_rect.center = self.rect.center
self.pos = vec(x, y)
self.vel = vec(0, 0)
self.acc = vec(0, 0)
self.is_animating = False
def get_keys(self):
self.acc = vec(0, PLAYER_GRAVITY)
keys = py.key.get_pressed()
if keys[py.K_RIGHT]:
self.acc.x += PLAYER_ACC
self.animate()
if keys[py.K_LEFT]:
self.acc.x -= PLAYER_ACC
def animate(self):
self.is_animating = True
def update(self):
self.get_keys()
if self.is_animating:
self.current_sprite += 0.2
if self.current_sprite >= len(self.sprites):
self.current_sprite = 0
self.is_animating = False
self.image = self.sprites[int(self.current_sprite)]
self.pos += self.vel
self.hit_rect.centerx = self.pos.x
wall_collision(self, self.game.walls, 'x')
self.hit_rect.centery = self.pos.y
wall_collision(self, self.game.walls, 'y')
self.rect.center = self.hit_rect.center
# Apply Friction
self.acc.x += self.vel.x * PLAYER_FRICTION
# Equation of motion
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc
I would try
pygame.transform.flip()
https://www.pygame.org/docs/ref/transform.html#pygame.transform.flip
When you blit to screen you could check if 'left key' was pressed and transform.flip
'flip(Surface, xbool, ybool) -> Surface'
eg.
if key == 'left':
self.screen.blit(pygame.transform.flip(self.image, False, True), self.rect)
example code:
import pygame
import pygame.sprite
import sys
class WalkingSprite(pygame.sprite.Sprite):
""" A class to manage an animated sprite. """
def __init__(self):
super(WalkingSprite, self).__init__()
self.direction = True
self.images = []
for number in range(1, 11):
self.images.append(pygame.image.load(f'images/walking_sprite{number}.png'))
self.index = 0
self.image = self.images[self.index]
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = 300, 200
def update(self):
self.index += 1
if self.index >= len(self.images):
self.index = 0
if self.direction:
self.image = self.images[self.index]
else:
self.image = pygame.transform.flip(self.images[self.index], True, False)
BG_COLOR = pygame.Color('white')
pygame.init()
screen = pygame.display.set_mode((800, 600))
walking_sprite = WalkingSprite()
sprite_group = pygame.sprite.Group(walking_sprite)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
walking_sprite.direction = False
if event.key == pygame.K_RIGHT:
walking_sprite.direction = True
if event.type == pygame.QUIT:
sys.exit()
sprite_group.update()
screen.fill(BG_COLOR)
sprite_group.draw(screen)
pygame.display.update()
clock.tick(15)
Transform.rotate is what your looking for.
for sprite in self.sprites :
pygame.transform.rotate (sprite, angle)
In my game the problem is that bullets are coming only from one place i.e, from the center. As my player rotates in direction of cursor, I want the bullets to be shot from top of the player even if the player is rotated and travel in a straight line in the direction player is facing towards, As the player rotates in the direction of cursor.
As you can view here the the bullets are always in same direction and always come out of same place.
I tried to use getpos() method to get cursor position and tried to subtract from the player coordinates but failed to get the result.
I think the problem is within the def shoot(self) method of Rotator class, I need to get the coordinates spaceship's tip even when it is rotating all time.
import math
import random
import os
import pygame as pg
import sys
pg.init()
height=650
width=1200
os_x = 100
os_y = 45
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (os_x,os_y)
screen = pg.display.set_mode((width,height),pg.NOFRAME)
screen_rect = screen.get_rect()
background=pg.image.load('background.png').convert()
background = pg.transform.smoothscale(pg.image.load('background.png'), (width,height))
clock = pg.time.Clock()
running = True
class Mob(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.image = pg.image.load('enemy.png').convert_alpha()
self.image = pg.transform.smoothscale(pg.image.load('enemy.png'), (33,33))
self.rect = self.image.get_rect()
self.rect.x = random.randrange(width - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
self.speedx = random.randrange(-3, 3)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > height + 10 or self.rect.left < -25 or self.rect.right > width + 20:
self.rect.x = random.randrange(width - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
class Rotator(pg.sprite.Sprite):
def __init__(self, screen_rect):
pg.sprite.Sprite.__init__(self)
self.screen_rect = screen_rect
self.master_image = pg.image.load('spaceship.png').convert_alpha()
self.master_image = pg.transform.smoothscale(pg.image.load('spaceship.png'), (33,33))
self.image = self.master_image.copy()
self.rect = self.image.get_rect(center=[width/2,height/2])
self.delay = 10
self.timer = 0.0
self.angle = 0
self.distance = 0
self.angle_offset = 0
def get_angle(self):
mouse = pg.mouse.get_pos()
offset = (self.rect.centerx - mouse[0], self.rect.centery - mouse[1])
self.angle = math.degrees(math.atan2(*offset)) - self.angle_offset
old_center = self.rect.center
self.image = pg.transform.rotozoom(self.master_image, self.angle,1)
self.rect = self.image.get_rect(center=old_center)
self.distance = math.sqrt((offset[0] * offset[0]) + (offset[1] * offset[1]))
def update(self):
self.get_angle()
self.display = 'angle:{:.2f} distance:{:.2f}'.format(self.angle, self.distance)
self.dx = 1
self.dy = 1
self.rect.clamp_ip(self.screen_rect)
def draw(self, surf):
surf.blit(self.image, self.rect)
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.centery)
all_sprites.add(bullet)
bullets.add(bullet)
class Bullet(pg.sprite.Sprite):
def __init__(self, x, y):
pg.sprite.Sprite.__init__(self)
self.image = pg.image.load('bullet.png').convert_alpha()
self.image = pg.transform.smoothscale(pg.image.load('bullet.png'), (10,10))
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
self.speedy = -8
def update(self):
self.rect.y += self.speedy
# kill if it moves off the top of the screen
if self.rect.bottom < 0:
self.kill()
all_sprites = pg.sprite.Group()
bullets = pg.sprite.Group()
mobs = pg.sprite.Group()
rotator = Rotator(screen_rect)
all_sprites.add(rotator)
for i in range(5):
m = Mob()
all_sprites.add(m)
mobs.add(m)
while running:
keys = pg.key.get_pressed()
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
pygame.quit()
if event.type == pg.MOUSEBUTTONDOWN:
rotator.shoot()
screen.blit(background, [0, 0])
all_sprites.update()
hits = pg.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
m = Mob()
all_sprites.add(m)
mobs.add(m)
hits = pg.sprite.spritecollide(rotator, mobs, False)
if hits:
running = False
all_sprites.draw(screen)
clock.tick(60)
pg.display.update()
See Shooting a bullet in pygame in the direction of mouse and calculating direction of the player to shoot pygame.
Pass the mouse position to rotator.shoot(), when the mouse button is pressed:
if event.type == pg.MOUSEBUTTONDOWN:
rotator.shoot(event.pos)
Calculate the direction of from the rotator to the mouse position and pass it the constructor of the new bullet object:
def shoot(self, mousepos):
dx = mousepos[0] - self.rect.centerx
dy = mousepos[1] - self.rect.centery
if abs(dx) > 0 or abs(dy) > 0:
bullet = Bullet(self.rect.centerx, self.rect.centery, dx, dy)
all_sprites.add(bullet)
bullets.add(bullet)
Use pygame.math.Vector2 to store the current positon of the bullet and the normalized direction of the bullet (Unit vector):
class Bullet(pg.sprite.Sprite):
def __init__(self, x, y, dx, dy):
pg.sprite.Sprite.__init__(self)
self.image = pg.transform.smoothscale(pg.image.load('bullet.png').convert_alpha(), (10,10))
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.speed = 8
self.pos = pg.math.Vector2(x, y)
self.dir = pg.math.Vector2(dx, dy).normalize()
Calcualate the new position of the bullet in update() (self.pos += self.dir * self.speed) and update the .rect attribute by the new position.
.kill() the bullet when it leaves the screen. This can be checked by self.rect.colliderect():
class Bullet(pg.sprite.Sprite):
# [...]
def update(self):
self.pos += self.dir * self.speed
self.rect.center = (round(self.pos.x), round(self.pos.y))
if not self.rect.colliderect(0, 0, width, height):
self.kill()
I want to make the enemies shoot, firstly with the tab butten, after I get this working I want to make them shoot randomly. When I press the tab button it says AttributeError: 'Group' object has no attribute 'shootEnemy'.
What is going wrong?
At this moment there is no collision detection. I will add this later.
import pygame, sys
from pygame.locals import *
import random
screenWidth = 800
screenHeight = 600
FPS = 60
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((screenWidth,screenHeight))
pygame.display.set_caption("Space Invaders")
clock = pygame.time.Clock()
shipWidth = 78
#colors
black=(0,0,0)
blue=(0,0, 255)
green=(0,128,0)
red=(255,0,0)
white=(255,255,255)
yellow=(255,255,0)
def app_quit():
pygame.quit()
sys.exit("System exit.")
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("spaceship7.png").convert()
self.image.set_colorkey(white)#make white transparant
self.rect = self.image.get_rect()
self.rect.centerx = screenWidth / 2
self.rect.bottom = screenHeight - 10
self.speedx = 0
def update(self):
self.speedx = 0
if event.type == KEYDOWN and event.key == K_LEFT:
self.speedx = -2
elif event.type == KEYDOWN and event.key == K_RIGHT:
self.speedx = 2
self.rect.x += self.speedx
if self.rect.right > screenWidth:
self.rect.right = screenWidth
if self.rect.left < 0:
self.rect.left = 0
def shootPlayer(self):
bulletPlayer = BulletPlayer(self.rect.centerx, self.rect.top)
allSprites.add(bulletPlayer)
bulletsPlayer.add(bulletPlayer)
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("enemy.png").convert()
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = random.randrange(0, 200)
self.speedx = random.randrange(1,2)
def update(self):
self.rect.x += self.speedx
if self.rect.right > screenWidth:
self.rect.x = 50
self.rect.y = random.randrange(0, 250)
self.speedx = random.randrange(1,3)
if self.rect.x > screenWidth:
self.kill()
def shootEnemy(self):
bulletEnemy = BulletEnemy(self.rect.centerx, self.rect.bottom)
allSprites.add(bulletEnemy)
bulletsEnemy.add(bulletEnemy)
class BulletPlayer(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("bullet.png").convert()
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -3
def update(self):
self.rect.y += self.speedy
if self.rect.bottom < 0:
self.kill()
class BulletEnemy(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("bulletenemy.png").convert()
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = 3
def update(self):
self.rect.y += self.speedy
if self.rect.bottom > screenHeight:
self.kill()
class Wall(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("wall.png").convert()
self.rect = self.image.get_rect()
self.rect.center = 100, 300
allSprites = pygame.sprite.Group()
player = Player()
enemy = pygame.sprite.Group()
bulletsPlayer = pygame.sprite.Group()
bulletsEnemy = pygame.sprite.Group()
wall = Wall()
allSprites.add(player, enemy, bulletsPlayer, bulletsEnemy, wall)
for i in range(1):
e = Enemy()
allSprites.add(e)
enemy.add(e)
running = True
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
running = False
app_quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shootPlayer()
if event.key == pygame.K_TAB:
enemy.shootEnemy()
allSprites.update()
screen.fill(black)
allSprites.draw(screen)
pygame.display.flip()
pygame.quit()
Change the line:
enemy.shoot()
to
random.choice(enemy.sprites()).shoot()
This will call the shoot() method of a random sprite from your SpriteGroup enemy.
this is my first post. I need to make a working game for my final project. Basically the idea is to have the character collide with an Item sprite and Have a random item display on the screen telling the player what the item is and where to take it.
#Initialize
import pygame
import random
pygame.init()
#Display
screen = pygame.display.set_mode((1180, 900))
class PaperBoy(pygame.sprite.Sprite):
def __init__(self,startY):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("paperboy.gif")
self.rect = self.image.get_rect()
self.image = self.image.convert()
self.rect.centery = startY
self.dx= 300
self.dy= 300
def update(self):
#adjust x/y to dx/dy
self.rect.centerx = self.rect.centerx+self.dx
self.rect.centery = self.rect.centery+self.dy
#check Boundaries
#Check right
if self.rect.centerx >= 670:
self.rect.centerx =670
#Check left
elif self.rect.centerx <= 220:
self.rect.centerx = 220
#Check Bottom
if self.rect.centery >= 700:
self.rect.centery = 700
#Check Top
elif self.rect.centery <= 200:
self.rect.centery = 200
def moveUp(self):
self.dx=0
self.dy=-5
def moveDown(self):
self.dx =0
self.dy =5
def moveLeft(self):
self.dx =-5
self.dy = 0
def moveRight(self):
self.dx =5
self.dy =0
"""
mousex, mousey = pygame.mouse.get_pos()
self.rect.centery = mousey
#Check X boundary.
if mousex >= 670:
self.rect.right = 670
elif mousex <= 210:
self.rect.left = 210
else:
self.rect.centerx = mousex
#Check Y boundary.
if mousey >= 670:
self.rect.top = 670
elif mousey >= 250:
self.rect.top = 250
if mousex >= 250 and mousey >= 220:
self.rect.left = 250
self.rect.top = 670
else:
self.rect.centery = mousey
"""
class Parcel(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("parcel.png")
self.rect = self.image.get_rect()
self.image = self.image.convert()
def update(self):
self.rect.center = (200,600)
"""(random.randint(300,800)),(random.randint(300,800))"""
"""
================================HUD======================================
"""
#Green Y
class ItemHUD(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("itemhud.png")
self.rect = self.image.get_rect()
self.image = self.image.convert()
def update(self):
self.rect.center = (950,200)
#Red A
class WhereHUD(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("where.png")
self.rect = self.image.get_rect()
self.image = self.image.convert()
def update(self):
self.rect.center = (950, 350)
#Small Green
class TimeHUD(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("timehud.png")
self.rect = self.image.get_rect()
self.image = self.image.convert()
def update(self):
self.rect.center = (915, 850)
#Yellow
class GoldHUD(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("gold.png")
self.rect = self.image.get_rect()
self.image = self.image.convert()
def update(self):
self.rect.center = (915, 700)
"""
=================================HUD OBJECTS==============================
"""
"""
------------------------------------MAIN-----------------------------------
"""
def main():
pygame.display.set_caption("A Link to the Parcel")
background = pygame.image.load('village.png').convert()
allSprites=pygame.sprite.Group()
parcel = Parcel()
#Heads up Display
itemHud = ItemHUD()
timeHud = TimeHUD()
goldHud = GoldHUD()
whereHud = WhereHUD()
#Player
paperboy = PaperBoy(200)
#Sprites added to AllSprites Group
allSprites.add(paperboy)
allSprites.add(parcel)
allSprites.add(itemHud)
allSprites.add(timeHud)
allSprites.add(goldHud)
allSprites.add(whereHud)
font = pygame.font.Font(None, 25)
goldSack = 0
clock = pygame.time.Clock()
keepGoing = True
while keepGoing:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
elif event.type == pygame.KEYUP:
if event.key==pygame.K_UP:
paperboy.moveUp()
elif event.key==pygame.K_DOWN:
paperboy.moveDown()
elif event.key==pygame.K_LEFT:
paperboy.moveLeft()
elif event.key==pygame.K_RIGHT:
paperboy.moveRight()
fontTitle = font.render("A Link to the Parcel", True, (255,255,255,))
screen.blit(background, (0, 0))
screen.blit(fontTitle, [925,100])
allSprites.clear(screen, background,)
allSprites.update()
allSprites.draw(screen)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
If I understand what you mean, you have a bunch of Sprite types, and you want to choose one at random. To do that, just put them all in a list, use random.choice to pick one, and then instantiate it. Like this:
class OneKindOfParcel(Parcel): # etc.
class AnotherKindOfParcel(Parcel): # etc.
class AThirdKindOfParcel(Parcel): # etc.
parcels = [OneKindOfParcel, AnotherKindOfParcel, AThirdKindOfParcel]
# … later …
parceltype = random.choice(parcels)
parcel = parceltype()
allSprites.add(parcel)
You probably want to give it a location, and display something about its name and location, and so on, but I think you know how to do all that.
Quick and dirty is a list of items and then use random.choice from the random module.