stevepaget / pygame_functions Goto Github PK
View Code? Open in Web Editor NEWA set of functions that make working with Pygame and Python much easier.
License: GNU General Public License v2.0
A set of functions that make working with Pygame and Python much easier.
License: GNU General Public License v2.0
Is there any difference? Any specific time I should use one vs the other?
I set the background to my image name, setBackgroundImage("stars.png")
, however, I keep getting an error stating "'str' object has no attribute 'blit'". I checked the code out and it seems to me that it should work fine.
def setBackgroundImage(img): global bgSurface, backgroundImage surf = loadImage(img) backgroundImage = surf screen.blit(surf, [0, 0]) bgSurface = screen.copy() updateDisplay()
I just don't know what I am doing wrong. If anyone could help me I would greatly appreciate it.
`#Import librarys
import pygame, math
from pygame_functions import *
pygame.init()
##game setup##
horSize = 1000
vertSize = 750
screen = pygame.display.set_mode((horSize, vertSize))
#screenSize(horSize, vertSize)
rocket = makeSprite("rocket1.png")
pygame.display.set_caption("Rocket Game")
setBackgroundImage(convert.alpha("stars.png"))
showSprite(rocket)`
hi, i love your Functions! teach me so much!
can you add chinese text display and input support? i can't input any chinese.
thanks!
My friend and I wrote a game using the library and had significant fps issues when multiple sprites were on the screen at the same time. I looked through the library and discovered that the display was updated after every sprite change. We moved this function call to the tick() function and noticed a significant boost in performance and fps. It makes it far more efficient to update the display upon every clock tick because the tick rate is then mirrored by the frame rate.
Hi Steve,
Thank you for your code we can use.
Is it possible to change font in the textbox?
i tried changing it the code, but nothing happens, still stays "Arial"
it doesn't look nice when the font in the label is much different than the one in the textbox.
same thing goes for color.
Thanks!
Hi,
first of all, I'd like to thank you for "Pygame Functions" and especially for creating the feature of the scrolling background! I'm using Pygame directly to have more control, but I appreciate, when you put such functions into your module, because I then can extract the code I need from there.
So here's the part I took for the scrolling background (in a working example):
#!/usr/bin/python
# coding: utf-8
import pygame
from pygame.locals import *
import os
class Background():
def __init__(self, screen):
self.screen = screen
self.colour = pygame.Color("black")
self.screen.fill(self.colour)
def setTiles(self, tiles):
if type(tiles) is str:
self.tiles = [[self.loadImage(tiles)]]
elif type(tiles[0]) is str:
self.tiles = []
t = []
for i in tiles:
t.append(self.loadImage(i))
self.tiles.append(t)
else:
self.tiles = []
for i in tiles:
t = []
for row in i:
t.append(self.loadImage(row))
self.tiles.append(t)
self.stagePosX = 0
self.stagePosY = 0
self.tileWidth = self.tiles[0][0].get_width()
self.tileHeight = self.tiles[0][0].get_height()
self.screen.blit(self.tiles[0][0], [0, 0])
def loadImage(self, fileName):
image = pygame.image.load(fileName)
image = image.convert_alpha()
return image
def scroll(self, x, y):
self.stagePosX -= x
self.stagePosY -= y
col = (self.stagePosX % (self.tileWidth * len(self.tiles[0]))) // self.tileWidth
xOff = (0 - self.stagePosX % self.tileWidth)
row = (self.stagePosY % (self.tileHeight * len(self.tiles))) // self.tileHeight
yOff = (0 - self.stagePosY % self.tileHeight)
col2 = ((self.stagePosX + self.tileWidth) % (self.tileWidth * len(self.tiles[0]))) // self.tileWidth
row2 = ((self.stagePosY + self.tileHeight) % (self.tileHeight * len(self.tiles))) // self.tileHeight
self.screen.blit(self.tiles[row][col], [xOff, yOff])
self.screen.blit(self.tiles[row][col2], [xOff + self.tileWidth, yOff])
self.screen.blit(self.tiles[row2][col], [xOff, yOff + self.tileHeight])
self.screen.blit(self.tiles[row2][col2], [xOff + self.tileWidth, yOff + self.tileHeight])
pygame.display.flip()
pygame.init()
pygame.display.set_caption("Scrolling Background")
os.environ['SDL_VIDEO_WINDOW_POS'] = "300, 30"
# The main window's size has to be set according to the sizes of the background's images.
# Otherwise, there will be uncovered screen areas or graphical artifacts.
screen = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
background = Background(screen)
background.setTiles([["images/dungeonFloor1.png", "images/dungeonFloor2.png"],
["images/dungeonFloor3.png", "images/dungeonFloor4.png"]])
while True:
clock.tick(60)
pygame.event.pump()
pressed = pygame.key.get_pressed()
if pressed[K_q]:
pygame.quit()
break
if pressed[K_RIGHT]:
background.scroll(-5, 0)
if pressed[K_DOWN]:
background.scroll(0, -5)
if pressed[K_LEFT]:
background.scroll(5, 0)
if pressed[K_UP]:
background.scroll(0, 5)
pygame.display.flip()
This works well with "clock.tick(120)" like in the official example. But usually I set the frames per second to 50 or 60 frames ("clock.tick(60)") in my Pygame scripts. When I do that here, unfortunately I get some juddering on the screen. Is there a way to fix this, or are 120 FPS required, and the other objects have to be slowed down by hand then?
By the way: I also tried PySFML, and I think, it's better and faster (I could run an example of "Outrun" example in PySFML, but not in Pygame; translated from this amazing C++-example
https://www.youtube.com/watch?v=N60lBZDEwJ8 ).
And PySFML has "scrolling background" routines built-in.
But unfortunately it's quite difficult to install. And it's not very common, not many people use it.
So it's easier sharing Pygame code. (That's why I was looking for "scrolling background" for it.)
Cheers
teapot3
Hi Steve,
I have been using your pygame_functions file to create my first game.
It is a simple space game exactly like your rocket.demo video.
I am working on inputting an introduction screen that utilizes spacebar to start the game and the letter q to exit.
Here is my code so far:
`#Set up introduction screen
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
end()
if event.type == pygame.KEYDOWN:
if keyPressed == "space":
intro = False
if keyPressed == "q":
end()
screenSize(450,300)
setBackgroundImage("intro_background.png")
titleLabel = makeLabel("SPACE RACER!", 45, 70, 0, "green", "Comic Sans MS")
showLabel(titleLabel)
directionLabel = makeLabel("Use the directional keys to guide your spaceship!", 15, 60, 180, "green", "Comic Sans MS")
showLabel(directionLabel)
entryLabel = makeLabel("Press the SPACEBAR to begin or Q to quit.", 15, 80, 200, "green", "Comic Sans MS")
showLabel(entryLabel)
game_intro()`
So far the commands do not work and the screen blips rapidly. I think I am bypassing a predefined function that you may have made in your file, but I am pretty new to all this and am not sure.
The error message reads...
Traceback (most recent call last):
File "C:\Users\Justin Beal\Desktop\Python Files\Space_Racer.py", line 40, in
game_intro()
File "C:\Users\Justin Beal\Desktop\Python Files\Space_Racer.py", line 27, in game_intro
screenSize(450,300)
File "C:\Users\Justin Beal\Desktop\Python Files\pygame_functions.py", line 294, in screenSize
windowInfo = pygame.display.Info()
pygame.error: video system not initialized
Any idea what I am doing wrong?
def is_exit():
ret = False
for event in pygame.event.get():
if (event.type == pygame.KEYDOWN and event.key == keydict["esc"]) or event.type == pygame.QUIT:
ret = True
return ret
def exec_exit():
pygame.quit()
sys.exit()
Hi,
I just found your videos and library and thought they would be ideal for a introductory python class I am currently teaching. I downloaded the most recent pygame_functions and tried to compile but I am getting this error from the library and I am stumped. Any suggestions?
Thanks,
Janet
Traceback (most recent call last):
File "", line 1, in
runfile('/Users/jslocum/Desktop/makinggames/bunny&carrot.py', wdir='/Users/jslocum/Desktop/makinggames')
File "/Users/jslocum/anaconda3/lib/python3.5/site-packages/spyder_kernels/customize/spydercustomize.py", line 668, in runfile
execfile(filename, namespace)
File "/Users/jslocum/anaconda3/lib/python3.5/site-packages/spyder_kernels/customize/spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/jslocum/Desktop/makinggames/bunny&carrot.py", line 25, in
moveSprite(bunny,10,height/2)
File "/Users/jslocum/Desktop/makinggames/pygame_functions.py", line 313, in moveSprite
updateDisplay()
File "/Users/jslocum/Desktop/makinggames/pygame_functions.py", line 674, in updateDisplay
spriteRects = spriteGroup.draw(screen)
File "/Users/jslocum/anaconda3/lib/python3.5/site-packages/pygame/sprite.py", line 568, in draw
surface_blit = surface.blit
AttributeError: 'str' object has no attribute 'blit'
In case its my code
import pygame, sys, random
from pygame.locals import *
from pygame_functions import *
pygame.init()
FPS = 300 # frames per second setting
fpsClock = pygame.time.Clock()
grassImg = pygame.image.load('grass.bmp')
width = grassImg.get_width() #find the width of the image
height = grassImg.get_height() #find the height of the image
DISPLAYSURF = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('Animation')
pygame.time.set_timer ( pygame.USEREVENT , 1000 )
#catImg = pygame.image.load('cat.bmp')
bunny = makeSprite('cat.bmp')
moveSprite(bunny,10,height/2)
showSprite(bunny)
carrot = []
speed =[]
location = []
for i in range(5):
carrot.append(makeSprite(carrot.bmp))
speedx = random.randomint(1,5)
speedy = random.randomint(1,5)
speed.append((speedx,speedy))
location.append((random.randomint(0,1000),random.randomint(0,500)))
moveSprite(carrot[i],location[i][0],location[i][1])
showSprite(carrot[i])
Hi Steve,
I have been using your tutorials and have made some headway with scrolling backgrounds and sprite animations. However, despite my best efforts I cannot seem to implement a jump mechanic. Is there anything in pygame_functions that may help to address this? My project code is below just wanted to see if you had any thoughts on how to implement it. I separated the code I think is relevant to the question below it.
from pygame_functions import *
import random
screenSize(1024, 512)
setBackgroundImage("Prehistoric_background.png")
makeMusic("Dino_dash_theme.mp3")
playMusic(loops=-1)
def game_Loop():
dino = makeSprite("dino1.png")
addSpriteImage(dino, "dino2.png") # Add extra images. They are stored in the Sprite object
addSpriteImage(dino, "dino3.png") # but not displayed yet
addSpriteImage(dino, "dino4.png")
addSpriteImage(dino, "dino9.png")
saur = makeSprite("dino5.png")
addSpriteImage(saur, "dino6.png")
addSpriteImage(saur, "dino7.png")
addSpriteImage(saur, "dino8.png")
#defining variable for jump animation
isJump = False
jumpCount = 10
width = 40
vel = 0.5
x = 50
y = 425
# Starting position of dino
xPos = 400
yPos = 340
moveSprite(dino, xPos, yPos)
showSprite(dino)
# flyer functions with random speed and position
flyer = [] # Creates a list called flyer
for x in range(1):
thisFlyer = makeSprite("flyer2.png")
addSpriteImage(thisFlyer, "flyer4.png")
addSpriteImage(thisFlyer, "flyer5.png")
addSpriteImage(thisFlyer, "flyer6.png")
addSpriteImage(thisFlyer, "flyer7.png")
thisFlyer.x = random.randint(600, 1400)
thisFlyer.y = random.randint(0, 0)
moveSprite(thisFlyer, thisFlyer.x, thisFlyer.y)
thisFlyer.xspeed = random.randint(-1, -1)
thisFlyer.yspeed = random.randint(0, 0)
showSprite(thisFlyer)
flyer.append(thisFlyer) # This adds thisFlyer to the list made at the top
#Key press funtions for dino and frames
nextFrame = clock()
frame = 0
while True:
if clock() > nextFrame: # We only animate our character every 80ms.
frame = (frame + 1) % 4 # There are 4 frames of animation in each direction
nextFrame += 80 # so the modulus 8 allows it to loop
if keyPressed("right") and x < 10000 - width - vel:
x += vel
changeSpriteImage(dino, 0 * 4 + frame) # 0*8 because right animations are the 0th set in the sprite sheet
scrollBackground(-3, 0) # The player is moving right, so we scroll the background left
if keyPressed("left") and x > vel:
x -= vel
hideSprite(dino)
moveSprite(saur, 400, 340)
showSprite(saur)
changeSpriteImage(saur, 0 * 4 + frame)
scrollBackground(3, 0)
else:
hideSprite(saur)
showSprite(dino)
if keyPressed("space"):
changeSpriteImage(dino, 4)
moveSprite(dino, xPos, yPos * vel)
if not (isJump):
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 10
if nextFrame:
changeSpriteImage(thisFlyer, 0 * 5 + frame)
# This moves the flyer by its speed
for thisFlyer in flyer:
thisFlyer.x += thisFlyer.xspeed
if thisFlyer.x > 1024:
thisFlyer.x = 0
elif thisFlyer.x < 0:
thisFlyer.x = 1024
thisFlyer.y += thisFlyer.yspeed
if thisFlyer.y > 0:
thisFlyer.y = 0
elif thisFlyer.y < 0:
thisFlyer.y = 0
moveSprite(thisFlyer, thisFlyer.x, thisFlyer.y)
game_Loop()
endWait()
Here is the code I need to revise:
#defining variable for jump animation
isJump = False
jumpCount = 10
width = 40
vel = 0.5
x = 50
y = 425
if keyPressed("space"):
changeSpriteImage(dino, 4)
moveSprite(dino, xPos, yPos * vel)
if not (isJump):
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 10
Hi i am a brand new user of your library and I was wondering if you could add a new feature to the:
makeSprite(filename, column)
by adding the ability to handle array and not single line image. In other way and this:
makeSprite(filename, line, column)
Thanks in advance
Hi Steve,
Firstly, thank you for this helpful library!
I just started using it, and my aim is to create a game that has a central actor that moves around a dynamic map (the actor stays centered, no translation, no rotation, while the background transforms accordingly).
I have been using the setBackgroundImage functionality and while the translation is simple to emulate using the scrollBackground function, I wonder if is there any "rotateBackground" functionality. If not, do you have any quick suggestions on how I should implement it in the already defined Background class?
I've tried using pygame_function.transformSprite and pygame.transform.rotate but I'm not quite sure on which of the Background's class internals I should apply it on.
Thanks!
Hi Steve,
I've installed Pygame_Functions and I'm experimenting with the code from your Text Outputs and Inputs lesson. It's named text.py
import pygame
from pygame_functions import *
import random
size = [790, 600]
instructionLabel = makeLabel("Please enter a word", 40, 10, 40, ("blue"), "AZgency FB", 'yellow')
showLabel(instructionLabel)
But I get the following error message:
C:\Users\gjano>text.py
Traceback (most recent call last):
File "C:\Users\gjano\text.py", line 13, in
showLabel(instructionLabel)
File "C:\Users\gjano\pygame_functions.py", line 562, in showLabel
updateDisplay()
File "C:\Users\gjano\pygame_functions.py", line 582, in updateDisplay
spriteRects = spriteGroup.draw(screen)
File "C:\Users\gjano\AppData\Roaming\Python\Python36\site-packages\pygame\sprite.py", line 568, in draw
surface_blit = surface.blit
AttributeError: 'str' object has no attribute 'blit'
I thought it would be neat to add fullscreen and an adaptable resolution or atleast resolution settings.
the way i thought it could be done is by changing it ingame like clicking on a setting which changes the screensize value's.
and then make presets
and maybey a way to directly make the labels adapt to it? (but thats not necassary)
just fullscreen and adjustable resolution would be nice
hello I'm a new user of you'r pygame fonction and I have two small problems: first I want to run a sprite on itself, so I use the transphorm sprite method. But there comes the problem the sprite turns around its angle so I went to see in pygame function to see how it works: I have identified that what makes the image rotate is this part: "'tempImage = pygame .transform.rotozoom (tempImage, -angle, scale) "'. and I also know that to rotate the image on itself we can then use "'sprite.rect = sprite.image.get_rect (center = sprite.rect.center)"' so i tried to modify the class but it didn't change anything, then i saw that oldmiddle might be useful but i didn't understand how to use it. That was the first problem. Now the second which is linked with the first: my character can move with the keys up, down, left, right and when I do a rotate sprite of 90 ° it does the rotation (not centered) but when I then want it rotate 90 ° again so that it is in front of its initial position the program does not take into account the first rotation performed and returns to the initial position for then the program execute a 180 ° rotation
here is if you need part of my code or something else tell me Thank you for your answers (and sorry for my bad english I'm french)
Hi, I'm using your pygamge_function with my High School Computer Science students in Chile, and I want to share with you this idea... I take your keyPressed function and add a simple modification to add multiple keys detecting (for jumping with direction for example, or move in diagonal):
def keysPressed(keyCheck):
global keydict
pygame.event.clear()
keys = pygame.key.get_pressed()
pressedKeys = 0
if sum(keys) > 0:
for key in keyCheck:
if key == "" or keys[keydict[key.lower()]]:
pressedKeys += 1
if pressedKeys == len(keyCheck):
return True
return False
When we use this, in the game loop, we must check the multiple keys pressed actions first, before of the single keystroke in the "if" that controls the movement.
I have installed a new font
https://www.dafont.com/it/spacebar.font
But it is not recognized by label.
`def print_text(text: str):
test_label = makeLabel(text, 40, 400, 300, fontColour="red", font="SPACEBAR")
moveLabel(test_label,
test_label.rect.topleft[0] - test_label.rect.width/2,
test_label.rect.topleft[1] - test_label.rect.height/2)
showLabel(test_label)`
Do you know where I am wrong?
If sprites are called in a function to start, they don't work with the touching function.
When running the python code for my PyGame window and trying to make a sprite it says something along the lines of
File "C:\Users\User\AppData\Roaming\Python\Python39\site-packages\pygame\sprite.py", line 648, in draw
surface_blit = surface.blit
AttributeError: 'str' object has no attribute 'blit'
This problem resides in the code provided by this functions download and not my code as you can see it finds the issue with a different file to my save file location. Does anyone know what is happening?
Traceback (most recent call last):
File "C:/Users/Bhavik Mangla/Desktop/PycharmProjects/speedtest/main.py", line 24, in
showTextBox(wordBox)
File "C:\Users\Bhavik Mangla\Desktop\PycharmProjects\pygame_functions.py", line 663, in showTextBox
updateDisplay()
File "C:\Users\Bhavik Mangla\Desktop\PycharmProjects\pygame_functions.py", line 674, in updateDisplay
spriteRects = spriteGroup.draw(screen)
File "C:\Users\Bhavik Mangla\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sprite.py", line 569, in draw
surface_blit = surface.blit
AttributeError: 'str' object has no attribute 'blit'
test_label = makeLabel("non funziona", 18, 50, 50)
showLabel(test_label)
It gives me this error
File "C:\Users\ActionICT\PycharmProjects\Asteroids\space_rocks\utils.py", line 54, in print_text
showLabel(test_label)
File "C:\Users\ActionICT\PycharmProjects\Asteroids\venv\lib\site-packages\pygame_functions\__init__.py", line 657, in showLabel
updateDisplay()
File "C:\Users\ActionICT\PycharmProjects\Asteroids\venv\lib\site-packages\pygame_functions\__init__.py", line 680, in updateDisplay
spriteRects = spriteGroup.draw(screen)
File "C:\Users\ActionICT\PycharmProjects\Asteroids\venv\lib\site-packages\pygame\sprite.py", line 648, in draw
surface_blit = surface.blit
AttributeError: 'str' object has no attribute 'blit'
I have written a code for a game in pygame_functions and an issue is showing up
pygame.error video system not initialized and therefore the any keyboard or mouse command is not working.
Hi Steve,
I ran into an issue when trying to implement a time based (in this case every 3 seconds I would like the score in the label box to increase by 10). I have shown both labels for the score and the box where I want the data to auto-update. I am wondering how I can take a label and allow it to update every 3 seconds using some sort of recursion function, but i'm not sure if this existing code is even viable.
Could you let me know your thoughts?
scoreTitle = makeLabel("SCORE ", 45, 830, 20, "white", "Comic Sans MS")
showLabel(scoreTitle)
scoreBox = makeLabel("0", 45, 1010, 20, "white", "Comic Sans MS")
showLabel(scoreBox)
if tick(3000):
changeLabel(scoreBox + str(int(10)))
from pygame_functions import *
import time
screenSize(1280,900)
setBackgroundImage("stars.png")
hydro = makeSprite("elementletter/H1.png")
addSpriteImage(hydro,"elementletter/H2.png")
addSpriteImage(hydro,"elementletter/H3.png")
moveSprite(hydro, 50, 300)
showSprite(hydro)
changeSpriteImage(hydro,1)
time.sleep(0.5)
changeSpriteImage(hydro,0)
time.sleep(0.5)
changeSpriteImage(hydro,2)
time.sleep(0.5)
changeSpriteImage(hydro,0)
time.sleep(0.5)
killSprite(hydro)
--I need to kill the sprite after the changing it..
When I run the py files in takes about 10-20 seconds before they open. Has anyone else seen this issue? It only happens with the py files in this project. Thank you.
changeSpriteImage() call resets scale of sprite to a default value. #10 is my fix
Sorry, new to Github. Couldn't find an appropriate way to communicate this. Just wanted to your thoughts on the code I added to my copy of pygame_functions.py
Added this to endWait() in the while loop, but after the if statement. Had to add sys.exit() otherwise it generated an error.
Is this the appropriate way to implement this?
for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
Anyways, just wanted to add my 2 cents. Again, sorry for posting here.
Hi, i am trying to create an AI that is using the textbox. She's just returning number
i am using those instructions:
event=[ ]
u=[u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9']
for i in range(10):
event+=[pygame.event.Event(pygame.KEYDOWN,key=pygame.K_i, mod=0 , unicode=u[i])
def ask_auto(question,reponse):
liste_reponse=list(reponse)
taille=len(liste_reponse)
for i in range(taille):
wordBox = pg.makeTextBox(300, 10, 300, 0, question, 15, 20)
pg.showTextBox(wordBox)
entry = pg.textBoxInput(wordBox)
evenement=event[int(liste_reponse[i])]
pygame.event.post(evenement)
evenement=pygame.event.Event(pygame.KEYDOWN,key=pygame.K_RETURN, mod=0 , unicode=u'')
pygame.event.post(evenement)
wordBox = pg.makeTextBox(300, 10, 300, 0, "", 15, 20)
pg.showTextBox(wordBox)
but it's not working...
Do you have an idea of what went wrong? i think it's about my pygame.event.Event() and the way you are saving the keyboard entry but i don't know what to change...
(i am french so reponse = answer and evenement = event in French)
(and sorry for my bad english)
I was gonna do a pull request but it seems that you disabled it.
This would implement the flip function
def transformFlip(sprite, horizontal=True, vertical=False): sprite.image = pygame.transform.flip(sprite.image, horizontal, vertical) updateDisplay()
There is only one problem is that when fliped it wants to change back to the non fliped image like so
if keyPressed("a"): transformFlip(Sprite, True, False)
This code works fine in isolation:
from pygame_functions import *
screenSize(500, 500)
setBackgroundColour("red")
#instructionLabel = makeLabel("Please enter a word", 40, 10, 40, ("blue"), "AZgency FB", 'yellow')
#showLabel(instructionLabel)
wordBox1 = makeTextBox(10, 80, 300, 0, "Enter distance to ball:", 0, 24)
showTextBox(wordBox1)
entry1 = textBoxInput(wordBox1)
wordlabel = makeLabel(entry1, 30, 10, 120, "black")
showLabel(wordlabel)
hyp = int(entry1)
hideTextBox(wordBox1)
wordBox2 = makeTextBox(10, 80, 300, 0, "Enter number of degrees:", 0, 24)
showTextBox(wordBox2)
entry2 = textBoxInput(wordBox2)
wordlabel2 = makeLabel(entry2, 30, 10, 150, "black")
showLabel(wordlabel2)
deg = int(entry2)
hideTextBox(wordBox2)
endWait()
But I get the following error messages when integrated into my existing program:
Traceback (most recent call last):
File "C:\Users\gjano\learnEXP1.py", line 483, in
measure()
File "C:\Users\gjano\learnEXP1.py", line 226, in measure
showTextBox(wordBox1)
File "C:\Users\gjano\pygame_functions.py", line 572, in showTextBox
updateDisplay()
File "C:\Users\gjano\pygame_functions.py", line 582, in updateDisplay
spriteRects = spriteGroup.draw(screen)
File "C:\Users\gjano\AppData\Roaming\Python\Python36\site-packages\pygame\sprite.py", line 568, in draw
surface_blit = surface.blit
AttributeError: 'str' object has no attribute 'blit'
I was exploring one of your demos and I see that something very particular happens to me ... I am using visual studio, if I run the code from the ide "run" button, it runs without problems, however when I try to run it using the shortcut of the keyboard throws me an image loading error :
"PS D:\Eze\proyectos python> & 'C:\Python\Python 310\python.exe' 'c:\Users\Ezequiel.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy\launcher' '60936' '--' 'c:\Users\Ezequiel\Desktop\Pygame_Functions-master\demos\animationDemo2.py'
pygame 2.0.2 (SDL 2.0.16, Python 3.10.0)"
I suppose that the compilation process must differ somewhat between running it with the keyboard shortcut and running it by clicking on the "run" button, so in one it throws an error and in the other it runs without problem ...
does that have any fix?
I'm leaving c++ using SFML and although there is a SFML version for Python, it is old and outdated.
But I have not found a fundamental feature in pygame which is the possibility of scrolling the image in the view of a camera, as does the View function of SFML.
There are a few varied solutions out there, but I think if you developed something similar and standardized, it would be very useful.
Could you please make it so pygame_functions allows you to change the Title (Caption) and Image (Icon) of the window.
I'm using this module (and I'm so thankful) but I found my deathpoint, when I want to make parallax scrolling in my background i just can't. (I'm new in programming and I would like some help please).
Thank you again.
Although I'm not familiar with pygame's shapes functionality, I saw a whole platformer built only with rects. I am trying to build a raycaster but I can't move the lines. It would be amazing if you made shapes moveable or made them updateable.
Thank you
from pygame_functions import *
def main():
# setup window
screenSize(1024, 768)
setBackgroundColour('dark blue')
# load player sprite
x = 500
y = 500
jonas = makeSprite('guyspritesheet32.gif', 48)
showSprite(jonas)
moveSprite(jonas, x, y, True)
nextFrame = clock()
frame = 0
# main loop
while True:
# player movement
if clock() > nextFrame:
frame = (frame+1) % 6
nextFrame += 80
if keyPressed('s'):
changeSpriteImage(jonas, 0 * 6 + frame)
elif keyPressed('s') and keyPressed('a'):
changeSpriteImage(jonas, 1 * 6 + frame)
elif keyPressed('a'):
changeSpriteImage(jonas, 2 * 6 + frame)
elif keyPressed('a') and keyPressed('w'):
changeSpriteImage(jonas, 3 * 6 + frame)
elif keyPressed('w'):
changeSpriteImage(jonas, 4 * 6 + frame)
elif keyPressed('w') and keyPressed('d'):
changeSpriteImage(jonas, 5 * 6 + frame)
elif keyPressed('d'):
changeSpriteImage(jonas, 6 * 6 + frame)
elif keyPressed('d') and keyPressed('s'):
changeSpriteImage(jonas, 7 * 6 + frame)
else:
changeSpriteImage(jonas, 0)
tick(60)
endWait()
if name == 'main':
main()
CMaps (short for collision maps) are files that contain info about what collision is where. You can access a specific position using a function and it can return what kind of collision is there. I already made a converter and handler for them by the way.
The advantage of using CMaps instead of itterating through every tile and testing if you overlap with them is that it's way more efficient.
Here you can see a documentation about CMaps in a library that is written in and made for C/C++ (my own handler and converter are made in and made for use with python): https://docs.google.com/document/d/1v7F8-fR8fXS6QZhQZPVwDxD1IccbRJx8oDDK5hJLlFs/edit?usp=sharing. It works almost exactly the same as my own Python implementation. The only differences are:
The input file for my converter can be a bunch of different filetypes
There is no need for the 8x8px grid layout in the input file
You can choose a factor by which the CMap will be scaled in the code
I attached an example code that shows how the CMaps are used, the converter (usage: ">convertCMap.py <filename of the CMap>"), the handler and an example CMap template.
I is possible I could contact you?
My program has no errors. However, the code I wrote doesn't project in the Graphics Window meaning there's only grey screen. (I am on a MacBook Air 2017). TY for any help.
I'm using pygame 2 and python 3.9.1 and I can't run some of the demos (like scrolling), maybe it needs to be updated?
Hi Steve,
I made a simple quiz project, with multiple given answers to chose from. However, I would like to experiment with text input option, and i found your lesson on youtube (pygame_functions: Text Outputs and Inputs). It works perfectly on it's own, but i have problem implementing it in my own code. I'm a novice and I teach myself using online resources, so my code is probably "ugly", but it works :)
I went through some previous question on this topic, and I think the problem is in gameDisplay.fill line, but I'm not sure how to fix it.
Here is the shortened code:
def question_1():
q1 = True
while q1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
question_message("question number 1: ", blue, -160, size="med")
question_message("what color is the sky?", blue, -20, size="med")
wordbox = makeTextBox(10, 80, 300, 0, "enter your answer", 10, 40)
showTextBox(wordbox)
entry = textBoxInput(wordbox)
score(points)
pygame.display.update()
and the error is:
File "test.py", line 157, in question_1
showTextBox(wordbox)
File "pygame_functions.py", line 663, in showTextBox
updateDisplay()
File "pygame_functions.py", line 674, in updateDisplay
spriteRects = spriteGroup.draw(screen)
File "PycharmProjects\pop_quiz\venv\lib\site-packages\pygame\sprite.py", line 568, in draw
surface_blit = surface.blit
AttributeError: 'str' object has no attribute 'blit'
Thank you so much for your lessons on youtube!
Unlike what was shown in the video https://www.youtube.com/watch?v=G933SOLWbbg&list=PLeOSHd3t9lzKr4O3A3Q7OZyf8QwyCALyn&index=4, case 1 or 2 does not currently change anything.
`from pygame_functions import*
import pygame
from pygame.locals import*
pygame.init()
screen=pygame.display.set_mode ((1200,675),RESIZABLE)
#infiniteloop
def game_intro ():
pygame.init()
intro= True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
menu= pygame.image.load("menu.JPG").convert()
screen.blit(menu, (0,0))
wordBox = makeTextBox(10,80,300, "Enter text here", 0, 24)
showTextBox(wordBox)
entry = textBoxInput(wordbox)
pygame.display.flip()
pygame.time.delay(2000)
game_intro()
intro()
`
Hi I wanted to change the title and icon of my game but I can't find the options for it in pygame_functions. Is there any way to change it now?
Hi, I'm using pygame_functions to create a rogue-like game, and I have tried to display some sprites over others, but using the following form doesn't work:
class Player(pg.sprite.Sprite):
def __init__(self):
self._layer = 1 # set layer 1
self.groups = game.all_sprites # add player to the all_sprites LayeredUpdates group
pg.sprite.Sprite.__init__(self, self.groups)
I have done the same for the other sprites, but it doesn't work, it still displays some sprites of the same group over and under the player one randomly
Hi, new adopter to pygame_functions
I have a problem with my custom hitbox, mainly with location.
So I have a sprite with a green background (don't know how to make that color transparent, but that's eside the point), I found out that I can't use the touching function (also besides the point), so I decided to draw some rects instead for the hit boxes but I have a problem with one of the rects, no matter how many pixels I add to the x coordinate, it just doesn't move. Here's my code:
Note: I changed the name of the pygame_functions to pygfunc so it would be less likely for me to misspell.
Note 2: I also slightly modified pygame_functions a little, mainly adding support for left alt, capslock and function keys 1-12, also changed endWait() a little, moved clock() so the new endWait would work, nothing about any of the other functions or variables so it wouldn't have been from modding the file... I think?
Note 3: I also only have one sprite sheet at the moment.
[code]
from pygfunc import *
screen size(600,600)
screenRefresh = False
cara = {"sprite": makeSprite("images/cara.png", 4), "width": 19, "height": 27, "hitbox": {}}
setBackGround color((0,0,139,255))
make music("music/testing.mid")
play music(0)
carb = {'sprite': makeSprite("images/cara.png", 4), "height": 27, "width": 19, "hitbox": {}}
cara['x'] = 300
cara['y'] = 300
carb['x'] = 50
carb['y'] = 50
while True:
cara['xa'] = cara['x']+2
cara['ya'] = cara['y']+1
cara['xb'] = cara['xa']+cara['width']
cara['yb'] = cara['ya']+cara['height']
carb['xa'] = carb['x']+2
carb['ya'] = carb['y']+1
carb['xb'] = carb['xa']+carb['width']
carb['yb'] = carb['ya']+carb['height']
moveSprite(carb['sprite'], carb['x'], carb['y'], False)
if keyPressed("right"):
changeSpriteImage(cara["sprite"], 1)
if keyPressed("left"):
changeSpriteImage(cara["sprite"], 2)
if keyPressed("up"):
changeSpriteImage(cara["sprite"], 3)
if keyPressed("down"):
changeSpriteImage(cara["sprite"], 0)
if keyPressed("w"):
cara['y'] -= 1
if keyPressed("a"):
cara['x'] -= 1
if keyPressed("s"):
cara['y'] += 1
if keyPressed("d"):
cara['x'] += 1
showSprite(cara['sprite'])
showSprite(carb['sprite'])
drawRect(cara['xa'], cara['ya'], cara['width'], cara['height'], (255,0,0,128))
drawRect(carb['x']+1, carb['y']+1, carb['width'], carb['height'], (255,0,255,128))
tick(30)
stopMusic()
pause(250)
end()
[/code]
I don't know what went wrong. will you please tell me what I did wrong?
Hi Steve,
you have a typo in pygame_functions:
Line 577 is just exit()
-> should be sys.exit()
T.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.