Python/Pygame - Sprite fails to blit - python

My player sprite fails to blit. However, when I uncomment the Rectangle code and comment the sprite code, it blits perfectly fine.
I do not receive an error message when loading the image, the sprite simply does not show up. The controls also act a bit wonky, with it seeming to "float" in the air unless it collides with a wall and jumping not functioning right. I know that it can find the image because a direct blit works.
Whenever I uncomment the Rect code and comment the load_image() code the controls function perfectly.
Here is an image of the screen with load_image().
Here is an image of the screen without load_image().
I have tried directly bilting the image instead of using the for e in entities loop with specified coordinates. It worked, however as specific x and y values were used, the image obviously stayed in the same place, therefore staying at the coordinates on the screen instead of displaying the player's movements. Whenever I run screen.blit(player.image, camera.apply(player)) it does not show up at all.
I have omitted certain things in the code (level array, other classes, etc) but I believe that the necessities are here. If this has a very simple fix, well, I'll feel pretty dumb :/
class Entity(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
class Player(Entity):
def __init__(self, x, y):
Entity.__init__(self)
self.xlevel = 0
self.ylevel = 0
self.onGround = False
# self.image = Surface((32, 32))
# self.image.fill(Color("#000000"))
# self.image.convert()
# self.rect = Rect(x, y, 32, 32)
self.image, self.rect = load_image("zur.png", colorkey=((255, 255, 255)))
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):
return target.rect.move(self.state.topleft)
def update(self, target):
self.state = self.camera_func(self.state, target.rect)
def simple_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
return Rect(-l + HALF_WIDTH, -t + HALF_HEIGHT, w, h)
def complex_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h # center player
l = min(0, l) # stop scrolling at the left edge
l = max(-(camera.width-WIN_WIDTH), l) # stop scrolling at the right edge
t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
t = min(0, t) # stop scrolling at the top
return Rect(l, t, w, h)
def load_image(name, colorkey=None):
fullname = os.path.join('assets', name)
try:
image = pygame.image.load(fullname)
except pygame.error, message:
print 'Cannot load image ' + name + ". Exiting."
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
def main():
global cameraX, cameraY
global mouseX, mouseY
global bulletExists
mouseX = 0
mouseY = 0
bulletExists = False
pygame.init()
screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
pygame.display.set_caption("Tale of Zur")
clock = pygame.time.Clock()
up = down = left = right = running = False
x = y = 0
background_images = []
platforms = []
background_images.append(pygame.image.load("assets/starting_background_1.jpg").convert())
entities = pygame.sprite.Group()
player = Player(32, 32)
bulletx = int(player.xlevel)
bullety = int(player.ylevel)
bullet = Bullet(player.rect.left, player.rect.top)
bullet.update(player.rect.left, player.rect.top)
screen.blit(background_images[0], [0, 0])
if bulletExists is True:
for i in range(10):
if up and i is not 10:
screen.blit(bullet.image, [bullet.bulletxpos + i, player.rect.top])
else:
screen.blit(bullet.image, [bullet.bulletxpos - i, player.rect.top])
camera.update(player)
player.update(up, down, left, right, running, platforms)
for e in entities:
screen.blit(e.image, camera.apply(e))
pygame.display.update()

If you do this (in the Camera.apply() method):
r = target.rect.move(self.state.topleft)
print r
the y co-ordinate is at -25, so it is blitting the image off-screen. I am not sure why this is, but this is the problem.

Related

Black BG during render under tiles, looks fine in Tiled map editor

