import pygame
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("TEST2")
black=(0,0,0)
white=(255,255,255)
moveX,moveY=0,0
clock = pygame.time.Clock()
class Sprite:
def __init__(self,x,y):
self.x=x
self.y=y
self.width=100
self.height=110
self.i100 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite0.PNG")
self.i1 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite1.PNG")
self.i2 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite2.PNG")
self.i3 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite3.PNG")
self.i4 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite4.PNG")
self.i5 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite5.PNG")
self.i6 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite6.PNG")
self.i7 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite7.PNG")
self.i8 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite8.PNG")
self.i9 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite9.PNG")
self.i10 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite10.PNG")
self.i11 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite11.PNG")
self.timeTarget=10
self.timeNum=0
self.currentImage=0
def update(self):
self.timeNum+=1
if(self.timeNum==self.timeTarget):
if (self.currentImage==0):
self.currentImage+=1
else:
self.currentImage=0
self.timeNum=0
self.render()
def render(self):
if (self.currentImage==0):
window.blit(self.i100, (self.x,self.y))
else:
window.blit(self.i1, (self.x,self.y))
window.blit(self.i2, (self.x,self.y))
window.blit(self.i3, (self.x,self.y))
player=Sprite(110,100)
gameLoop = True
while gameLoop:
for event in pygame.event.get():
if event.type==pygame.QUIT:
gameLoop = False
if (event.type==pygame.KEYDOWN):
if (event.key==pygame.K_LEFT):
moveX = -3
if (event.key==pygame.K_RIGHT):
moveX = 3
if (event.key==pygame.K_UP):
moveY = -3
if (event.key==pygame.K_DOWN):
moveY = 3
if (event.type==pygame.KEYUP):
if (event.key==pygame.K_LEFT):
moveX=0
if (event.key==pygame.K_RIGHT):
moveX=0
if (event.key==pygame.K_UP):
moveY=0
if (event.key==pygame.K_DOWN):
moveY=0
window.fill(black)
player.x+=moveX
player.x+=moveY
player.update()
clock.tick(50)
pygame.display.flip()
pygame.quit()
What im doing is trying to animate 11 photos into an animation with pygame. this code works but when I run it the pictures seem to almost overlap. I did window.blit for the first few images and put them under else? I feel like I rendered them wrong. also I must add im really bad at picking up what people are trying to say and best learn from examples. Thanks!
BTW: your code could look like this:
I use my images in example but there are still lines with your images.
I use timer to change images.
You can press space to pause and escape to exit.
etc.
import pygame
#----------------------------------------------------------------------
class Sprite:
def __init__(self, x, y, curren_time):
self.rect = pygame.Rect(x, y, 100, 110)
self.images = []
#for x in range(12):
for x in range(1,4):
img = pygame.image.load("ball" + str(x) +".png")
#img = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite" + str(x) +".PNG")
self.images.append( img )
self.current_image = 0
self.time_num = 100 # miliseconds
self.time_target = curren_time + self.time_num
def update(self, curren_time):
if curren_time >= self.time_target:
self.time_target = curren_time + self.time_num
self.current_image += 1
if self.current_image == len(self.images):
self.current_image = 0
def render(self, window):
window.blit(self.images[self.current_image], self.rect)
#----------------------------------------------------------------------
# CONSTANS - uppercase
BLACK = (0 ,0 ,0 )
WHITE = (255,255,255)
#----------------------------------------------------------------------
# MAIN
def main():
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("TEST2")
move_x, move_y = 0, 0
clock = pygame.time.Clock()
curren_time = pygame.time.get_ticks()
player = Sprite(110,100, curren_time)
font = pygame.font.SysFont(None, 150)
pause_text = font.render("PAUSE", 1, WHITE)
pause_rect = pause_text.get_rect( center = window.get_rect().center ) # center text on screen
# mainloop
state_game = True
state_pause = False
while state_game:
curren_time = pygame.time.get_ticks()
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
state_game = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
state_game = False
elif event.key == pygame.K_SPACE:
state_pause = not state_pause
if event.key == pygame.K_LEFT:
move_x = -3
elif event.key == pygame.K_RIGHT:
move_x = 3
elif event.key == pygame.K_UP:
move_y = -3
elif event.key == pygame.K_DOWN:
move_y = 3
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
move_x = 0
elif event.key in (pygame.K_UP, pygame.K_DOWN):
move_y = 0
# moves
if not state_pause:
player.rect.x += move_x
player.rect.y += move_y
player.update(curren_time)
# draws
window.fill(BLACK)
player.render(window)
if state_pause:
window.blit(pause_text, pause_rect)
pygame.display.flip()
# FPS
clock.tick(50)
# the end
pygame.quit()
#----------------------------------------------------------------------
if __name__ == '__main__':
main()
ball1.png
ball2.png
ball3.png
By putting all those window.blit(...) calls one after another, you are drawing those three frames on top of each other. Even if your computer lagged for a second between each call, you still wouldn't see them individually because they all can't appear until pygame.display.flip() is called.
You should store the images in a list, and keep a counter like currentFrame that loops from 0 to number_of_frames-1 (or len(frames)-1). Then each frame of the game you do something like this:
class Player:
...
def draw(window):
window.blit(self.frames[self.currentFrame])
Related
i am making a top down car racing game as project (i'm new to python) and i want to know how to make the track (that i have made a background) move, so that when the user's car is moving, the track is essentially moving in the opposite direction so it looks like you are progressing through the course of the circuit. (The camera is focused on the user's car)
Thanks
import math
import random
import pygame
pygame.mixer.pre_init(44100,16,2,4096)
pygame.init()
screen = pygame.display.set_mode((1280, 800))
rect = screen.get_rect()
clock = pygame.time.Clock()
#music
pygame.mixer.music.load("Wice.mp3")
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(-1)
WHITE = pygame.Color('white')
VEHICLE1 = pygame.Surface((40, 70), pygame.SRCALPHA)
VEHICLE1.fill((130, 180, 20))
#blitting car onto 'rectangle car'
VEHICLE1 = pygame.image.load("YellowLambo.png")
screen.blit(VEHICLE1,(0,0))
pygame.display.update()
VEHICLE2 = pygame.Surface((40, 70), pygame.SRCALPHA)
VEHICLE2.fill((200, 120, 20))
#blitting computer's car
VEHICLE2 = pygame.image.load("RedLambo.png")
screen.blit(VEHICLE2,(0,0))
pygame.display.update()
BACKGROUND = pygame.Surface((1280, 800))
BACKGROUND.fill((127, 69, 2))
BACKGROUND = pygame.image.load("track.png").convert()
screen.blit(BACKGROUND,(0,0))
pygame.display.update()
class Entity(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
class VehicleSprite(Entity):
MAX_FORWARD_SPEED = 10
MAX_REVERSE_SPEED = 2
ACCELERATION = 0.05
TURN_SPEED = 0.000000000001
def __init__(self, image, position):
Entity.__init__(self)
self.src_image = image
self.image = image
self.rect = self.image.get_rect(center=position)
self.position = pygame.math.Vector2(position)
self.velocity = pygame.math.Vector2(0, 0)
self.speed = self.direction = 0
self.k_left = self.k_right = self.k_down = self.k_up = 0
def update(self, time):
# SIMULATION
self.speed += self.k_up + self.k_down
# To clamp the speed.
self.speed = max(-self.MAX_REVERSE_SPEED,
min(self.speed, self.MAX_FORWARD_SPEED))
# Degrees sprite is facing (direction)
self.direction += (self.k_right + self.k_left)
rad = math.radians(self.direction)
self.velocity.x = -self.speed*math.sin(rad)
self.velocity.y = -self.speed*math.cos(rad)
self.position += self.velocity
self.image = pygame.transform.rotate(self.src_image, self.direction)
self.rect = self.image.get_rect(center=self.position)
class Background(pygame.sprite.Sprite):
def __init__(self, image, location):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect(topleft=location)
def game_loop():
background = Background(BACKGROUND, [0, 0])
bike = VehicleSprite(VEHICLE1, rect.center)
ball = VehicleSprite(VEHICLE2, rect.center)
bike_group = pygame.sprite.Group(bike)
ball_group = pygame.sprite.Group(ball)
all_sprites = pygame.sprite.Group(bike_group, ball_group)
camera = pygame.math.Vector2(0, 0)
done = False
while not done:
time = clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
# Bike Input (Player 1)
if event.key == pygame.K_d:
bike.k_right = -5
elif event.key == pygame.K_a:
bike.k_left = 5
elif event.key == pygame.K_w:
bike.k_up = 2
elif event.key == pygame.K_s:
bike.k_down = -2
elif event.key == pygame.K_ESCAPE:
done = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_d:
bike.k_right = 0
elif event.key == pygame.K_a:
bike.k_left = 0
elif event.key == pygame.K_w:
bike.k_up = 0
elif event.key == pygame.K_s:
bike.k_down = 0
camera -= bike.velocity
all_sprites.update(time)
screen.fill(WHITE)
screen.blit(background.image, background.rect)
for sprite in all_sprites:
screen.blit(sprite.image, sprite.rect.topleft+camera)
pygame.display.flip()
game_loop()
pygame.quit()
Just add the camera vector to the background.rect.topleft position as well:
screen.blit(background.image, background.rect.topleft+camera)
I am trying to move this rectangle to make Pong. I had it working before but I messed up the code.
Could anyone help me make it move and possibly make my code look cleaner?
Again, I made it move, but the problem seems to be in the Update method.
Possibly the ScreenSide parameter???...
import pygame, sys, random
from pygame.locals import *
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((800, 600))
rectImg1 = 'Rect.jpg'
rectImg2 = 'Rect2.jpg'
RIGHT = "RIGHT"
LEFT = "LEFT"
WHITE = (255,255,255)
FPS = 30
PADDLE_SPEED = 5
BALL_SPEED = 10
fpsClock = pygame.time.Clock()
xPos = 0
yPos = 0
leftY = 20
rightY = 20
class Paddle(pygame.sprite.Sprite):
def __init__(self, screenSide):
pygame.sprite.Sprite.__init__(self)
self.screenSide = screenSide
if self.screenSide == LEFT:
self.image = pygame.image.load(rectImg1).convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = 20
self.rect.y = 20
def update(self):
if self.screenSide == LEFT:
self.y = leftY
allSpritesGroup = pygame.sprite.Group()
paddle = Paddle(LEFT)
allSpritesGroup.add(paddle)
#code to make it move
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if paddle.screenSide == LEFT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
paddle.y += PADDLE_SPEED
elif event.key == pygame.K_w:
paddle.y -= PADDLE_SPEED
elif event.type == pygame.KEYUP:
if event.key == pygame.K_s or event.key == pygame.K_w:
paddle.y == 0
screen.fill((255,255,255))
allSpritesGroup.draw(screen)
allSpritesGroup.update()
pygame.display.flip()
fpsClock.tick(FPS)
pygame.quit()
Just a guess but your problem might be in:
elif event.type == pygame.KEYUP:
if event.key == pygame.K_s or event.key == pygame.K_w:
paddle.y == 0
This looks more like a comparison and if not then you're setting the y to 0 whenever you let go of a key.
Also, You're right about the update function:
def update(self):
if self.screenSide == LEFT:
self.y = leftY
You're constantly setting the y to 20 so it won't move since every time it updates its moved to 20.
Your event handling is broken. The KEYDOWN and KEYUP events are outside of the event loop because of this line if paddle.screenSide == LEFT:. You also need to update paddle.rect.y not paddle.y and you should do that in the class not with global variables. I'd give the paddles a self.y_speed attribute which you set in the event loop and then use it to update the self.rect.y position each frame in the update method. And remove the screenSide checks and just pass the image and position to the sprites during the instantiation.
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen_rect = screen.get_rect()
rectImg1 = pygame.Surface((30, 50))
rectImg1.fill((20, 20, 120))
rectImg2 = pygame.Surface((30, 50))
rectImg2.fill((120, 10, 20))
WHITE = (255,255,255)
FPS = 30
PADDLE_SPEED = 5
fpsClock = pygame.time.Clock()
class Paddle(pygame.sprite.Sprite):
def __init__(self, image, pos):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect(topleft=pos)
self.y_speed = 0
def update(self):
self.rect.y += self.y_speed
allSpritesGroup = pygame.sprite.Group()
paddle = Paddle(rectImg1, (20, 20))
paddle2 = Paddle(rectImg2, (750, 20))
allSpritesGroup.add(paddle, paddle2)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
paddle.y_speed = PADDLE_SPEED
elif event.key == pygame.K_w:
paddle.y_speed = -PADDLE_SPEED
elif event.type == pygame.KEYUP:
if event.key == pygame.K_s or event.key == pygame.K_w:
paddle.y_speed = 0
allSpritesGroup.update()
screen.fill(WHITE)
allSpritesGroup.draw(screen)
pygame.display.flip()
fpsClock.tick(FPS)
So I'm just learning how to work with classes and getting them to work between each different class. I'm trying to design a game where the user moves around and picks up food and each time the user picks up a piece of food the size of the character increases. I've done something similar before but now that there are classes involved I seem to have a hard time finding which class this should be part of. I added within the sprite update method that if it collides with a cherry then the size of the player should increase by 5 pixels each time. using the code :
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
Each time the game runs the player size doesn't change and for some reason the game no longer ends after the player has eaten a certain amount of cherries so I was just wondering if I was using a wrong method of changing the size of the player perhaps there may be an easier way to do so? Heres the rest of the code incase it helps at all.
import pygame, glob, random, time
from pygame.locals import *
from LabelClass import *
# CONSTANTS
WIDTH = 400 # Window width
HEIGHT = 400 # Window height
BLACK = (0,0,0) # Colors
WHITE = (255,255,255)
BACKGR = BLACK # Background Color
FOREGR = WHITE # Foreground Color
FPS = 40 # Frames per second
pwidth = 40
pheight = 40
class Food:
def __init__(self,screen,centerx,centery):
self.screen = screen
self.surface = pygame.image.load('cherry.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
class Player:
def __init__(self, screen, centerx,
centery, speed, backcolor):
self.surface = pygame.image.load('player.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
self.speed = speed
self.screen = screen
self.backcolor = backcolor
self.dir = ''
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
def move(self):
if self.dir != '':
if self.dir == 'd' and self.rect.bottom < HEIGHT:
self.rect.top += self.speed
if self.dir == 'u' and self.rect.top > 0:
self.rect.top -= self.speed
if self.dir == 'l' and self.rect.left > 0:
self.rect.left -= self.speed
if self.dir == 'r' and self.rect.right < WIDTH:
self.rect.right += self.speed
def jump(self,top,left):
self.rect.top = top
self.rect.left = left
class SpritesGame:
def __init__(self,screen):
self.screen = screen
screen.fill(BLACK)
pygame.display.update()
music_file = getRandomMusic()
pygame.mixer.music.load(music_file)
pygame.mixer.music.play(-1,0.0)
self.music = True
self.Foods = [ ]
self.Eaten = 0
for i in range(20):
self.Foods.append(
Food(self.screen,
WIDTH*random.randint(1,9)//10,
HEIGHT*random.randint(1,9)//10))
for f in self.Foods:
f.draw()
self.Player = Player(screen,WIDTH//2,HEIGHT//2,6,BLACK)
self.PickUpSound = pygame.mixer.Sound('pickup.wav')
self.PlaySound = True
self.startTime = time.clock()
self.endTime = -1
self.Won = False
def update(self):
self.screen.fill(BLACK)
pickedUp = False
for f in self.Foods[:]:
if self.Player.rect.colliderect(f.rect):
self.Foods.remove(f)
self.Foods.append(Food(self.screen,WIDTH*random.randint(1,9)//10,HEIGHT*random.randint(1,9)//10))
pickedUp = True
self.Eaten += 1
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
#self.rect.center = center
print self.Eaten
if pickedUp and self.PlaySound:
self.PickUpSound.play()
for f in self.Foods:
f.draw()
if self.Eaten == 40:
self.Won = True
self.endTime = time.clock()
self.Player.move()
self.Player.draw()
pygame.display.update()
def toggleMusic(self):
self.music = not self.music
if self.music:
pygame.mixer.music.play(-1,0.0)
else:
pygame.mixer.music.stop()
def run(self):
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYDOWN: # Keeps moving as long as key down
if event.key == K_LEFT or event.key == ord('a'):
self.Player.dir = 'l'
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = 'r'
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = 'u'
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = 'd'
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
if event.key == K_ESCAPE:
stop = True
if event.key == K_LEFT or event.key == ord('a'): # End repetition.
self.Player.dir = ''
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = ''
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = ''
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = ''
if event.key == ord('x'):
top = random.randint(0,
HEIGHT - self.Player.rect.height)
left = random.randint(0,
WIDTH - self.Player.rect.width)
self.Player.jump(top,left)
if event.key == ord('m'):
self.toggleMusic()
if event.key == ord('p'):
self.PlaySound = not self.PlaySound
mainClock.tick(FPS)
self.update()
if self.Won:
stop = True # END OF WHILE
if self.Won:
self.screen.fill(BLACK)
pygame.display.update()
msg = (str((int(self.endTime)
-int(self.startTime)))
+" seconds to finish. Hit Q.")
L2 = Label(display,WIDTH//2,HEIGHT*7//8,26,msg,WHITE,BLACK)
L2.draw()
stop = False
while not stop:
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
pygame.event.get()
pygame.mixer.music.stop()
def getRandomMusic():
mfiles = glob.glob("*.wav")
mfiles.append(glob.glob("*.mid"))
r = random.randint(0,len(mfiles)-1)
return mfiles[r]
def OpeningScreen(screen):
screen.fill(BLACK)
pygame.display.update()
L1 = Label(display,WIDTH//2,HEIGHT*7//8,26,"Hit Q to Quit, P to Play.",WHITE, BLACK)
L1.draw()
# Properly initiate pygame
pygame.init()
# pygame.key.set_repeat(INT,INT)
# Set the clock up
mainClock = pygame.time.Clock()
# Initialize Display
display = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Sprites and Sounds V06')
OpeningScreen(display)
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYUP:
if event.key == ord('p'):
game = SpritesGame(display)
game.run()
OpeningScreen(display)
if event.key == ord('q'):
stop = True
pygame.quit()
Surface.get_rect() will always return a rect starting at (0,0), and you also are modifying SpritesGame.rect. I think you should change
self.rect = self.Player.surface.get_rect()
to
self.Player.rect.inflate_ip(5, 5)
import pygame
class Sprite:
def __init__(self, x, y, curren_time):
self.rect = pygame.Rect(x, y, 100, 110)
self.images = []
#Tells pygame the image list that you want to stitch together
for x in range(10):
img = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST6/Cernunnos" + str(x) +".PNG")
#Append the image to each other to create the animation effect
self.images.append( img )
self.current_image = 0
self.time_num = 100
self.time_target = curren_time + self.time_num
def update(self, curren_time):
if curren_time >= self.time_target:
self.time_target = curren_time + self.time_num
self.current_image += 1
if self.current_image == len(self.images):
self.current_image = 0
def render(self, window):
window.blit(self.images[self.current_image], self.rect)
#Colors
black = (0,0,0)
white = (255,255,255)
def main():
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Sprites")
move_x, move_y = 0, 0
clock = pygame.time.Clock()
curren_time = pygame.time.get_ticks()
player = Sprite(110,100,curren_time)
font = pygame.font.SysFont(None, 150)
pause_text = font.render("PAUSE",1,white)
pause_rect = pause_text.get_rect( center = window.get_rect().center )
#Adding how many places the image moves when using the key function
state_game = True
state_pause = False
#So while True
while state_game:
curren_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
state_game = False
elif event.type == pygame.KEYDOWN:
if event.key ==pygame.K_ESCAPE:
state_game = False
elif event.key == pygame.K_SPACE:
state_pause = not state_pause
if event.key == pygame.K_LEFT:
move_x = -3
elif event.key == pygame.K_RIGHT:
move_y = 3
elif event.key == pygame.K_UP:
move_x = -3
elif event.key == pygame.K_DOWN:
move_y = 3
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
move_x = 0
elif event.key in (pygame.K_UP, pygame.K_DOWN):
move_y = 0
if not state_pause:
player.rect.x += move_x
player.rect.y += move_y
player.update(curren_time)
#Fills the window with a color
window.fill(black)
player.render(window)
if state_pause:
window.blit(pause_text,pause_rect)
pygame.display.flip()
clock.tick(50)
pygame.quit()
if __name__ == '__main__':
main()
#Code constructed by furas
So the problem is whenever I hit the right key the animation slides off the screen on the left. the animation does not stop when you take your finger off the key. I have searched for the problem myself and am unable to find any problems. Please if you see something that may be causing the problem let me know. Thanks! (Up key = Down, Down key = Down, Right key = Left, Left key = Left)
Your problem is that you have move_x and move_y swapped for K_RIGHT and K_UP.
elif event.key == pygame.K_RIGHT:
move_y = 3
elif event.key == pygame.K_UP:
move_x = -3
Should be:
elif event.key == pygame.K_RIGHT:
move_x = 3
elif event.key == pygame.K_UP:
move_y = -3
I'm faced with a logic error where the sprite simply doesn't move regardless of input.
My code will be below so no context is left out, it's fairly short.
Is there a better way of moving the sprite apart from the blit?
I've seen somewhere stuff about updating the sprite or some such, done quite differently to simply blitting it.
import pygame
pygame.init()
import random
import math
screen=pygame.display.set_mode([700,400])
black = ( 0, 0, 0)
white = ( 255, 255, 255)
red = ( 255, 0, 0)
player_x=350
player_y=200
player_x_vel=0
player_y_vel=0
rot_player=pygame.image
pi=math.pi
class Player(pygame.sprite.Sprite):
def __init__(self):
global player
pygame.sprite.Sprite.__init__(self)
self.pos=(350,200)
self.image=pygame.image.load("arrowtest.png").convert()
self.rect=self.image.get_rect()
screen=pygame.display.get_surface()
self.area=screen.get_rect()
self.speed=10
self.state="still"
self.reinit()
def reinit(self):
self.state="still"
self.movepos=[0,0]
def update(self):
newpos=self.rect.move(self.movepos)
if self.area.contains(newpos):
self.rect=newpos
pygame.event.pump()
def moveup(self):
self.movepos[1]-=(self.speed)
self.state="moveup"
def movedown(self):
self.movepos[1]+=(self.speed)
self.state="movedown"
def moveleft(self):
self.movepos[0]-=(self.speed)
self.state="moveleft"
def moveright(self):
self.movepos[0]+=(self.speed)
self.state="moveright"
def moveupright(self):
self.movepos[1]-=(self.speed)
self.movepos[0]+=(self.speed)
def moveupleft(self):
self.movepos[1]-=(self.speed)
self.movepos[0]-=(self.speed)
def movedownright(self):
self.movepos[1]+=(self.speed)
self.movepos[0]+=(self.speed)
def movedownleft(self):
self.movepos[1]+=(self.speed)
self.movepos[0]-=(self.speed)
def angleplayer(self):
mouse_pos=pygame.mouse.get_pos()
dx=mouse_pos[0]-player_x
dy=mouse_pos[1]-player_y
rads=math.atan2(-dy, dx)
rads %= 2*pi
angle = math.degrees(rads)
print angle
rot_player.image=pygame.transform.rotate(player.image, angle-90)
done=False
clock=pygame.time.Clock()
while done==False:
player = Player()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type == pygame.MOUSEBUTTONDOWN:
fired_pos=pygame.mouse.get_pos()
fired=True
if event.type == pygame.KEYDOWN:
player.angleplayer()
if event.key == pygame.K_w:
player.moveup()
if event.key == pygame.K_s:
player.movedown()
if event.key == pygame.K_a:
player.moveleft()
if event.key == pygame.K_d:
player.moveright()
print "co ords", player_x,player_y
print "x vel", player_x_vel
print "y vel", player_y_vel
if event.type == pygame.KEYUP:
player.movepos=[0,0]
player.state="still"
player.angleplayer()
screen.fill(white)
screen.blit(player.image, player.pos)
clock.tick(20)
pygame.display.flip()
pygame.quit()
Thanks in advance
First of all, you are creating a new player every iteration of your main loop:
...
while done == False:
player = Player()
...
You want to create the player once, so move the creation outside the loop:
...
player = Player()
while not done:
...
Second: To get the position of the player, you use player.pos:
...
screen.blit(player.image, player.pos)
...
but you never update player.pos (it's always (350,200)), you only change self.rect:
def update(self):
newpos=self.rect.move(self.movepos)
if self.area.contains(newpos):
self.rect=newpos
pygame.event.pump()
either use player.rect to get the player position, or update player.pos accordingly:
def update(self):
newpos=self.rect.move(self.movepos)
if self.area.contains(newpos):
self.rect = newpos
self.pos = self.rect.topleft
# don't call pygame.event.pump() here. Doesn't make any sense :-)
Third, you update the player position in the update function, but you never call it. Call it before drawing the player:
...
while not done:
...
player.update()
screen.fill(white)
screen.blit(player.image, player.pos)
...
You can simplify your code alot by setting movepos directly and removing the move... functions.
working example:
import pygame
pygame.init()
colors = pygame.color.THECOLORS
screen = pygame.display.set_mode([700,400])
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.surface.Surface((32,32))
self.image.fill(colors['green'])
self.rect = self.image.get_rect().move(350, 200)
self.speed = 4
def update(self):
dx, dy = self.movepos[0] * self.speed, self.movepos[1] * self.speed
self.rect = self.rect.move(dx, dy)
done=False
clock = pygame.time.Clock()
player = Player()
while not done:
if pygame.event.get(pygame.QUIT):
break
pressed = pygame.key.get_pressed()
l, r, u, d = [pressed[k] for k in pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_s]
player.movepos = -l + r, -u + d
player.update()
screen.fill(colors['white'])
screen.blit(player.image, player.rect.topleft)
pygame.display.flip()
clock.tick(60)
You have a lot of move functions. Try combining them into a simple two function class like this example:
class Puck(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
The two main controllers are the self.rect.left and self.rect.top. By changing their values, you can move the sprites like in this example.
#Name of varible# = Puck('#Image File#', [#value of self.rect.left#, value of self.rect.top]
Then you can use events to change them like:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
elif event.type == pygame.KEYDOWN:
if event.key == K_UP:
random.rect.top =random.rect.top - 75
elif event.key == K_LEFT:
random.rect.left = random.rect.left - 75
elif event.key == K_DOWN:
random.rect.top = random.rect.top + 75
elif event.key == K_RIGHT:
randoml.rect.left = randoml.rect.left + 75
elif event.key == K_w:
random.rect.top = random.rect.top - 50
elif event.key == K_a:
random.rect.left = random.rect.left - 50
elif event.key == K_s:
random.rect.top = random.rect.top + 50
elif event.key == K_d:
random.rect.left = random.rect.left + 50
This should be able to move your sprite.