"Hello from the pygame community" - python

When I executed the following code, instead of an error it said "Hello from the pygame community. https://www.pygame.org/contribute.html". It would be easier for me if it just included the error so I could fix it myself without posting the code in stackoverflow (for privacy reasons).
Here's the code:
# import the pygame module, so you can use it
import pygame
# define a main function
def main():
# initialize the pygame module
pygame.init()
# load and set the logo
logo = pygame.image.load("logo32x32.png")
pygame.display.set_icon(logo)
pygame.display.set_caption("minimal program")
# create a surface on screen that has the size of 240 x 180
screen = pygame.display.set_mode((240, 180))
# define a variable to control the main loop
running = True
# main loop
while running:
# event handling, gets all event from the eventqueue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
# draw a green line from (0,0) to (100,100)
pygame.draw.line(screen, (0,255,0), (0,0), (100,100))
# draw a green line from (0,100) to (100,0)
pygame.draw.line(screen, (0,255,0), (0,100), (100,0))
# draw a rectangle outline
pygame.draw.rect(screen, (0,255,0), (60,60,100,50), 1)
# draw a filled in rectangle
pygame.draw.rect(screen, (0,255,0), (60,120,100,50))
# draw a circle
pygame.draw.circle(screen, (0,255,0), (120,60), 20, 0)
# draw a circle outline
pygame.draw.circle(screen, (0,255,0), (120,60), 20, 1)
# draw a polygon
pygame.draw.polygon(screen, (0,255,0), ((140,60),(160,80),(160,100),(140,120),(120,100),(120,80)), 0)
# draw a filled in poly
pygame.draw.polygon(screen, (0,255,0), ((140,60),(160,80),(160,100),(140,120),(120,100),(120,80)), 1)
# draw a text
font = pygame.font.Font(None, 36)
text = font.render("Hello There", 1, (10, 10, 10))
textpos = text.get_rect()
textpos.centerx = screen.get_rect().centerx
screen.blit(text, textpos)
# update the screen
pygame.display.flip()
# quit pygame properly to clean up resources
pygame.quit()
# end of the code

That isn't an error. That line is printed when you import pygame. None of your code is producing an error because none of it is being called. After you define the main function, make sure to call main().

Related

Button's rectangle is in the wrong place [duplicate]

This question already has an answer here:
Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?
(1 answer)
Closed 2 years ago.
I am developing an idle clicker game for a school project. There's a button that you can click on to upgrade your clicking power, but the rectangle assigned to it is in the wrong place. The button's rectangle is not on the button itself. Here is some of the code.
import pygame
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((800, 600))
clickimage = pygame.image.load('block.png')
button = pygame.image.load('button.png')
boxclip = clickimage.get_rect()
buttonclip = button.get_rect()
myfont = pygame.font.SysFont('Comic Sans MS', 50)
coins = 0
cost = 15
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if pygame.mouse.get_pressed()[0] and boxclip.collidepoint(pygame.mouse.get_pos()):
coins = coins+1
if pygame.mouse.get_pressed()[0] and buttonclip.collidepoint(pygame.mouse.get_pos()):
coins = coins-cost
screen.fill((255, 255, 255))
screen.blit(clickimage, (50, 50))
screen.blit(button, (500, 50))
coindisplay = myfont.render(f'Coins: {coins}', False, (0, 0, 0))
costdisplay = myfont.render(f'Cost: {cost}', False, (0, 0, 0))
screen.blit(coindisplay, (50, 310))
screen.blit(costdisplay, (500, 200))
pygame.display.update()
I assigned the button's rectangle to the button but it's for some reason overlapping the clickimage. Why is this happening?
pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. The Surface is placed at a position when it is blit to the display. The position of the rectangle can be specified by a keyword argument. For example, the top ledt of the rectangle can be specified with the keyword argument topleft. These keyword argument are applied to the attributes of the pygame.Rect before it is returned (see pygame.Rect for a full list of the keyword arguments).
You only need to change 2 lines of your code:
clickimage = pygame.image.load('block.png')
button = pygame.image.load('button.png')
boxclip = clickimage.get_rect(topleft = (50, 50)) # <---
buttonclip = button.get_rect(topleft = (500, 50)) # <---
# [...]
running = True
while running:
# [...]
screen.blit(clickimage, boxclip)
screen.blit(button, buttonclip)
# [...]
You are checking to see if the user clicked the block by checking the boxclip rect. You set the boxclip = clickimage.get_rect() before you blit the image to a place on the screen, so how could the rect know what position it is? It's position is likely set at 0, 0.
You can fix this by defining your own rectangle for the block.
boxclip = pygame.Rect(50, 50, clickimage.get_rect().width, clickimage.get_rect().height)
The first 2 arguments are the x and y positions and 50, 50 is where you blited it. Then you can check if the mouse collides with this rectangle. You also need to apply this to your button collisions as well.

Pygame creating surfaces

