Display not appearing - python

this is one of my first pygame scripts and its a template idea for a loading screen. Just want something basic that opens when run and closes when a key is pressed. I'm not getting any error messages when run and the display does not pop up. How would I get this script to open up that display and wait for that key press?
import pygame, sys
from pygame.locals import *
# Create the Constants
FPSCLOCK = 30
WINDOWWIDTH = 640
WINDOWHEIGHT = 480 # this is my laptops resolution
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BGCOLOR = BLACK
def main(): # includes the entire game process
global FPSCLOCK, DISPLAYSURF, BASICFONT # Use Global Constants Here
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.SysFont('amethystoriginal', 16)
pygame.display.set_caption('Find your stuff!')
while True:
showLoadingScreen()
def showLoadingScreen():
loadingFont = pygame.font.SysFont('amethystoriginal', 100)
loadingSurf1 = loadingFont.render('Find your stuff!', True, WHITE)
while True:
DISPLAYSURF.fill(BGCOLOR)
loadingRect1 = loadingSurf1.get_rect()
loadingRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
DISPLAYSURF.blit(loadingSurf1, loadingRect1)
drawPressKeyMsg()
if checkForKeyPress():
pygame.event.get()
return
pygame.display.update()
FPSCLOCK.tick(FPS)
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render('Press a key to search.', True, DARKGRAY)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
def checkForKeyPress():
if len(pygame.event.get(QUIT)) > 0:
terminate()
keyUpEvents = pygame.event.get(KEYUP)
if len(keyUpEvents) == 0:
return None
if keyUpEvents[0].key == K_ESCAPE:
terminate()
return keyUpEvents[0].key
def terminate():
pygame.quit()
sys.exit()

The declaration of DARKGRAY and FPS as a call to main() seems to be missing in this code. Other than that, the application works fine for me.

Related

Why is only one specific image registering and not others in pygame?

