This question already has answers here:
Invalid destination position for blit error, not seeing how
(1 answer)
How to draw images and sprites in pygame?
(4 answers)
Closed last month.
import pygame
class popUpWindow:
#Initialization of Window
def __init__(self,capNa,width,height):
self.screen = pygame.init()
self.capNa = capNa
self.width = width
self.height = height
self.screen = pygame.display.set_mode((self.width,self.height))
pygame.display.set_caption(self.capNa)
#Make Player
self.px = float
self.py = float
self.psrc = 'Images/player.png'
self.player_load = pygame.image.load(self.psrc)
def LoadPlayer(self):
self.screen.blit(self.player_load, (self.px,self.py))
pygame.display.update()
def runWindow(self):
self.__init__(self.capNa,self.width,self.height)
self.Is_running = True
self.player_load()
while self.Is_running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
pygame.display.update()
def closeWindow(self):
pygame.quit()
I tried to make the code change the player position but I failed!
How can I change the player positions at any time, without returning back to the code.
Related
This question already has answers here:
Pygame level/menu states
(2 answers)
Closed 18 days ago.
this code when run changes the screen but changes to the original one when i release my mouse why does this happen?when i comment out the screen.blit(bg,(0,0))and when i click it it works and changes to the other screen normally here is the code to show the problem:
import pygame
import os
game = False
pygame.init()
screen = pygame.display.set_mode((3840, 2160))
running = True
os.chdir(r"C:\Users\tomarj\OneDrive - Tata Advanced Systems Limited\Desktop\War Crime")
pygame.display.set_caption("GermanBall")
bg = pygame.image.load("Tan.jpg")
icon = pygame.image.load("box.png")
button1 = pygame.image.load("shirt.png").convert_alpha()
bg_new = pygame.image.load("big.jpg")
pygame.display.set_icon(icon)
class Button():
def __init__(self, x, y, image, scale):
width = image.get_width()
height = image.get_height()
self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
def draw(self):
screen.blit(self.image, (self.rect.x, self.rect.y))
stat = Button(1550, 700, button1, 0.5)
while running:
pos = pygame.mouse.get_pos()
if stat.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1:
game = True
if game:
new_screen = pygame.display.set_mode((3840, 2160))
new_screen.blit(bg_new, (0, 0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
screen.blit(bg, (0, 0))
stat.draw()
pygame.display.update()
pygame.quit()
At every frame (iteration of the while loop (while running)) The screen is being painted over (blit) with bg. You are also checking if the mouse is pressed and if so, you are 'blitting' bg_new. However this blit gets overridden by the blit at the end of the loop hence why after you release, the screen goes back to bg.
This question already has answers here:
How to move the player across a one background image?
(1 answer)
How to scroll the background surface in PyGame?
(1 answer)
Closed 1 year ago.
What I want to do is make the background move when my player moves forward, as the background contains a story-line of sorts. Instead the background is just moving on it's own and cannot be stopped.
Here is all the relevant code:
paccpos=(0,0)
bgX=0
pX, pY = paccpos
while 1:
events = pygame.event.get()
for e in events:
if e.type == QUIT:
exit()
if e.type == KEYDOWN and e.key == K_ESCAPE:
exit()
if pX+1:
bgX -= 1.4
screen.blit(bg_img, (bgX, 0))
entities.update(dt, events)
entities.draw(screen)
pygame.display.update()
dt = timer.tick(60)
class Player(Entity):
def __init__(self, platforms, pos, *groups):
super().__init__((color),(pygame.image.load("lemon3.png")), pos)
self.vel = pygame.Vector2((0, 0))
self.onGround = False
self.platforms = platforms
self.speed = 8
self.jump_strength = 6
self.pos=pos
def globpos(self):
global paccpos
paccpos=self.pos
def update(self, dt, events):
pressed = pygame.key.get_pressed()
up = pressed[K_UP]
left = pressed[K_LEFT]
right = pressed[K_RIGHT]
running = pressed[K_SPACE]
This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
How can you rotate an image around an off center pivot in Pygame
(1 answer)
How to rotate an image(player) to the mouse direction?
(2 answers)
Closed 2 years ago.
I'm trying to rotate an image using pygame. Here is my code thus far:
def main(self):
self.size = width, height = 500, 500
self.black = 0,0,0
self.screen = pygame.display.set_mode(self.size)
self.ball = pygame.image.load("deathstar.png")
self.ballrect = self.ball.get_rect()
self.ballcenter = self.ballrect.center
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEMOTION:
print ("mouse at ", event.pos)
self.rotate_image(some angle)
self.screen.fill(self.black)
self.screen.blit(self.ball, self.ballrect)
pygame.display.flip()
def rotate_image(self, angle):
How would I define rotate_image? I need it to rotate based on where the mouse is placed on the screen. Thanks!
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Why is nothing drawn in PyGame at all?
(2 answers)
Closed 2 years ago.
import pygame as pg
import sys
pg.init()
buttonFont = pg.font.SysFont("garamond", 25)
screenGray = pg.Color('gray80')
buttonGray2 = pg.Color('gray50')
textColour = pg.Color('navy')
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
class Button(pg.sprite.Sprite):
def __init__(self, text, x, y, width, height, colour):
super().__init__()
self.image = pg.Surface((width, height))
self.image.fill(colour)
self.rect = self.image.get_rect()
txt = buttonFont.render(text, True, textColour)
txtRect = txt.get_rect(center = self.rect.center)
self.image.blit(txt, txtRect)
self.rect.topleft = x, y
def isPressed(self, event):
if event.type == pg.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
return True
return False
def FrontPage():
screen.fill(screenGray)
Continue = Button('Continue', 105, 455, 120, 50, buttonGray2)
buttonsGroup1 = pg.sprite.Group(Continue)
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
elif Continue.isPressed(event):
Menu()
buttonsGroup1.draw(screen)
pg.display.flip()
clock.tick(60)
def Menu():
screen.fill(screenGray)
Scytale = Button('Scytale', 105,105,140,65, buttonGray2)
Caesar = Button('Caesar', 330,105,140,65, buttonGray2)
Vigenere = Button('Vigenere', 555,105,140,65, buttonGray2)
Enigma = Button('Enigma', 105,430,140,65,buttonGray2)
PublicKey = Button('Public Key', 330,430,140,65, buttonGray2)
Rijndael = Button('Rijndael', 555,430,140,65, buttonGray2)
buttonsGroup2 = pg.sprite.Group(Scytale,Caesar,Vigenere,Enigma,PublicKey,Rijndael)
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
buttonsGroup2.draw(screen)
clock.tick(60)
FrontPage()
Above is the stripped back code of my FrontPage, that has a button on it that, when clicked, should take the user to the menu screen where 6 more buttons are displayed to move onto the users chosen encryption method.
However, when I press the Continue button, nothing happens.
Is it because there is something wrong with the Button Class?
Or is there something else that makes the button stop working?
Thanks in advance
You have to call pg.display.flip() in the Menu function.
I also have a little recommendation about the code structure. I'd use another function or class (main in this case) to manage the different scenes. So I first assign the current scene function to a variable and call it in the main while loop. When the scene is done, I return the next scene and assign it to the scene variable to swap the scenes. That will avoid potential recursion errors which you get if you just call the next function directly from within another scene (although it's unlikely that you'll exceed the recursion limit of 1000 in a simple game or app).
import pygame as pg
pg.init()
screen = pg.display.set_mode((600, 400))
clock = pg.time.Clock()
BLUE = pg.Color('dodgerblue3')
ORANGE = pg.Color('sienna3')
def front_page():
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return None
# Press a key to return the next scene.
elif event.type == pg.KEYDOWN:
return menu
screen.fill(BLUE)
pg.display.flip()
clock.tick(60)
def menu():
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return None
# Press a key to return the next scene.
elif event.type == pg.KEYDOWN:
return front_page
screen.fill(ORANGE)
pg.display.flip()
clock.tick(60)
def main():
scene = front_page # Set the current scene.
while scene is not None:
# Execute the current scene function. When it's done
# it returns either the next scene or None which we
# assign to the scene variable.
scene = scene()
main()
pg.quit()
This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
How to get keyboard input in pygame?
(11 answers)
How to get if a key is pressed pygame [duplicate]
(1 answer)
How to hold a 'key down' in Pygame?
(1 answer)
Closed 2 years ago.
Hey guys I'm trying to add movement to a sprite I have and I'm having some trouble, heres the code. I'm using the WASD keys to move the player around the place, I just can't seem to figure out why it won't move. Any help is appreciated.
import pygame
import math
from sys import exit
from pygame.locals import *
pygame.mixer.init
class Player(pygame.sprite.Sprite):
def __init__(self, screen):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("ryu.png")
transColor = self.image.get_at((1, 1))
self.image.set_colorkey(transColor)
self.rect = self.image.get_rect()
self.dx = screen.get_width()/2
self.dy = screen.get_height()/2
self.rect.center = (self.dx, self.dy)
self.screen = screen
self.speed = 4
def update(self):
self.rect.center = (self.dx, self.dy)
def returnPosition(self):
return self.rect.center
def MoveLeft(self):
if self.rect.left < 0:
self.dx+=0
else:
self.dx-=self.speed
def MoveRight(self):
if self.rect.right >self.screen.get_width():
self.dx+=0
else:
self.dx+=self.speed
def MoveUp(self):
if self.rect.top <0:
self.dy+=0
else:
self.dy-=self.speed
def MoveDown(self):
if self.rect.bottom > self.screen.get_height():
self.dy+=0
else:
self.dy+=self.speed
def checkKeys(myData):
(event, player) = myData
keys = pygame.key.get_pressed()
if keys [K_a]:
print 'He turned left!!!'
player.MoveLeft()
if keys [K_s]:
print "He's going down!!!"
if keys [K_d]:
print "He turned right!!!"
if keys [K_w]:
print "He's going up!!!"
def main():
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
keepGoing = True
pygame.display.set_caption("Creating a sprite")
player = Player(screen)
background = pygame.Surface(screen.get_size())
background.fill((0, 0, 0))
allSprites = pygame.sprite.Group(player)
while keepGoing:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
allSprites.clear(screen, background)
allSprites.update()
allSprites.draw(screen)
pygame.display.flip()
if __name__ == "__main__":
main()