I started learning Pygame and Tiled map editor. I have the following test:
Example
It looks fine in the editor, the objects that have the black BG are currently on layer_4 (but they do it regardless of layer count).
I already tried using convert_alpha on it, ticking and unticking the transparency color in Tiled when loading in the tile map.
This is the original picture:
Full picture
This is the part where I load in the picture:
def import_cut_graphics(path):
surface = pygame.image.load(path).convert_alpha()
tile_num_x = int(surface.get_size()[0] / TILESIZE)
tile_num_y = int(surface.get_size()[1] / TILESIZE)
cut_tiles = []
for row in range(tile_num_y):
for col in range(tile_num_x):
x = col * TILESIZE
y = row * TILESIZE
new_surface = pygame.Surface((TILESIZE, TILESIZE))
new_surface.blit(surface, (0, 0), pygame.Rect(x, y, TILESIZE, TILESIZE))
cut_tiles.append(new_surface)
return cut_tiles
And this is where I work with it:
class Level:
def __init__(self, level_data, surface):
# general setup
self.all_layers = import_cut_graphics("img\ProjectUtumno_full.png")
self.display_surface = surface
self.world_shift = 0
# terrain setup
layer1_layout = import_csv_layout(level_data["layer_1"])
self.layer1_sprites = self.create_tile_group(layer1_layout, 'layer_1')
# grass setup
layer2_layout = import_csv_layout(level_data["layer_2"])
self.layer2_sprites = self.create_tile_group(layer2_layout, "layer_2")
# crates
layer3_layout = import_csv_layout(level_data["layer_3"])
self.layer3_sprites = self.create_tile_group(layer3_layout, "layer_3")
# layer 4
layer4_layout = import_csv_layout(level_data["layer_4"])
self.layer4_sprites = self.create_tile_group(layer4_layout, "layer_4")
def create_tile_group(self, layout, type):
sprite_group = pygame.sprite.Group()
for row_index, row in enumerate(layout):
for col_index, val in enumerate(row):
if val != '-1':
x = col_index * TILESIZE
y = row_index * TILESIZE
if type == 'layer_1':
tile_surface = self.all_layers[int(val)]
sprite = StaticTile(TILESIZE, x, y, tile_surface)
sprite_group.add(sprite)
if type == "layer_2" :
tile_surface = self.all_layers[int(val)]
sprite = StaticTile(TILESIZE, x, y, tile_surface)
sprite_group.add(sprite)
if type == "layer_3" :
tile_surface = self.all_layers[int(val)]
sprite = StaticTile(TILESIZE, x, y, tile_surface)
sprite_group.add(sprite)
if type == "layer_4" :
tile_surface = self.all_layers[int(val)]
sprite = StaticTile(TILESIZE, x, y, tile_surface)
sprite_group.add(sprite)
return sprite_group
def run(self):
# run the entire game / level
self.camera()
# layer1
self.layer1_sprites.update(self.world_shift)
self.layer1_sprites.draw(self.display_surface)
# layer2
self.layer2_sprites.update(self.world_shift)
self.layer2_sprites.draw(self.display_surface)
# layer3
self.layer3_sprites.update(self.world_shift)
self.layer3_sprites.draw(self.display_surface)
# layer4
self.layer4_sprites.update(self.world_shift)
self.layer4_sprites.draw(self.display_surface)
This is my main game loop:
class Game:
def __init__(self):
pygame.init()
pygame.font.init()
self.screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
self.clock = pygame.time.Clock()
self.screen_name = pygame.display.set_caption("New Game")
self.running = True
self.playing = False
self.level = Level(level_0, self.screen)
self.character_spritesheet = Spritesheet('img\MainCharacter\B_witch_idle.png')
def main(self):
# game loop
while self.running:
self.events()
self.update()
self.draw()
self.running = False
def draw(self):
self.screen.fill(BLACK)
self.level.run()
self.all_sprites.draw(self.screen)
self.clock.tick(FPS)
pygame.display.update()
I did try commenting the screen fill black and got the same result. I tried out set_colorkey with white/black colors but didn't work out.
I add my tile create class too:
class Tile(pygame.sprite.Sprite):
def __init__(self, size, x, y):
super().__init__()
self.image = pygame.Surface((size, size))
self.rect = self.image.get_rect(topleft=(x, y))
def update(self, shift):
self.rect.x += shift
class StaticTile(Tile):
def __init__(self, size, x, y, surface):
super().__init__(size, x, y)
self.image = surface
Thanks in advance if you can figure out why i have this problem.
So for anyone who's having this problem, I managed to solve it by this:
Inside my import_cut_graphics methode I added a set_colorkey(BLACK), turns out the problem occured when I was originally cutting the picture, therefore it didnt matter how much I change it at the latter phases since the problem was in an earlier stage.
def import_cut_graphics(path):
surface = pygame.image.load(path).convert_alpha()
tile_num_x = int(surface.get_size()[0] / TILESIZE)
tile_num_y = int(surface.get_size()[1] / TILESIZE)
cut_tiles = []
for row in range(tile_num_y):
for col in range(tile_num_x):
x = col * TILESIZE
y = row * TILESIZE
new_surface = pygame.Surface((TILESIZE, TILESIZE))
new_surface.blit(surface, (0, 0), pygame.Rect(x, y, TILESIZE, TILESIZE))
new_surface.set_colorkey(BLACK)
cut_tiles.append(new_surface)
return cut_tiles