I am new to coding games using pygame so I thought of making a cookie clicker type of game for my first project. My problem is that I can press the cookie and it gives me cookies when pressed but I cannot press the BUY picture that I have on screen. It's like it doesn't register the click. Please help me I have searched for 2 hours I can'αΊ— find a solution anywhere.
Here's my code:
# import the pygame module
import pygame
pygame.init()
# Define a function for what will happen if the player buys an item (not done)
def shop():
if buy_image.get_rect().collidepoint(pos):
times_clicked -= 15
# Start with no clicks
times_clicked = 0
background_colour = ("white")
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("Cookies")
screen.fill(background_colour)
# create a font object.
# 1st parameter is the font file
# which is present in pygame.
# 2nd parameter is size of the font
font = pygame.font.SysFont("arial",32, True)
fullscreen = False
# Variable to keep our game loop running
running = True
clock = pygame.time.Clock()
# game loop
while running:
# Amount of cookies here
text = font.render(f"Cookies: {times_clicked}", True, "orange")
# create a rectangular object for the
# text surface object
textRect = text.get_rect()
# set the center of the rectangular object.
textRect.center = (880, 100)
# Shop pic
shop_text = pygame.image.load("shop.png")
shop_text = pygame.transform.scale(shop_text, (400, 100))
# Cursor (shop)
cursor_image = pygame.image.load("cursor.png")
cursor_image = pygame.transform.scale(cursor_image, (100, 100))
# Cookie pic
image = pygame.image.load("cookie.jpeg")
image = pygame.transform.scale(image, (800, 800))
# "BUY" pic that doesn't work
buy_image = pygame.image.load("buy.jpeg")
buy_image = pygame.transform.scale(buy_image, (100, 80))
for event in pygame.event.get():
screen.fill(background_colour)
screen.blit(image, (100, 60))
screen.blit(text, textRect)
screen.blit(shop_text, (1250, 20))
screen.blit(cursor_image, (1550, 120))
screen.blit(buy_image, (1400, 130))
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the pos postions of the mouse click
pos = pygame.mouse.get_pos()
# Check if cookie picture is pressed
if image.get_rect().collidepoint(pos):
times_clicked += 1
# Check if BUY picture is pressed
shop()
# Check for QUIT event
if event.type == pygame.QUIT:
running = False
# Update the display using flip
pygame.display.flip()
clock.tick(60)
image.get_rect() gives Rect() but only with size of image - it always gives (0,0) as its position.
You should get it only once (before loop) and assign to variable ie. image_rect and assign position to this object
image_rect = image.get_rect()
image_rect.x = 100
image_rect.y = 60
And later use it to check collision
if image_rect.collidepoint(event.pos):
And you can use it also to display image.
blit(image, image_rect)
EDIT:
I didn't run it because I don't have images but it could be something like this:
import pygame
# --- classes ---
# empty
# --- functions ---
def shop(pos, times_clicked):
if buy_image_rect.collidepoint(pos):
times_clicked -= 15
return times_clicked
# --- main ---
times_clicked = 0
background_colour = "white"
fullscreen = False
# - start -
pygame.init()
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("Cookies")
# - objects -
shop_text = pygame.image.load("shop.png")
shop_text = pygame.transform.scale(shop_text, (400, 100))
shop_text_rect = shop_text.get_rect()
shop_text_rect.x = 1250
shop_text_rect.y = 20
cursor_image = pygame.image.load("cursor.png")
cursor_image = pygame.transform.scale(cursor_image, (100, 100))
cursor_image_rect = cursor_image.get_rect()
cursor_image_rect.x = 1550
cursor_image_rect.y = 120
image = pygame.image.load("cookie.jpeg")
image = pygame.transform.scale(image, (800, 800))
image_rect = image.get_rect()
image_rect.x = 100
image_rect.y = 60
buy_image = pygame.image.load("buy.jpeg")
buy_image = pygame.transform.scale(buy_image, (100, 80))
buy_image_rect = buy_image.get_rect()
buy_image_rect.x = 1400
buy_image_rect.y = 130
font = pygame.font.SysFont("arial", 32, True)
# - loop -
running = True
clock = pygame.time.Clock()
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if image_rect.collidepoint(event.pos):
times_clicked += 1
times_clicked = shop(event.pos, times_clicked)
if event.type == pygame.QUIT:
running = False
# - calculations -
text = font.render(f"Cookies: {times_clicked}", True, "orange")
#text_rect = text.get_rect()
#text_rect.center = (880, 100)
text_rect = text.get_rect(center=(880, 100))
# - draws -
screen.fill(background_colour)
screen.blit(image, image_rect)
screen.blit(text, text_rect)
screen.blit(shop_text, shop_text_rect)
screen.blit(cursor_image, cursor_image_rect)
screen.blit(buy_image, buy_image_rect)
# - update -
pygame.display.flip()
clock.tick(60)

I'n creating my first game in pygame and i need help on showing up a screen when i press any key [duplicate]