Code:
#!/usr/bin/python
import pygame, time, sys, random, os
from pygame.locals import *
from time import gmtime, strftime
pygame.init()
w = 640
h = 400
screen = pygame.display.set_mode((w, h),RESIZABLE)
clock = pygame.time.Clock()
x = y = 100
def starting():
basicfont = pygame.font.SysFont(None, 48)
text = basicfont.render('Starting...', True, (255, 255, 255), (0, 0, 255))
textrect = text.get_rect()
textrect.centerx = screen.get_rect().centerx
textrect.centery = screen.get_rect().centery
screen.fill((0, 0, 255))
screen.blit(text, textrect)
def taskbar():
basicfont = pygame.font.SysFont(None, 24)
taskbarrect = pygame.Rect((0, int(h-40)), (int(w), int(h)))
text = basicfont.render(strftime("%Y-%m-%d", gmtime()), True, (0, 0, 0))
text2 = basicfont.render(strftime("%H:%M:%S", gmtime()), True, (0, 0, 0))
taskbarrect.blit(text, (w - 100, h - 37))
taskbarrect.blit(text2, (w - 100, h - 17))
pygame.display.update()
starting()
screen.fill((255,255,255))
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type==VIDEORESIZE:
w = event.dict['size'][0]
h = event.dict['size'][1]
screen=pygame.display.set_mode(event.dict['size'],RESIZABLE)
taskbar()
Because I want to make my code run faster, I want to create surfaces and blit rects on top of them, so that I can do pygame.display.update(taskbarrect) and speed up my code. However, I don't know how to create multiple surfaces. I have tried taskbarrect=(xcoordinate, ycoordinate, width, length) then blitting an image or text or whatever, but trying it says tuple object has no attribute blit. Trying the method in the code (suggested by #elegent) gives 'pygame.Rect' object has no attribute 'blit'.
What am I doing wrong?
Pygame uses surfaces to represent any form of image. This could be either
your main screen Surface, which is returned by the pygame.display.set_mode() function
myDisplay = pygame.display.set_mode((500, 300))
or created object of the pygame.Surface class:
#create a new Surface
myNewSurface = Surface((500, 300))
#change its background color
myNewSurface.fill((55,155,255))
#blit myNewSurface onto the main screen at the position (0, 0)
myDisplay.blit(myNewSurface, (0, 0))
#update the screen to display the changes
display.update() #or display.flip()
Pygame's display.update() has a method that allows one to update only some portions of the screen by passing one object or a list of pygame.Rect objects to it. Therefore, we could also call:
myUpdateRect= pygame.Rect((500, 300), (0, 0))
display.update(myUpdateRect)
Anyway, I recommend to using the pygame.draw module to draw simple shapes like rectangles, circles and polygons onto a surface, because all of these functions return a rectangle representing the bounding area of changed pixels.
This enables you to pass this information to the update() function, so Pygame only updates the pixels of the just drawn shapes:
myDisplay = pygame.display.set_mode((500, 300))
myRect= pygame.Rect((100, 200), (50, 100))
pygame.display.update(pygame.draw.rect(myDisplay, (55, 155, 255), myRect))
Update:
def taskbar():
basicfont = pygame.font.SysFont(None, 24)
text = basicfont.render(strftime("%Y-%m-%d", gmtime()), True, (0, 0, 0))
text2 = basicfont.render(strftime("%H:%M:%S", gmtime()), True, (0, 0, 0))
screen.fill((55, 155, 255))
screen.blit(text, (w - 100, h - 37))
screen.blit(text2, (w - 100, h - 17))
pygame.display.update()
Hope this helps :)

How to display text in pygame? [duplicate]

This question already has answers here:
pygame - How to display text with font & color?
(7 answers)
Closed 2 years ago.
I can't figure out to display text in pygame.
I know I can't use print like in regular Python IDLE but I don't know how.
import pygame, sys
from pygame.locals import *
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = ( 255, 0, 0)
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('P.Earth')
while 1: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.display.update()
import time
direction = ''
print('Welcome to Earth')
pygame.draw.rect(screen, RED, [55,500,10,5], 0)
time.sleep(1)
This is only the beginning part of the whole program.
If there is a format that will allow me to show the text I type in the pygame window that'd be great. So instead of using print I would use something else. But I don't know what that something else is.
When I run my program in pygame it doesn't show anything.
I want the program to run in the pygame window instead of it just running in idle.
You can create a surface with text on it. For this take a look at this short example:
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
my_font = pygame.font.SysFont('Comic Sans MS', 30)
This creates a new object on which you can call the render method.
text_surface = my_font.render('Some Text', False, (0, 0, 0))
This creates a new surface with text already drawn onto it.
At the end you can just blit the text surface onto your main screen.
screen.blit(text_surface, (0,0))
Bear in mind, that every time the text changes, you have to recreate the surface again, to see the new text.
There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.
Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.
You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.
import pygame
import pygame.freetype # Import the freetype module.
pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255,255,255))
# You can use `render` and then blit the text surface ...
text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
screen.blit(text_surface, (40, 250))
# or just `render_to` the target surface.
GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))
pygame.display.flip()
pygame.quit()
When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:
import pygame
def text_to_screen(screen, text, x, y, size = 50,
color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
try:
text = str(text)
font = pygame.font.Font(font_type, size)
text = font.render(text, True, color)
screen.blit(text, (x, y))
except Exception, e:
print 'Font Error, saw it coming'
raise e
Then when that has been imported when I want to display text taht updates E.G score I do:
Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)
If it is just normal text that isn't being updated:
Funk.text_to_screen(screen, 'Text', xpos, ypos)
You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))