How do I make my player image bigger on collision while keeping its proportions?

I am making a game in pygame where you now swim around and eat small squares, with an animation to the jellyfish. I've made it so you get bigger when eating, but when adding a number between 1-9 to the scale the image sort of gets wider than I want it to become. When I have the scale go up by 10 or more when eating this problem does not occur as badly.
This is the code for the jellyfish/player:
import pygame, math, time
pt = time.time()
speed = 40
pygame.display.set_mode((800, 500))
img0 = pygame.transform.scale(pygame.image.load("assets/glow0.png"), (30,30)).convert_alpha()
img1 = pygame.transform.scale(pygame.image.load("assets/glow1.png"), (30,30)).convert_alpha()
img2 = pygame.transform.scale(pygame.image.load("assets/glow2.png"), (30,30)).convert_alpha()
img3 = pygame.transform.scale(pygame.image.load("assets/glow3.png"), (30,30)).convert_alpha()
img4 = pygame.transform.scale(pygame.image.load("assets/glow4.png"), (30,30)).convert_alpha()
img5 = pygame.transform.scale(pygame.image.load("assets/glow5.png"), (30,30)).convert_alpha()
img6 = pygame.transform.scale(pygame.image.load("assets/glow6.png"), (30,30)).convert_alpha()
img7 = pygame.transform.scale(pygame.image.load("assets/glow7.png"), (30,30)).convert_alpha()
img8 = pygame.transform.scale(pygame.image.load("assets/glow8.png"), (30,30)).convert_alpha()
class Glow():
rot = 0
rotp = 1
xsp = 0
ysp = 0
def __init__(self, x, y, scale):
self.x, self.y = x, y
self.scale = scale
self.list = [img0, img1, img2, img3, img4, img5, img6, img7, img8]
self.current = 0
self.image = self.list[int(self.current)]
self.rect = self.image.get_rect(center = (x, y))
self.colRect = pygame.rect.Rect((0, 0), (self.rect.width/3, self.rect.height/3))
self.colRect.center = self.rect.center
def update(self, x, y, accex):
global pt, speed
now = time.time()
dt = now - pt
pt = now
self.rect = self.image.get_rect(center = (x, y))
if pygame.key.get_pressed()[pygame.K_UP] or accex:
# animation
self.current += dt*5
if self.current >= len(self.list):
self.current = 0
self.image = pygame.transform.rotate(self.list[int(self.current)], self.rot)
self.rect = self.image.get_rect(center = (x, y))
self.colRect.center = self.rect.center
# go in direction of rotation
self.rotr = math.radians(self.rot)
self.ysp = math.cos(self.rotr)
self.xsp = math.sin(self.rotr)
self.x -= self.xsp*dt*speed
self.y -= self.ysp*dt*speed
if not accex:
if pygame.key.get_pressed()[pygame.K_LEFT]:
self.rot += math.pi*dt*7
if pygame.key.get_pressed()[pygame.K_RIGHT]:
self.rot -= math.pi*dt*7
if accex:
speed += dt*10
def scaleup(self):
self.scale += 2
i = 0
for img in self.list:
self.list.remove(img)
img = pygame.transform.scale(img, (self.scale, self.scale))
self.list.insert(i, img)
i += 1
This is the main code in the game loop that has to do with this:
W, H = 800, 500
sc = pygame.display.set_mode((W, H))
score = 0
score_x, score_y = 10, 10
font = pygame.font.SysFont("calibri", 30)
score_text = font.render("0", True, (255,255,255))
score _rect = score_text.get_rect(topleft = (score_x, score_y))
if lvl0:
glow.update(glow.x, glow.y, accex)
sc.fill((0,0,0))
for food in Food.food_list:
sc.blit(food.image, (food.x, food.y))
if pygame.Rect.colliderect(glow.colRect, food.rect):
Food.food_list.remove(food)
glow.scaleup()
score += 3
score_text = font.render(str(score), True, (255,255,255))
score_rect = score_text.get_rect(topleft = (score_x, score_y))
sc.blit(glow.image, glow.rect)
sc.blit(label, label_rect)
pygame.display.update()
Pygame behaves weird when using the transformed image repetitively as in case of rotation...
I even have faced crashes due to it
So try using the the same image which is initially loaded as img0,img1,etc. and scale it to the desired size. As of now you were using the same scaled image again and again .
This might help
I know there is an already accepted answer, but here is how I do it:
class Wabbit:
# this store the main, unaltered image loaded from disk
_main_image = None
def __init__(self, pos, scale=1):
# if the class._main_image variable is not set
# we do this so we only have to load the image once
# when the first instance is created
if not self._main_image:
# load the image from disk
self._main_image = pygame.image.load('wabbit_alpha.png')
self.pos = Vector2(pos)
self.vel = Vector2()
self.scale = scale
# some variables to store the "previous" values
self._scale = None
self._image = None
#property
def size(self):
# returns the size of our image, as a Vector2
return Vector2(self.image.get_size())
#property
def image(self):
# this is where we look at our current scale
# compare it to our previous _scale
# and update our _image if the two arent the same
if self.scale != self._scale:
# update the previous _scale value
self._scale = self.scale
# get the size of the original image and scale it
# according to our scale value
size = Vector2(self._main_image.get_size()).elementwise() * self.scale
# set our _image to be the scaled version of the main, original image
self._image = pygame.transform.scale(self._main_image, size)
# return our scaled image
return self._image
def update(self, dt):
self.pos += self.vel * dt
def draw(self, surface):
surface.blit(self.image, self.pos-self.size/2)