This question already has answers here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
As i mention, i'm super new in pygame and need help with this. I'm just testing the pygame commands, and want to show up a white screen with a message whenever i initialize the game and press any key, but apparently, it's not working. Here's my code:
# pygame template
import pygame
# import random
WIDTH = 400
HEIGHT = 500
FPS = 60
TITLE = 'My Game'
FONT_NAME = 'SNAKE/DinoTopia.ttf'
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
CLOCK = pygame.time.Clock()
# classes
class Main:
def __init__(self):
self.running = False
self.game_font = pygame.font.match_font(FONT_NAME)
def show_screen(self):
if self.running is True:
SCREEN.fill(WHITE)
self.draw_text('HELLO', 50, WIDTH/2, HEIGHT/2, BLUE)
pygame.display.flip()
self.wait_for_key()
def wait_for_key(self):
for key in pygame.event.get():
if key.type == pygame.KEYUP:
self.running = True
self.show_screen()
def draw_text(self, text, size, x, y, color):
font = pygame.font.Font(self.game_font, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
SCREEN.blit(text_surface, text_rect)
g = Main()
# game loop
running = True
while running:
# keep loop running at the right speed
CLOCK.tick(FPS)
# process input
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# update
# draw/ render
SCREEN.fill(BLACK)
g.wait_for_key()
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
i know something may be wrong with the wait_for_key function but i can't see what it is, so a little help would be nice! thanks in advance!
show screen function is only called when a key is up. A single frame. You have to call it every frame. Also don't call pygame.event.get and pygame.display.flip more than once.
# pygame template
import pygame
# import random
WIDTH = 400
HEIGHT = 500
FPS = 60
TITLE = 'My Game'
FONT_NAME = 'SNAKE/DinoTopia.ttf'
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
CLOCK = pygame.time.Clock()
# classes
class Main:
def __init__(self):
self.running = False
self.game_font = pygame.font.match_font(FONT_NAME)
def show_screen(self):
if self.running:
SCREEN.fill(WHITE)
self.draw_text('HELLO', 50, WIDTH/2, HEIGHT/2, BLUE)
def wait_for_key(self, events):
for event in events:
if event.type == pygame.KEYUP:
self.running = True
def draw_text(self, text, size, x, y, color):
font = pygame.font.Font(self.game_font, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
SCREEN.blit(text_surface, text_rect)
g = Main()
# game loop
running = True
while running:
# keep loop running at the right speed
CLOCK.tick(FPS)
# process input
events = pygame.event.get()
for event in events:
# check for closing window
if event.type == pygame.QUIT:
running = False
# update
# draw/ render
SCREEN.fill(BLACK)
g.wait_for_key(events)
g.show_screen()
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()

Comparing keypressed to a char

I want to make some sort of typing game in python using pygame. So, if the key pressed character is the same as the character in the word, it should return true... Is there any way to do this in python?
For example:
the word is "cat", if the user presses the key 'c', then it returns true... and so on for the rest of the characters.
here's my main.py file
from time import sleep
import pygame
import random
import winsound
from words import Words
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
done = False
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
w1 = Words(screen) #making a single word (for now) to see if typing works
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
w1.draw()
#attempting to write code here to compare word and user input
pygame.display.flip()
clock.tick(60)
pygame.init()
exit()
here's my words.py file
from random_words import RandomWords
import pygame
import random
from queue import *
rw = RandomWords()
class Words():
def __init__(self, screen):
self.screen = screen
self.x_point = 400
self.y_point = 400
self.word = rw.random_word() #generates a random word
self.queue = Queue() #was hoping to use the queue so that if the user types the char correctly in the right order, then the letter would change color or something (but that's further down the line)
for c in self.word: #iterate through randomized word..
self.queue.put(c) #add each char in randomized word to queue, for typing reasons
def getY(self):
return self.y_point
def draw(self):
#creates a new object
myfont = pygame.font.SysFont('Comic Sans MS' ,30)
#creates a new surface with text drawn on it
textsurface = myfont.render(self.word, False, (0,0,0))
self.screen.blit(textsurface,(self.x_point,self.y_point))
Event KEYDOWN has event.unicode, event.key, event.mod
You can compare
if event.type == pygame.KEYDOWN:
if event.unicode == "a":
or even
if event.type == pygame.KEYDOWN:
if event.unicode.lower() == "a":
to check "a" and "A"
To check char in word
if event.type == pygame.KEYDOWN:
if event.unicode.lower() in your_word.lower():
Example code use event.unicode to render text with pressed keys.
BTW: It is not some Entry widget so it doesn't delete char when you press backspace.
import pygame
# --- constants ---
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 200
FPS = 5 # `FPS = 25` is enough for human eye to see animation.
# If your program don't use animation
# then `FPS = 5` or even `FPS = 1` can be enough
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
screen_rect = screen.get_rect()
# - objects -
font = pygame.font.SysFont(None, 30)
text = ""
text_image = font.render(text, True, GREEN)
text_rect = text_image.get_rect() # get current size
text_rect.center = screen_rect.center # center on screen
# - mainloop -
clock = pygame.time.Clock()
done = False
while not done:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
text += event.unicode
text_image = font.render(text, True, GREEN)
text_rect = text_image.get_rect() # get current size
text_rect.center = screen_rect.center # center on screen
# - draws -
screen.fill(BLACK)
screen.blit(text_image, text_rect)
pygame.display.flip()
clock.tick(FPS)
# - end -
pygame.quit() # <-- quit(), not init()

How to queue multiple pygame scripts in a module?

Does anyone know if there is a way to make pygame scripts run one after another?
This is my module below, I would like to know if I could get them to deploy at certain intervals, that is, I would like 'A_long_time_ago' to run, last for 5 seconds then close and immediately load 'sounds' and 'logo', then 3 seconds later for them to close, transitioning into 'Title_Crawl'.
The Module
from A_long_time_ago import *
from sounds import *
from logo import *
from Title_Crawl import *
A_long_time_ago
import pygame
import time
pygame.init()
screen = pygame.display.set_mode((1376, 760))
clock = pygame.time.Clock()
done = False
font = pygame.font.SysFont("franklingothicbook", 40)
text = font.render("A long time ago in a galaxy far, far away....", True, (75, 213, 238))
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
screen.fill((0, 0, 0))
screen.blit(text,
(700 - text.get_width() // 2, 380 - text.get_height() // 2))
pygame.display.flip()
clock.tick(60)
sounds
import pygame
pygame.mixer.init()
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
pygame.mixer.music.load('The_Theme.wav')
pygame.mixer.music.play()
logo
import pygame
import os
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
_image_library[path] = image
return image
pygame.init()
screen = pygame.display.set_mode((1000, 800))
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill((0, 0, 0))
screen.blit(get_image('sw.png'), (10, 10))
pygame.display.flip()
clock.tick(60)
Title_Crawl
#!/usr/bin/python
import pygame
from pygame.locals import *
pygame.init()
pygame.display.set_caption('Title Crawl')
screen = pygame.display.set_mode((1000, 800))
screen_r = screen.get_rect()
font = pygame.font.SysFont("franklingothicdemibold", 40)
clock = pygame.time.Clock()
def main():
crawl = ["Star Wars - The Wilds"," ","It is a dark time for the Galaxy. The evil Dark","Lord, Vitiate is rising to power. Alone, a single", "spec is on a trip, a trip that will ultimately", "rectify the wrongs of the galaxy. The keepers ", "of peace are dying out and the DARK SIDE is", "lurking, a conniving force determined to", "become the omniarch."]
texts = []
# we render the text once, since it's easier to work with surfaces
# also, font rendering is a performance killer
for i, line in enumerate(crawl):
s = font.render(line, 1, (229, 177, 58))
# we also create a Rect for each Surface.
# whenever you use rects with surfaces, it may be a good idea to use sprites instead
# we give each rect the correct starting position
r = s.get_rect(centerx=screen_r.centerx, y=screen_r.bottom + i * 45)
texts.append((r, s))
while True:
for e in pygame.event.get():
if e.type == QUIT or e.type == KEYDOWN and e.key == pygame.K_ESCAPE:
return
screen.fill((0, 0, 0))
for r, s in texts:
# now we just move each rect by one pixel each frame
r.move_ip(0, -1)
# and drawing is as simple as this
screen.blit(s, r)
# if all rects have left the screen, we exit
if not screen_r.collidelistall([r for (r, _) in texts]):
return
# only call this once so the screen does not flicker
pygame.display.flip()
# cap framerate at 60 FPS
clock.tick(60)
if __name__ == '__main__':
main()
The best way to do this would be to make them into classes and give them a run method, and then instantiate each one on a timer and call its run method to do what it needs to do.

Black screen when trying to create a menu

I have a problem. I have made a menu for a game I am making with python (it is more of a start screen). However, when I run the code, I see a windows titled appropriately, but the screen itself is black. What am I doing wrong?
#importing the libraries
import pygame
import sys
import os
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
#colour R G B
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
DARKGREEN = ( 0, 155, 0)
DARKGREY = ( 40, 40, 40)
BGCOLOR = BLACK
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.init()
#Drawing the message
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render("Press a key to play...", True, DARKGREY)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
#Showing the start screen
def showStartScreen():
titleFont = pygame.font.Font(None, 100)
titleMain = titleFont.render('Badger Defense', True, WHITE, BGCOLOR)
titleSecond = titleFont.render("Don't get your family killed!", True, GREEN)
while True:
drawPressKeyMsg()
#Main function
def main():
global DISPLAYSURF, BASICFONT
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.Font(None, 18)
pygame.display.set_caption('Badger Defense - Aplha(0.0.1)')
showStartScreen()
#Drawing the screen
DISPLAYSURF.fill(BGCOLOR)
pygame.display.update()
#Reaction to the message
def checkForKeyPress():
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
os.system('python game.py')
if __name__ == "__main__":
main()
I am using Sublime and am running Ubuntu 12.04. I have the game and all its resources in the same folder as the menu, and I have a __init__.py file there as well.
Use pygame.display.update() to update the screen.

Categories