Pygame sprite hitboxes don't follow as screen scrolls/zooms - scroll

First, the CameraGroup class is attributed to the wonderful youtube channel Clear Code.
Second, the hitboxes will not zoom (mousewheel) or scroll (WASD keys) with the planet icons. Try clicking the planets before zooming or scrolling and you will see the hitbox in action.
Third, as the screen is zoomed out the planets get smaller and the camera window shrinks towards the middle of the screen. Ideally, the camera window should stay the full size of the parent window to allow displaying more planets in the zoomed out state.
Finally, I am eager to learn, so please be brutal. Just drop the two planet icons in the folder with the .py file.
import os
import pygame
from pygame import *
from sys import exit
class CameraGroup(pygame.sprite.Group):
def __init__(self):
super().__init__()
self.display_surf_foreground = pygame.display.get_surface()
# camera offset
self.offset = pygame.math.Vector2()
self.half_w = self.display_surf_foreground.get_size()[0] // 2
self.half_h = self.display_surf_foreground.get_size()[1] // 2
self.scroll_offset = (0, 0)
# box setup
self.camera_borders = {'left': 200, 'right': 200, 'top': 100, 'bottom': 100}
l = self.camera_borders['left']
t = self.camera_borders['top']
w = self.display_surf_foreground.get_size()[0] - (self.camera_borders['left'] + self.camera_borders['right'])
h = self.display_surf_foreground.get_size()[1] - (self.camera_borders['top'] + self.camera_borders['bottom'])
self.camera_rect = pygame.Rect(l, t, w, h)
# camera speed
self.keyboard_speed = 10
# zoom
self.zoom_scale = 1
self.foreground_surf_size = (400, 400)
self.foreground_surf = pygame.Surface(self.foreground_surf_size, pygame.SRCALPHA)
self.foreground_rect = self.foreground_surf.get_rect(center=(self.half_w, self.half_h))
self.foreground_surf_size_vector = pygame.math.Vector2(self.foreground_surf_size)
self.foreground_offset = pygame.math.Vector2()
self.foreground_offset.x = self.foreground_surf_size[0] // 2 - self.half_w
self.foreground_offset.y = self.foreground_surf_size[1] // 2 - self.half_h
# planets and labels
self.planet_surf = pygame.Surface
self.planet_rect = pygame.Rect
def keyboard_control(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.camera_rect.x -= self.keyboard_speed
if keys[pygame.K_d]:
self.camera_rect.x += self.keyboard_speed
if keys[pygame.K_w]:
self.camera_rect.y -= self.keyboard_speed
if keys[pygame.K_s]:
self.camera_rect.y += self.keyboard_speed
self.offset.x = self.camera_rect.left - self.camera_borders['left']
self.offset.y = self.camera_rect.top - self.camera_borders['top']
def zoom_keyboard_control(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_q]:
self.zoom_scale += 0.1
if self.zoom_scale > 2:
self.zoom_scale = 2
if keys[pygame.K_e]:
self.zoom_scale -= 0.1
if self.zoom_scale < .5:
self.zoom_scale = .5
def custom_draw(self, planets):
self.keyboard_control()
self.zoom_keyboard_control()
self.foreground_surf.fill((0, 0, 0, 255))
# active elements
for planet in planets:
self.planet_surf = pygame.image.load(planet.icon).convert_alpha()
offset_coord = planet.coord - self.offset + self.foreground_offset
self.planet_rect = self.planet_surf.get_rect(center=offset_coord)
self.foreground_surf.blit(self.planet_surf, self.planet_rect)
scaled_surf = pygame.transform.scale(self.foreground_surf, self.foreground_surf_size_vector * self.zoom_scale)
scaled_rect = scaled_surf.get_rect(center=(self.half_w, self.half_h))
self.display_surf_foreground.blit(scaled_surf, scaled_rect)
class Game:
def __init__(self):
self.game_over = False
self.game_year = 0
self.game_state = 'splash'
#staticmethod
def activate_planet(screen, planets):
active_planet_coord = None
for planet in planets:
if planet.rect.collidepoint(pygame.mouse.get_pos()):
active_planet_coord = planet.rect.center
return active_planet_coord
return active_planet_coord
#staticmethod
def heartbeat(screen, active_planet_coord):
# global heartbeat_mod
global heartbeat
ticks = pygame.time.get_ticks()
heartbeat_thump = round(ticks / 1000) % 2
if heartbeat_thump == 0:
heartbeat_mod = .1
else:
heartbeat_mod = -.1
heartbeat += heartbeat_mod
if heartbeat < 1:
heartbeat = 1
elif heartbeat > 6:
heartbeat = 6
heartbeat_color = (0, 255, 0)
pygame.draw.circle(screen, heartbeat_color, active_planet_coord, 25 + round(heartbeat), round(heartbeat) + 2)
class Planet(pygame.sprite.Sprite):
def __init__(self, icon, group):
super().__init__(group)
self.icon = icon
self.coord = (0, 0)
self.group = group
self.image = pygame.image.load(self.icon).convert_alpha()
self.rect = self.image.get_rect(center=self.coord)
self.planet_icons = []
self.planet_names = []
#staticmethod
def update_coords(planets, star_coords):
i = 0
for planet in planets:
planet.coord = tuple(star_coords[i])
planet.rect = planet.image.get_rect(center=planet.coord)
i += 1
if i == len(star_coords):
del planets[len(star_coords):]
return planets
def main():
global heartbeat
global heartbeat_mod
pygame.init()
width, height = 400, 400
screen = pygame.display.set_mode((width, height))
pygame.display.init()
pygame.display.update()
active_planet_coord = (-100, -100)
heartbeat = 0
heartbeat_mod = .1
clock = pygame.time.Clock()
game = Game()
camera_group = CameraGroup()
planet_array = os.listdir('./')
planet_array.pop(0) # remove 'camera scroll example.py' file
planet_icons = planet_array
planets = []
for new_planet in range(2):
icon = planet_icons.pop()
planet = Planet(icon, camera_group)
planets.append(planet)
star_coords = [[100, 100], [200, 200]]
planets = planet.update_coords(planets, star_coords)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
active_planet_coord = game.activate_planet(screen, camera_group)
if active_planet_coord is None:
active_planet_coord = (-100, -100)
pygame.display.update()
elif event.type == pygame.MOUSEWHEEL:
camera_group.zoom_scale += event.y * 0.1
if camera_group.zoom_scale > 2:
camera_group.zoom_scale = 2
elif camera_group.zoom_scale < .5:
camera_group.zoom_scale = .5
camera_group.update()
camera_group.custom_draw(planets)
game.heartbeat(screen, active_planet_coord)
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
main()

An alternative way to solve this problem is to "inverse zoom" the mouse position when you use it for click detection:
zoom:
p_zoom = (p - zoom_center) * zoom_scale + zoom_center
inverse zoom:
p = (p_zoom - zoom_center) / zoom_scale + zoom_center
Apply this to your code:
class Game:
# [...]
#staticmethod
def activate_planet(screen, planets):
zoom_scale = planets.zoom_scale
zoom_center = pygame.math.Vector2(screen.get_rect().center)
pos = pygame.math.Vector2(pygame.mouse.get_pos())
pos = (pos - zoom_center) / zoom_scale + zoom_center
active_planet_coord = None
for planet in planets:
if planet.rect.collidepoint(pos):
planet_center = (planet.rect.center - zoom_center) * zoom_scale + zoom_center
active_planet_coord = round(planet_center.x), round(planet_center.y)
return active_planet_coord
return active_planet_coord

Related

How Do I Make Enemies In My Game Shoot Missles randomnly?

So I'm trying to create space Invaders currently and i'm trying to make the aliens shoot at the player randomnly. I've made it so that one projectile or enemy missle is shot at the player, but I can't figure out how I can make this happen from random places where the aliens are located, and how I can make the enemy repeatedly shoot missles,as opposed to just once as it's doing right now. My code that i'm using is down below (variables related to the shooting of the enemy are enemMissleFire and enemymissles)....
import pygame
import sys
import time
#initialize pygame
pygame.init()
width = 800
height = 600
# set the size for the surface (screen)
screen = pygame.display.set_mode((width, height),pygame.FULLSCREEN)
width = screen.get_width()
height = screen.get_height()
print(width)
print(height)
# set the caption for the screen
pygame.display.set_caption("Space Invaders")
def checkCollision(missles, type, score):
for missle in missles:
collision = missle.collidelist((type))
if collision > -1:
type.pop(collision)
missles.remove(missle)
missle.move_ip(0,missleSpeed)
pygame.draw.rect(screen, WHITE, missle,0)
# 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)
clock = pygame.time.Clock()
FPS = 60
s = 25
#load and scale images
smallInvaderImg = pygame.image.load("images/smallinvader.png")
smallInvaderImg = pygame.transform.scale(smallInvaderImg,(s,s))
medInvaderImg = pygame.image.load("images/crabinvader.png")
medInvaderImg = pygame.transform.scale(medInvaderImg, (s,s))
bigInvaderImg = pygame.image.load("images/biginvader.png")
bigInvaderImg = pygame.transform.scale(bigInvaderImg, (s,s))
shipImg = pygame.image.load("images/ship.png")
shipImg = pygame.transform.scale(shipImg, (60,60))
smallInvaders = []
medInvaders = []
bigInvaders = []
enemiesMap = ["sssssssssss",
"mmmmmmmmmmm",
"mmmmmmmmmmm",
"bbbbbbbbbbb"]
invadertype = [smallInvaders,medInvaders,bigInvaders]
dx = 1
dy = 0
x = 240
y = 0
gap = 10
for element in enemiesMap:
for char in element:
if char == "s":
smallInvaders.append(pygame.Rect(x,y,s,s))
elif char == "m":
medInvaders.append(pygame.Rect(x,y,s,s))
elif char == "b":
bigInvaders.append(pygame.Rect(x,y,s,s))
x += s + gap
y += s + gap
x = 240
score = 2
ship = pygame.Rect(width/2,525,60,60)
if ship.right == width:
ship.right = width
#missles
maxMissles = 3
missleSpeed = -6
missleWidth = 5
missleHeight = 30
enemmissleWidth = 5
enemmissleHeight = 25
missles = []
missleFired = False
lives = 3
playbutton = pygame.Rect(width/2,height/2,155,90)
playbutton.center = (width/2,height/2)
quitbutton = pygame.Rect(width/2,height/2,155,90)
quitbutton.center = (width/2,height/2+110)
playagn = pygame.Rect(width/2,height/2,155,90)
playagn.center = (width/2,height/2)
playword = pygame.font.SysFont("comicsanms", 35)
title = pygame.font.SysFont("comicsanms", 90)
quitword = pygame.font.SysFont("comicsanms",35)
endscreen = pygame.font.SysFont("comicsanms", 90)
playagaintext = pygame.font.SysFont("comicsanms", 35)
enemMissleFire = False
enemmislist = []
enemymissles = (pygame.Rect(ship.centerx,y,enemmissleWidth,enemmissleHeight))
invaderDirSwapped = False
screenControl = 0
main = True
while main:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
main = False
for element in smallInvaders:
element.move_ip(dx,dy)
for element in smallInvaders:
if element.right >= width or element.left <= 0:
dx *= -1
invaderDirSwapped = True
for element in medInvaders:
element.move_ip(dx,dy)
if not invaderDirSwapped:
for element in medInvaders:
if element.right >= width or element.left <= 0:
dx *= -1
invaderDirSwapped = True
for element in bigInvaders:
element.move_ip(dx,0)
if not invaderDirSwapped:
for element in bigInvaders:
if element.right >= width or element.left <=0:
dx *= -1
invaderDirSwapped = True
key_input = pygame.key.get_pressed()
if key_input[pygame.K_RIGHT] and ship.right < width:
ship.move_ip(4,0)
if key_input[pygame.K_LEFT] and ship.left > 0:
ship.move_ip(-4,0)
if key_input[pygame.K_SPACE] and not missleFired:
missleFired = True
missles.append(pygame.Rect(ship.centerx,ship.top,missleWidth,missleHeight))
if screenControl == 0:
screen.fill(BLACK)
texttitle = title.render("SPACE INVADERS", True, WHITE)
textrect = texttitle.get_rect()
textrect.center = (width/2, 100)
screen.blit(texttitle,textrect)
if playbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
screenControl = 1
pygame.draw.rect(screen,WHITE,(playbutton), 0)
if playbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE, (playbutton), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE,(quitbutton), 0)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,quitbutton,4)
textplay = playword.render("PLAY", True, BLUE)
textrect2 = textplay.get_rect()
textrect2.center = (width/2,height/2)
screen.blit(textplay,textrect2)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
if screenControl == 1:
screen.fill(BLACK)
if len(missles) > 0:
if missleFired and missles[-1].bottom < (ship.top - 120) and not key_input[pygame.K_SPACE]:
missleFired = False
if len(missles) == 0:
missleFired = False
if enemMissleFire:
enemymissles.colliderect(ship)
enemymissles.move_ip(0,-missleSpeed)
pygame.draw.rect(screen, WHITE, enemymissles,0)
for invader in smallInvaders:
screen.blit(smallInvaderImg, invader)
for invader in medInvaders:
screen.blit(medInvaderImg, invader)
for invader in bigInvaders:
screen.blit(bigInvaderImg, invader)
screen.blit(shipImg,ship)
#move and draw missles
checkCollision(missles,smallInvaders,score)
checkCollision(missles,medInvaders,score)
checkCollision(missles,bigInvaders,score)
if smallInvaders == [] and medInvaders == [] and bigInvaders == []:
screenControl = 2
if screenControl == 2:
screen.fill(BLACK)
if playagn.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
screenControl = 0
pygame.draw.rect(screen,WHITE,(playagn),0)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE, (quitbutton),0)
if playagn.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(playagn), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(quitbutton),4)
textend = endscreen.render("YOU WON!", True, WHITE)
textrect4 = textend.get_rect()
textrect4.center = (width/2, 150)
screen.blit(textend,textrect4)
textplayagn = playagaintext.render("PLAY AGAIN", True, BLUE)
textrect5 = textplayagn.get_rect()
textrect5.center = (width/2,height/2)
screen.blit(textplayagn,textrect5)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
pygame.display.update()
Regardless, I can't figure out how I can make it so that projectiles can be shot from random aliens, over the course of the player shooting, and so any help would be appreicated.
Import Random and Time
this will get the random and time functions built in
from random import randint as ran
import time
Get the Number
this will get the time between the previous shot and the next
t = ran(Min_Time,Max_Time)
Get The Countdown
this will count a second between numbers
time.sleep(1)
t -= 1
print(t)
Shot!
shoot
if t == 0:
print('shot!')
FINAL CODE (trumpet fanfare)
from random import randint as ran
import time
def randshot(Min_Time,Max_Time):
t = ran(Min_Time,Max_Time)
print(t)
while t:
time.sleep(1)
t -= 1
print(t)
if t == 0:
print('shot!')
while True:
randshot(5,10)
Hope this Helped!