How would I get my game over screen stay on the screen

import pygame, random, time
from time import sleep
from pygame import*
pygame.init()
myname=input('What is your name')
#set the window size
window= pygame.display.set_mode((800,600) ,0,24)
pygame.display.set_caption("Fruit Catch")
gameover=pygame.image.load('fifa.jpg')
#game variables
myscore=0
mylives=3
mouth_x=300
fruit_x=250
fruit_y=75
fruitlist=['broccoli.gif','chicken.gif']
#prepare for screen
myfont=pygame.font.SysFont("Britannic Bold", 55)
label1=myfont.render(myname, 1, (240, 0, 0))
label3=myfont.render(str(mylives), 1, (20, 255, 0))
#grapchics
fruit=pygame.image.load('data/chicken.png')
mouth=pygame.image.load('data/v.gif')
backGr=pygame.image.load('data/kfc.jpg')
#endless loop
running=True
while running:
if fruit_y>=460:#check if at bottom, if so prepare new fruit
fruit_x=random.randrange(50,530,1)
fruit_y=75
fruit=pygame.image.load('data/'+fruitlist[random.randrange(0,2,1)])
caught= fruit_x>=mouth_x and fruit_x<=mouth_x+300
else:fruit_y+=5
#check collision
if fruit_y>=456:
mylives-=1
if fruit_y>=440:
if fruit_x>=mouth_x and fruit_x<=mouth_x+300 :
myscore+=1
fruit_y=600#move it off screen
pygame.mixer.music.load('data/eating.wav')
if mylives==0:
window.blit(backg,(0,0))
pygame.time.delay(10)
window.blit(gameover,(0,0))
pygame.display.update()
#detect key events
for event in pygame.event.get():
if (event.type==pygame.KEYDOWN):
if (event.key==pygame.K_LEFT):
mouth_x-=55
if (event.key==pygame.K_RIGHT):
mouth_x+=55
label3=myfont.render(str(mylives), 1, (20, 255, 0))
label2=myfont.render(str(myscore), 1, (20, 255, 0))
window.blit(backGr,(0,0))
window.blit(mouth, (mouth_x,440))
window.blit(fruit,(fruit_x, fruit_y))
window.blit(label1, (174, 537))
window.blit(label2, (700, 157))
window.blit(label3, (700, 400))
pygame.display.update()
When my lives hit 0 the game over screen comes up but it flickers between that and the normal background.
How would I get it to stay on the screen?
I thinks its something to with the updates, but if I take either out it doesn't work
If line is 0 then you run some blits and update twice
First inside if mylives==0: (and it stay for awhile becaus you use delay(10) )
Second time at the end of loop.
Use:
if mylives==0:
#blit and update game over
else:
#blit and update normal game

I wrote a pygame program but when I try to use py2exe I don't get an exe in the dist

I wrote a program called Hello.py that looks like this:
import pygame, sys
from pygame.locals import *
# set up pygame
pygame.init()
# set up the window
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Hello world!')
# set up the colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# set up fonts
basicFont = pygame.font.SysFont(None, 48)
# set up the text
text = basicFont.render('Hello world!', True, WHITE, BLUE)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
# draw the white background onto the surface
windowSurface.fill(WHITE)
# draw a green polygon onto the surface
pygame.draw.polygon(windowSurface, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))
# draw some blue lines onto the surface
pygame.draw.line(windowSurface, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(windowSurface, BLUE, (120, 60), (60, 120))
pygame.draw.line(windowSurface, BLUE, (60, 120), (120, 120), 4)
# draw a blue circle onto the surface
pygame.draw.circle(windowSurface, BLUE, (300, 50), 20, 0)
# draw a red ellipse onto the surface
pygame.draw.ellipse(windowSurface, RED, (300, 250, 40, 80), 1)
# draw the text's background rectangle onto the surface
pygame.draw.rect(windowSurface, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
# get a pixel array of the surface
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
# draw the text onto the surface
windowSurface.blit(text, textRect)
# draw the window onto the screen
pygame.display.update()
# run the game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
And I have a program called setup.py that looks like this:
from distutils.core import setup
import py2exe
import pygame
setup(window=['Hello.py'])
when I run py2exe, it makes a dist folder but inside the folder there is no exe file, just the other files it creates. I hate to keep asking questions like this but I'm a little short for time and don't have time to play 20 error messages with my computer. I am currently running windows vista.
Pygame already has a default program for using pygame and py2exe, Pygame2exe.
Here is a link to it.
Just fill in the arguments in BuildExe.__init__ and run it. You don't even have to run it in console because it adds "py2exe" to the arguments.
Hope this answer helps!

Categories