Pygame line appearing broken

So I was making a turtle like object in python and I had a issue which got resolved.
Now I am noticing a intersting or rather annoying thing that when I attempt to a make a square with lt(90) or rt(270), one of the line appears broken.
Here is my code:
import pygame
from pygame.locals import *
from pygame.math import Vector2
from math import sin, cos, radians
class Turtle:
def __init__(self):
self.vector = Vector2(0, 0)
self.angle = 0
self.pen_width = 25
self.pen_color = (255, 255, 255)
self.pen_visible = True
def forward(self, win, distance):
start = self.vector
offset = Vector2(sin(radians(self.angle)), cos(radians(self.angle)))
offset *= distance
end = start + offset
if self.is_down():
pygame.draw.line(win, self.pen_color, start, end, self.pen_width)
self.vector = end
fd = forward
def backward(self, win, distance):
self.forward(win, -distance)
bk = back = backward
def left(self, angle):
self.angle = (self.angle + angle) % 360
self.angle
lt = left
def right(self, angle):
self.left(-angle)
rt = right
def goto(self, win, pos):
if self.is_down():
pygame.draw.line(win, self.pen_color, self.vector, pos, self.pen_width)
self.vector = Vector2(pos)
setposition = setpos = goto
def set_angle(self, angle= None):
if not angle:
return self.angle
self.angle = angle
def position(self):
return self.vector.xy
pos = position
def sety(self, y):
self.vector.y = y
def setx(self, x):
self.vector.x = x
def xcor(self):
return self.vector.x
def ycor(self):
return self.vector.y
def penup(self):
self.pen_visible = False
pu = up = penup
def pendown(self):
self.pen_visible = True
pd = down = pendown
def is_down(self):
return self.pen_visible
def write(self, win, font_label):
win.blit(font_label, self.vector)
def test():
pygame.init()
pygame.font.init()
WIDTH, HEIGHT = 500, 500
CAPTION = 'Caption'
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(CAPTION)
FPS = 60
clock = pygame.time.Clock()
mytut = Turtle()
mytut.pen_width = 5
mytut.goto(win, (250, 250))
mytut.pen_color = '#00FF00'
for _ in range(4):
mytut.fd(win, 100)
mytut.rt(270)
while True:
clock.tick(FPS)
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
if __name__ == '__main__':
test()
Screenshot -
Moreover this issue does not occur when I use lt(270) or rt(90).
I dont know why this happens in pygame. I feel it may related to some floating point numbers being a bit off but dont know exactly why?
I need help to fix this!
The problem is caused by a floating point inaccuracy. round the coordinates to solve the issue. You can further improve the representation, by drawing a small circle at the end of the line:
class Turtle:
# [...]
def forward(self, win, distance):
start = self.vector
offset = Vector2(sin(radians(self.angle)), cos(radians(self.angle)))
offset *= distance
end = start + offset
if self.is_down():
s = round(start.x), round(start.y)
e = round(end.x), round(end.y)
pygame.draw.line(win, self.pen_color, s, e, self.pen_width)
pygame.draw.circle(win, self.pen_color, e, self.pen_width // 2)
self.vector = end

How to make an image move using OOP

I'm new to pygame, and I'm trying to get the image (Player1) to move in OOP. I initially used procedural and it worked but when I put it into OOP format, the image no longer works.
This is the code I used when doing procedural programming, which I got by adapting code I found from https://www.pygame.org/docs/ref/key.html#comment_pygame_key_name
#Moving player
import pygame
pygame.init()
ScreenSize = 1200, 600
Screen = pygame.display.set_mode(ScreenSize)
Screen.fill([255, 255, 255])
XPos = 0
YPos = 0
Plyr = []
PlyrRct = []
Background = pygame.image.load('carpet.jpg')
Player = pygame.image.load('player.jpg')
PlayerTemp = Player.subsurface(1, 0, 64, 64)
PlayerRectTemp = PlayerTemp.get_rect()
Plyr.append(PlayerTemp)
PlyrRct.append(PlayerRectTemp)
End = False
while not End:
Key = pygame.key.get_pressed()
if Key[pygame.K_a]:
XPos -= 4
if Key[pygame.K_d]:
XPos += 4
if Key[pygame.K_w]:
YPos -= 4
if Key[pygame.K_s]:
YPos += 4
Background = pygame.image.load('carpet.jpg')
Screen.blit(Background, (0, 0))
PlyrRct[0].left = XPos
PlyrRct[0].top = YPos
Screen.blit(Plyr[0], PlyrRct[0])
for event in pygame.event.get():
if event.type==pygame.QUIT:sys.exit()
pygame.display.flip()
This is currently my oop program
# Player Move test
import pygame
pygame.init()
class LoadImages(object):
def __init__(self, Image, Top, Left, Width, Height):
self.Image = pygame.image.load(Image)
self.Top = Top
self.Bottom = Top + Height
self.Left = Left
self.Right = Left + Width
class Player(LoadImages):
def __init__(self, Image, Top, Left, Width, Height):
LoadImages.__init__(self, Image, Top, Left, Width, Height)
def Move(self, A, D, W, S):
#self.CheckCollision()
if A:
self.Left -= 4
self.Right -= 4
if D:
self.Left += 4
self.Right += 4
if W:
self.Top += 4
self.Bottom += 4
if S:
self.Top -= 4
self.Bottom -= 4
#def CheckCollision(self):
#print ()
class Item(LoadImages):
def __init__(self, Image, Top, Left, Width, Height):
LoadImages.__init__(self, Image, Top, Left, Width, Height)
#def Examine(self):
#print ()
Player1 = Player("player.jpg", 0, 0, 300, 300)
Item1 = Item("player.jpg", 0, 0, 300, 300)
Background = pygame.image.load("carpet.jpg")
ScreenSize = 1200, 600
Screen = pygame.display.set_mode(ScreenSize)
Screen.fill([255, 255, 255])
End = False
while not End:
Screen.blit(Background, (0, 0))
Screen.blit(Player1.Image, (Player1.Top, Player1.Left))
pygame.display.update()
Key = pygame.key.get_pressed()
Player1.Move(Key[pygame.K_a], Key[pygame.K_d], Key[pygame.K_w], Key[pygame.K_s])
I'm expecting the image (Player1) to move on the screen but it won't move anywhere.
The images in the program are just being used for testing purposes and will be replaced with a .png
You're missing the event processing in your second example. If you don't call pygame.event.get() (or poll()), your window won't respond (depending on your OS/window manager).
So simple add
for e in pygame.event.get():
if e.type == pygame.QUIT:
End = True
to your while loop.
Also, since you're using pygame, take a look at its Sprite class, which you can use for OOP with pygame. Somewhat related to your question is this one. Maybe you'll find it useful.

How can I mouse-scroll around a 2D tile map in pygame?

I am trying to play around with pygame and I have using some examples that I found to learn and create a simple. My next goal is to create a 2D tile map bigger than the screen size and then being able to scroll around with the mouse. I would like to make something similar as a strategic game, where if you move the mouse to the edges of the screen, the "camara" will move in that direction, showing that part of the map (I would like also to stop the camara if it reaches the end of the map). At this moment, if I hover the mouse over the edges, it will only move once.
import pygame, os
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
SCREEN_WIDTH = 5*40
SCREEN_HEIGHT = 7*40
#functions to create our resources
def load_image(name, colorkey=None):
try:
image = pygame.image.load(name)
except pygame.error, message:
print 'Cannot load image:', name
raise SystemExit, message
image = image.convert_alpha()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
#classes for our game objects
class Camera(object):
def __init__(self, camera_func, width, height):
self.camera_func = camera_func
self.state = pygame.Rect(100,100, width, height)
def apply(self, rect):
l, t, w, h = rect
if 0 <= self.state[0] <= (SCREEN_WIDTH/5):
l += 10
elif (SCREEN_WIDTH - (SCREEN_WIDTH/5)) < self.state[0] <= SCREEN_WIDTH:
l -=10
if 0 <= self.state[1] <= (SCREEN_HEIGHT/5):
t += 10
elif (SCREEN_HEIGHT - (SCREEN_HEIGHT/5)) < self.state[1] <= SCREEN_HEIGHT:
t -=10
return rect.move(l,t)
def update(self):
pos = pygame.mouse.get_pos()
self.state.topleft = pos
#self.state = self.camera_func(self.state)
def complex_camera(camera):
l, t, w, h = camera
l, t, _, _ = -l, -t, w, h
l = min(0, l) # stop scrolling at the left edge
l = max(-(camera.width-SCREEN_WIDTH), l) # stop scrolling at the right edge
t = max(-(camera.height-SCREEN_HEIGHT), t) # stop scrolling at the bottom
t = min(0, t) # stop scrolling at the top
return pygame.Rect(l, t, w, h)
def main ():
pygame.init()
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
pygame.display.set_caption("W40K")
grasstile = pygame.image.load('./textures/grass.png')
watertile = pygame.image.load('./textures/water.png')
waterbeach = pygame.image.load('./textures/dirt.png')
grassrect = grasstile.get_rect()
waterrect = watertile.get_rect()
waterb = waterbeach.get_rect()
TILESIZE = 40
tilemap = [
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,waterbeach,waterbeach,waterbeach,watertile,watertile,watertile,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[waterbeach,waterbeach,waterbeach,waterbeach,watertile,watertile,watertile,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,waterbeach,waterbeach,waterbeach,waterbeach,waterbeach,grasstile,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[watertile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[watertile,watertile,waterbeach,waterbeach,waterbeach,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,waterbeach,waterbeach,waterbeach,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,grasstile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,grasstile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
[grasstile,grasstile,waterbeach,waterbeach,watertile,watertile,waterbeach,waterbeach,grasstile,grasstile,waterbeach,watertile,watertile,watertile,waterbeach,waterbeach,waterbeach,grasstile,grasstile,waterbeach],
]
#Creates surface of the background
map_surface = pygame.Surface((len(tilemap[0])*TILESIZE, len(tilemap)*TILESIZE))
#Display the surface
for y,row in enumerate(tilemap):
for x,tile_surface in enumerate(row):
map_surface.blit(tile_surface,(x*TILESIZE,y*TILESIZE))
total_level_width = len(tilemap[0]) * 40
total_level_height = len(tilemap) * 40
camera = Camera(complex_camera,total_level_width, total_level_height)
#mouse = Mouse()
#allsprites = pygame.sprite.RenderPlain((mouse))
clock = pygame.time.Clock()
while 1:
clock.tick(60)
#Handle Input Events
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN and event.key == K_ESCAPE:
return
screen.fill(BLACK)
#Camera moves.
camera.update()
#Display background.
screen.blit(map_surface, camera.apply(waterrect))
pygame.display.flip()
if __name__ == "__main__":
main()
pygame.quit()
I think that the problem is in the camara function and the apply function, but I have no clue to improve this and make the camara work properly.
Thanks!
It is hard for me to say exactly what is wrong with your sode ( i got too little experience in coding ) , but i just realised movin screen by mouse in my script and i did this :
screen=pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT),32)
Map=pygame.image.load(os.path.join('Image','MAP.png')).convert_alpha()
startX,startY=0,0 # starting coordinates for Map
while 1:
screen.fill(white)
screen.blit(Map,(startX,startY))
for event in pygame.event.get():
if event.type == MOUSEMOTION :
mousepos=pygame.mouse.get_pos()
if WINDOWHEIGHT-mousepos[1]<50: # if y-position of mouse is 50 pixel far from lower edge ..
startY -= 5 # ..move Map by 5 px
if mousepos [1]<50:
startY += 5
if mousepos [0]<50 :
startX += 5
if WINDOWWIDTH - mousepos[0]<50:
startX -= 5
pygame.display.flip()
Hope this can suggest you an idea how to improve your code

Categories