I use multiprocessing to search for images, but I get an error

import cv2
import numpy as np
from PIL import ImageGrab
from multiprocessing import Pool
def getGrayBase():
base = ImageGrab.grab(bbox=(0, 0, 1920, 1080))
base.save(f'Screen\\base.png')
base = f'Screen\\base.png'
rgbBase = cv2.imread(base)
grayBase = cv2.cvtColor(rgbBase, cv2.COLOR_BGR2GRAY)
return grayBase
def findPict(sabjektSearch):
grayBase=getGrayBase()
template = cv2.imread(sabjektSearch, 0)
rezult = {'flag': False, 'x': 0, 'y': 0, 'func': 0,'scroll':0}
# w, h = template.shape[::-1] # Высота ширина
# We find the center of the desired image
M = cv2.moments(template)
centr_x = int(M['m10'] / M['m00'])
centr_y = int(M['m01'] / M['m00'])
# print(f'centr {centr_x, centr_y}')
rez_search = cv2.matchTemplate(grayBase, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
# Check if the image you are looking for in the base
flag = False
for i in rez_search:
if np.amax(rez_search) > threshold:
flag = True
rezult['flag'] = flag
if flag == True:
loc = np.where(rez_search >= threshold)
for pt in zip(*loc[::-1]):
x = int(pt[0]) + centr_x
y = int(pt[1]) + centr_y
rezult['x'] = x
rezult['y'] = y
nameFunc = sabjektSearch.split('\\')[-1]
rez = f'{nameFunc} - YES ' if flag else f' {nameFunc} - no '
print(rez,end=" ")
return rezult
arr_pick_all=[f'Screen\p1.png',f'Screen\\p2',f'Screen\p3.png',f'Screen\p4.PNG',f'Screen\p5.png',f'Screen\\p6.png']
if __name__ == '__main__':
p = Pool(len(arr_pick_all))
rezult=p.map(findPict,arr_pick_all)
print()
print(rezult.get(timeout=1))
p.close()
p.join()
Finds 1-3 pictures, but with a large number an error occurs
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Generating and displaying random platforms in pygame

So this is part of the code for my game, using pygame. I'm trying to generate random platforms (from 3 different options), store them in a list and then blit all platforms in the list to the screen. I am able to generate the platform shapes correctly but other than the first platform i'm unable to position them where i want them.
blue = (0, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
i = 0
c = 0
Done = True
globalplatpos = pygame.Surface([395, 30])
globalplat = globalplatpos.get_rect()
platform_dimensions = plattop, platleft, platw, plath = 0,0,0,0
def play():
#============GAME SETUP============
SIZE = WIDTH, HEIGHT = 800, 600
TITLE = "Duality"
SPEED = 10
JUMPHEIGHT = 300
JUMPCOUNT = 0
JUMPSPEED = 15
GRAVITY = 10
STANDING = 1
JUMPING = 0
globalplatpos.fill(red)
platform = globalplat
platform.bottom = HEIGHT
PLATFORM = []
PLATPOS = []
platstand = True
screen = pygame.display.set_mode(SIZE)
caption = pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
mainsprite = pygame.image.load("images\mainsprite.png")
mainchar = mainsprite.get_rect()
mainchar.left = 177.5
mainchar.bottom = 570
mirrsprite = pygame.image.load("images\mirrsprite.png")
mirrchar = mirrsprite.get_rect()
mirrchar.left = mainchar.left + 400
mirrchar.bottom = mainchar.bottom
#============GAME SETUP============
#============PLATFORM GENERATOR============
def platform_generator(platform):
global globalplat
global globalplatpos
global platform_dimensions
globalplat = platform.move(0,-60)
globalplatpos.fill(red)
lastplat = PLATFORM[len(PLATFORM) - 1]
platheight = lastplat.top
leftpos = pygame.Surface([131, 30])
leftplat = leftpos.get_rect()
centrepos = pygame.Surface([100, 30])
centreplat = centrepos.get_rect()
rightpos = pygame.Surface([131, 30])
rightplat = rightpos.get_rect()
plat_type = random.randrange(0,3)
if plat_type == 0:
globalplat = leftplat
globalplatpos = leftpos
platform_dimensions = int(globalplat.top + 290), 0, 131, 30
elif plat_type == 1:
globalplat = centreplat
globalplatpos = centrepos
platform_dimensions = int(globalplat.top + 290), 132, 100, 30
elif plat_type == 2:
globalplat = rightplat
globalplatpos = rightpos
platform_dimensions = int(globalplat.top + 290), 233, 131, 30
else:
pass
PLATFORM.append(globalplat)
PLATPOS.append(globalplatpos)
#============PLATFORM GENERATOR============
#============GAME LOOP============
Done = False
while not Done:
clock.tick(60)
fps = clock.get_fps()
print(fps)
platform = globalplat
platpos = globalplatpos
mirrchar.left = mainchar.left + 406
mirrchar.bottom = mainchar.bottom
def update():
screen = pygame.display.set_mode(SIZE)
screen.fill(blue)
screen.blit(mainsprite, mainchar)
screen.blit(mirrsprite, mirrchar)
listpos = 0
pos = PLATPOS[listpos]
platshape = pygame.Rect(platform_dimensions)
platform = pygame.draw.rect(screen, red, platshape, 0)
platpos = globalplatpos
PLATFORM.append(platform)
PLATPOS.append(platpos)
for form in PLATFORM:
pos = PLATPOS[listpos]
listpos += 1
screen.blit(pos, form)
divpos = pygame.Rect(395, 0, 10, HEIGHT)
divrect = pygame.draw.rect(screen, black, divpos, 0)
pygame.display.update()
global i
if i == 0:
globalplat.bottom = HEIGHT
i = 1
PLATFORM.append(globalplat)
PLATPOS.append(globalplatpos)
screen.blit(globalplatpos, globalplat)
elif i == 1 and len(PLATFORM) < 10:
platform_generator(platform)
plat1 = PLATFORM[0]
update()
elif plat1.top > HEIGHT:
plat1 = PLATFORM[0]
pos1 = PLATPOS[0]
del plat1
del pos1
else:
update()
if mainchar.left > 0: #MOVE LEFT
if pygame.key.get_pressed()[K_LEFT] or pygame.key.get_pressed()[K_a]:
mainchar.left -= SPEED
else:
mainchar.left = 0
if mainchar.right < 395: # MOVE RIGHT
if pygame.key.get_pressed()[K_RIGHT] or pygame.key.get_pressed()[K_d]:
mainchar.right += SPEED
else:
mainchar.right = 395
jump = pygame.key.get_pressed()[K_SPACE] or pygame.key.get_pressed()[K_UP]
platstand = mainchar.collidelist(PLATFORM)
for form in PLATFORM:
if mainchar.colliderect(form):
STANDING = 1
mainchar.bottom = form.top
if JUMPING == 0:
if mainchar.collidelist(PLATFORM) > -1:
STANDING = 1
if STANDING == 1:
if jump:
JUMPING = 1
if JUMPING == 1:
if JUMPCOUNT < JUMPHEIGHT/2:
mainchar.bottom -= JUMPSPEED
mirrchar.bottom -= JUMPSPEED
JUMPCOUNT += JUMPSPEED
elif JUMPCOUNT > JUMPHEIGHT/2 and JUMPCOUNT < JUMPHEIGHT * 0.75:
mainchar.bottom -= JUMPSPEED/2
mirrchar.bottom -= JUMPSPEED/2
JUMPCOUNT += JUMPSPEED
elif JUMPCOUNT > JUMPHEIGHT * 0.75 and JUMPCOUNT < JUMPHEIGHT:
mainchar.bottom -= JUMPSPEED/4
mirrchar.bottom -= JUMPSPEED/4
JUMPCOUNT += JUMPSPEED
else:
JUMPCOUNT = 0
JUMPING = 0
STANDING = 0
jump = False
if STANDING == 0:
mainchar.bottom += GRAVITY
mirrchar.bottom += GRAVITY
def gameover():
Done = True
if mainchar.top > HEIGHT:
gameover()
if pygame.key.get_pressed()[K_ESCAPE]:
escape()
for event in pygame.event.get():
if event.type == pygame.QUIT: Done = True
update()
#============GAME LOOP============
I can't run this example but I see one mistake in blit()
You use
screen.blit( position, surface )
but blit() expects
screen.blit( surface, position )
Read PyGame Documentation: pygame.Surface.blit()

PyGame independent background image [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am having a problem that I wish you guys could help me.
In this soccer game when i move the player around the field the goals dont stick to there positions and they move along with the ball.
Example:
import pygame
import random
import sys, glob
from pygame.locals import *
class Ball(pygame.sprite.Sprite):
def __init__(self,x,y,image_x):
self.bottom = 20
self.image = pygame.image.load("res/images/ball1.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
screen.blit(self.image,(self.rect.x,self.rect.y))
self.change_x=x
self.change_y=y
class Field(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
#self.field = pygame.image.load('res/images/field.png').convert()
#self.field_rect = self.field.get_rect()
#self.field_rect.x = 0
#screen.blit(self.field,(self.field_rect.x,self.field_rect.y))
def goal_top(self):
self.goal_top = pygame.image.load("res/images/goal-top.png")
screen.blit(self.goal_top,(425,0))
def goal_bottom(self):
self.goal_bottom = pygame.image.load("res/images/goal-btm.png")
self.goal_bottom_rect = self.goal_bottom.get_rect()
self.goal_bottom_rect.y = 720
screen.blit(self.goal_bottom,(425,self.goal_bottom_rect.y ))
class Player(pygame.sprite.Sprite):
def __init__(self,x,y,image_x,image_y):
self.bottom = 20
self.image = pygame.image.load("res/images/player/boy.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
screen.blit(self.image,(self.rect.x,self.rect.y))
self.change_x=x
self.change_y=y
def changespeed_x(self,x):
self.change_x = x
def changespeed_y(self,y):
self.change_y = y
class Camera(object):
def __init__(self, camera_func, width, height):
self.camera_func = camera_func
self.state = Rect(0, 0, width, height)
def apply(self, target):
try:
return target.rect.move(self.state.topleft)
except AttributeError:
return map(sum, zip(target, self.state.topleft))
def update(self, target):
self.state = self.camera_func(self.state, target.rect)
def complex_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
l, t, _, _ = -l + HALF_WIDTH, -t+HALF_HEIGHT, w, h
l = min(0, l) # stop scrolling left
l = max(-(camera.width-WIN_WIDTH), l) # stop scrolling right
t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling bottom
t = min(0, t) # stop scrolling at the top
return Rect(l, t, w, h)
pygame.init()
# Set the height and width of the screen
WIN_WIDTH = 963
WIN_HEIGHT = 760
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)
size=[WIN_WIDTH,WIN_HEIGHT]
screen=pygame.display.set_mode(size)
#screen=pygame.display.set_mode(size,FULLSCREEN)
pygame.display.set_caption("Soccer")
clock=pygame.time.Clock()
x=500
y=280
set_ball_x = 500
set_ball_y = 300
shot = False
type=''
dir_y=0
##INITIAL POSITION OF IMAGES
image_x=0
image_y=0
ball_image_x=0
dir_y=0
##CAMERA TRACK
total_level_width = 963 ##BACKGROUND (Field) width
total_level_height = 1200 ##BACKGROUND (Field) height
camera = Camera(complex_camera, total_level_width, total_level_height)
background = pygame.image.load('res/images/field.png').convert()
background_rect = background.get_rect()
while 1:
clock.tick(20)
screen.blit(background, camera.apply((0,0)))
ball = Ball(set_ball_x,set_ball_y,ball_image_x)
camera.update(ball)
player = Player(x,y,image_x,image_y)
field = Field()
field.goal_top()
field.goal_bottom()
if pygame.key.get_pressed()[pygame.K_RIGHT]:
x=x+6
pos =+1
image_x = 0
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.key.get_pressed()[pygame.K_LEFT]:
x=x-6
image_x = 130
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.key.get_pressed()[pygame.K_UP]:
y=y-6
image_x = 195
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.key.get_pressed()[pygame.K_DOWN]:
y=y+6
image_x = 70
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.sprite.collide_rect(player,ball):
set_ball_x = player.change_x
set_ball_y = player.change_y+20
if pygame.key.get_pressed()[pygame.QUIT]:
sys.exit()
if pygame.key.get_pressed()[pygame.K_q]: ## KEY "Q" to EXIT
sys.exit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
pygame.display.update()
Any ideas why this is happening?
Thank you
What is Camera.apply() doing?
This:
l, t, _, _ = target_rect
_, _, w, h = camera
Should be:
loc = target_rect.topleft
size = camera.size
And
l, t, _, _ = -l + HALF_WIDTH, -t+HALF_HEIGHT, w, h
If you're trying to get the center coordinate? You use
loc = target_rect.center

Image viewer - standard gui controls, bottom-up or what?

I need to make a basic image viewer.
The main concern is how to implement (in terms of gui components and image manipulation) such features as: zoom in-out, scroll and 'hand tool'.
There seems to be several options for achieving this goal, differing mainly in degree of putting responsibilities on the graphical interface framework as opposed to manually implementing things.
Two solutions that are obvious to me are:
1) Resizing and cropping the visible part of the image is crafted on its own using functionality of some image manipulation library. The image (or it's part) is then drawn on some window/control in an overridden onPaint() method. Scrollbars updating (when 'hand tool' used) and operation (when used directly) code needs to be written.
2) An oversized control (StaticBitmap or whatever) containing the image is put inside a window with automatic scrolling. Then one needs to figure out how to convert image coordinates to scrolling coordinates.
Both ways look awkward. Any ideas how to do it in a neat way? Or is what I feel as being ugly just the only way to go?
I'm using Python with wxPython/wxWidgets and PIL, but the question is to a large extent language- and platform- independent.
Sample code and links to sources (of something that is not too bloated) are welcome.
Here's a tutorial that might help. Build a wxPython Image Viewer
I didn't actually watch all the videos, so I can't speak to how well it address's your specific problems.
Also, here's a blog post by Jeff Atwood on Coding Horror that could apply. Programming Is Hard, Let's Go Shopping! It speaks to when you should take the time to write your own code and when to just use a third party solution.
I'm new here, and after searching for a while I still can't find a way to upload files. Oh well, here's the code in a post. Sorry for the non-descriptive variable names and lack of comments. I guess the main functions you'll want to look at are processPicture and showPicture.
Edit: and just to reiterate, I started this with the example in this tutorial.
import wx, os, string, sys
from PIL import Image
# Scroll wheel and +/- do zoom in/out. f toggles full screen. r rotates.
# m changes PIL mode from low quality (fast) to high quality (slow).
# Images under 1000x1000 are automatically on high quality.
# Middle button down while dragging moves image around, as do arrow
# keys (if image is bigger than window).
# Left and right mouse buttons are next and previous image.
# There is no functionality to load an image. When an executeable is made, the
# viewer is started by opening an image with it.
# To run this file from command line, comment out line 55 and uncomment
# line 54, then do "viewer.py sampleImage"
# There are several lines that are Windows specific. They (probably) all have
# to do with paths, i.e, "/" vs "\".
class ImageFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,title = "viewer")
self.Centre()
self.Size = (450,450)
self.imageBox = wx.Window(self)
self.vbox = wx.BoxSizer(wx.VERTICAL)
self.CreateStatusBar(5)
self.SetStatusWidths([-1, 70, 50, 50, 30])
self.cursor = wx.StockCursor(wx.CURSOR_ARROW)
self.moveCursor = wx.StockCursor(wx.CURSOR_SIZING)
self.vbox.Add(self.imageBox,proportion=1,flag = wx.EXPAND)
self.SetSizer(self.vbox)
self.Show()
self.sbm = 0
self.sbmList = []
self.name = ''
self.url = ''
self.dir = ''
self.factor = 1.0
self.rotation = 0
self.width = 0
self.height = 0
self.count = 0
self.size = 0
self.numOfPics = 0
self.mc = False
self.fs = False
self.mode = 0
self.SetStatusText(str(self.mode), 4)
if len(sys.argv) == 2:
#self.url = os.getcwd() + '\\' + sys.argv[1]
self.url = sys.argv[1]
self.name = self.url.split('\\')[len(self.url.split('\\'))-1]
self.dir = self.url.replace('\\' + self.name,'')
self.loadDirectory(self.dir)
self.processPicture()
self.imageBox.Bind(wx.EVT_SIZE, lambda evt: self.rescale(evt,1))
self.imageBox.Bind(wx.EVT_MOUSEWHEEL,self.zoom)
self.imageBox.Bind(wx.EVT_KEY_DOWN, self.keyEvent)
self.imageBox.Bind(wx.EVT_MIDDLE_UP, self.endDrag)
self.imageBox.SetBackgroundColour((0,0,0,0))
self.imageBox.Bind(wx.EVT_LEFT_DOWN, self.next)
self.imageBox.Bind(wx.EVT_RIGHT_DOWN, self.prev)
def nameFromUrl(self,url):
name = url.split('\\')
name = name[len(name)-1]
return name
def processPicture(self, factor = 0):
img = Image.open(self.url)
self.width = img.size[0]
self.height = img.size[1]
ogHeight = self.height
ogWidth = self.width
xWin = self.imageBox.Size[0]
yWin = self.imageBox.Size[1]
winRatio = 1.0*xWin/yWin
imgRatio = 1.0*self.width/self.height
self.factor = factor*self.factor
if factor == 0:
self.factor = 1
mode = 0
if (ogWidth <=1000 and ogHeight <= 1000) or self.mode == 1:
mode = 1
if imgRatio >= winRatio: #match widths
self.width = self.factor*xWin
self.height = self.factor*xWin/imgRatio
img = img.resize((int(self.width),int(self.height)),mode)
else: #match heights
self.height = self.factor*yWin
self.width = self.factor*yWin*imgRatio
img = img.resize((int(self.width),int(self.height)),mode)
label = str(int(100*self.width/ogWidth))
name = self.nameFromUrl(self.url)
index = self.sbmList.index(name)
self.SetStatusText(name, 0)
self.SetStatusText(str(ogWidth) + 'x' + str(ogHeight), 1)
self.SetStatusText(label + '%', 2)
self.SetStatusText(str(index+1) + '/' + str(self.numOfPics), 3)
if self.rotation % 360 != 0:
img = img.rotate(self.rotation)
self.width = img.size[0]
self.height = img.size[1]
wximg = wx.EmptyImage(img.size[0],img.size[1])
wximg.SetData(img.convert("RGB").tostring())
wximg.SetAlphaData(img.convert("RGBA").tostring()[3::4])
self.showPicture(wximg)
def showPicture(self,img):
bmp = wx.BitmapFromImage(img)
x = (self.imageBox.Size[0] - self.width)/2.0
y = (self.imageBox.Size[1] - self.height)/2.0
tmp = wx.StaticBitmap(self.imageBox,wx.ID_ANY,bmp,(x,y))
tmp.Bind(wx.EVT_LEFT_DOWN, self.next)
tmp.Bind(wx.EVT_RIGHT_DOWN, self.prev)
tmp.Bind(wx.EVT_MOTION, self.drag)
tmp.Bind(wx.EVT_MIDDLE_UP, self.endDrag)
tmp.SetBackgroundColour((180,180,180,180))
if self.sbm:
self.sbm.Destroy()
self.sbm = tmp
self.imageBox.Refresh()
def loadDirectory(self,dir):
self.sbmList = []
for image in os.listdir(dir):
if image.lower().endswith('jpg') or image.lower().endswith('png') or image.lower().endswith('jpeg') or image.lower().endswith('gif') or image.lower().endswith('bmp'):
self.sbmList.append(image)
self.numOfPics = len(self.sbmList)
def next(self,event):
if self.name in self.sbmList:
n = self.sbmList.index(self.name)
if n == len(self.sbmList) - 1:
n = -1
self.name = self.sbmList[n + 1]
self.url = self.dir + '\\' + self.name
self.rotation = 0
self.processPicture()
def prev(self,event):
if self.name in self.sbmList:
n = self.sbmList.index(self.name)
if n == 0:
n = len(self.sbmList)
self.name = self.sbmList[n - 1]
self.url = self.dir + '\\' + self.name
self.rotation = 0
self.processPicture()
def rescale(self,event,factor):
if self.url and self.GetStatusBar(): #close is seen as a size event.
self.processPicture(factor)
def zoom(self,event):
factor = 1.25
if event.GetWheelRotation() < 0:
factor = 0.8
self.rescale(event,factor)
def keyEvent(self,event):
code = event.GetKeyCode()
if code == 43: #plus
self.rescale(event,1.25)
elif code == 45: #minus
self.rescale(event,0.8)
elif code == 82 and self.url: #r
self.rotation = self.rotation + 90
self.processPicture(1)
elif code == 70: #f
self.toggleFS()
elif (code == 314 or code == 315 or code == 316 or code == 317) and self.sbm:
#left, up, right, down
self.scroll(code)
elif code == 77: #m
if self.mode == 0:
self.mode = 1
else:
self.mode = 0
self.SetStatusText(str(self.mode), 4)
self.processPicture(1)
def scroll(self,code):
boxPos = self.imageBox.GetScreenPositionTuple()
imgPos = self.sbm.GetScreenPositionTuple()
delta = 20
if code == 314 and self.width > self.imageBox.Size[0]:
compare = boxPos[0] - imgPos[0]
if compare <= delta:
delta = max(compare,0)
self.imageBox.ScrollWindow(delta,0)
if code == 315 and self.height > self.imageBox.Size[1]:
compare = boxPos[1] - imgPos[1]
if compare <= delta:
delta = max(compare,0)
self.imageBox.ScrollWindow(0,delta)
if code == 316 and self.width > self.imageBox.Size[0]:
compare = imgPos[0] + self.sbm.Size[0] - boxPos[0] - self.imageBox.Size[0]
if compare <= delta:
delta = max(compare,0)
self.imageBox.ScrollWindow(-delta,0)
if code == 317 and self.height > self.imageBox.Size[1]:
compare = imgPos[1] + self.sbm.Size[1] - boxPos[1] - self.imageBox.Size[1]
if compare <= delta:
delta = max(compare,0)
self.imageBox.ScrollWindow(0,-delta)
def drag(self,event):
if event.MiddleIsDown():
if not self.mc:
self.SetCursor(self.moveCursor)
self.mc = True
boxPos = self.imageBox.GetScreenPositionTuple()
imgPos = self.sbm.GetScreenPositionTuple()
if self.count == 0:
self.x = event.GetX()
self.y = event.GetY()
self.count = self.count + 1
if self.count > 1:
deltaX = event.GetX() - self.x
deltaY = event.GetY() - self.y
if imgPos[0] >= boxPos[0] and deltaX > 0:
deltaX = 0
if imgPos[0] + self.width <= boxPos[0] + self.imageBox.Size[0] and deltaX < 0:
deltaX = 0
if imgPos[1] >= boxPos[1] and deltaY > 0:
deltaY = 0
if imgPos[1] + self.height <= boxPos[1] + self.imageBox.Size[1] and deltaY < 0:
deltaY = 0
self.imageBox.ScrollWindow(2*deltaX,2*deltaY)
self.count = 0
def endDrag(self,event):
self.count = 0
self.SetCursor(self.cursor)
self.mc = False
def toggleFS(self):
if self.fs:
self.ShowFullScreen(False)
self.fs = False
else:
self.ShowFullScreen(True)
self.fs = True
app = wx.App(redirect = False)
frame = ImageFrame()
app.MainLoop()
And there is Cornice an open source image viewer written in wxPython which might help you
You can try Document/View architecture.
I think it should be available in Python. You can take a look at this tutorial, it is for C++ but approach should be similar. It also shows how to implement selection rectangle.
I actually just made a simple image viewer with wxPython and PIL. I didn't want to, but I was having a hard time finding a viewer as simple as I wanted. Anyway, I started from this page and worked myself up to an app that zooms, rotates, and browses all images in the folder it was started from. When I get home I can post the full code if you like.

Resources