I have a problem. i am trying to program a menu for a game in python I am making now. But I have a problem. Every time I run the code, the code exits without even doing anything. i went through the code, and see nothing that can cause this. Here is the code:
#importing the libraries
import pygame
import sys
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))
def main():
global DISPLAYSURF, BASICFONT
pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.Font('DrippingCool.ttf, 18')
pygame.display.set_caption('Badger Defense - Aplha(0.0.1)')
showStartScreen()
#Drawing the screen
DISPLAYSURF.fill(BGCOLOR)
pygame.display.update()
#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)
#Reaction to the message
def checkForKeyPress():
if len(pygame.event.get(QUIT)) > 0:
terminate()
keyUpEvents = pygame.event.get(KEYUP)
if len(keyUpEvent) == 0:
return None
if keyUpEvents[0].key == K_SPACE:
terminate()
return keyUpEvents[0].key
#Showing the start screen
def showStartScreen():
titleFont = pygame.font.Font('DrippingCool.ttf', 100)
titleMain = titleFont.render('Badger Defense', True, WHITE, DARKGREEN)
titleSecond = titleFont.render('Badger Defense', True, GREEN)
degrees1 = 0
degrees2 = 0
while True:
DISPLAYSURF.fill(BCOLOR)
rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
rotatedRect1 = rotatedSurf1.get_rect()
rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
rotatedRect2 = rotatedSurf2.get_rect()
rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
DISPLAYSURF.blit(rotatedSurf2, rotatedRect2)
drawPressKeyMsg()
if checkForKeyPress():
pygame.event.get()
return
pygame.display.update()
degrees1 += 3 #rotate by 3 degrees each frame
degrees2 += 7 #rotate by 7 degrees each frame
def terminate():
pygame.quit()
sys.exit()
I am running Ubuntu 12.04. I wrote the code in Sublime but tried to run it in Geany as well. Both didn't work.
Thanks for the help in advance.
You don't seem to have a if __name__ == '__main__': section at the bottom of your code, or anything else that would actually run your code. You are defining everything, but nothing runs because you have not told it to run.
Try adding something like this to the bottom of your code:
if __name__ == '__main__':
main()
The StackOverflow question What does if __name__ == "__main__": do? talks about why you would put that in your file.
Related
I wrote a small code to try working with pygame for the first time, but I'm having trouble getting the game window to respond to any input at all including the exit button. No matter if I run the code through Sublime, VScode, or Python the window loads fine but the sprite takes no input (so fare I have only coded left) nor will the window close. If I want to close the window I have to close whatever editor/terminal I'm running the program through
import pygame
import os
pygame.display.set_caption("CyberPunk 3077")
WIDTH, HEIGHT = 900, 500
PLAYER, SIZE = 34, 34
WIN = pygame.display.set_mode((WIDTH,HEIGHT))
'''We have now created the window and it's size
Now lets create the background display'''
FPS = 60
VELOCITY = 3
WHITE = ((255, 255, 255))
MID_BORDER = pygame.Rect((WIDTH/2)-2.5, 0,5, HEIGHT) #this will place a solid line in the middle of the screen
Player_1 = pygame.transform.scale(pygame.image.load(os.path.join('skins', 'player.png')), (PLAYER,SIZE))
P1 = pygame.transform.rotate(Player_1, 270)
Player_2 = pygame.transform.scale(pygame.image.load(os.path.join('skins', 'enemy.png')), (PLAYER,SIZE))
P2 = pygame.transform.rotate(Player_2, 270)
SKY = pygame.transform.scale(pygame.image.load(os.path.join('skins', 'bg.png')), (WIDTH,HEIGHT))
#this will search our folder 'skins' for the file 'bg' to make our background
def draw(yellow, blue):
WIN.blit(SKY, (0,0))
pygame.draw.rect(WIN, WHITE, MID_BORDER)
WIN.blit(P1, (yellow.y, yellow.y))
WIN.blit(P2, (blue.x, blue.y))
#pygame starts tracking at the top left with 0,0
pygame.display.update()
def P1_moves(keys_pressed, yellow):
if keys_pressed[pygame.K_a] and yellow.x - VELOCITY > 0: #LEFT
yellow.x -= VELOCITY
'''this is the only instance of movement I have coded so far. Didn't want to continue if I can't even get 'left' to work '''
def main():
yellow = pygame.Rect(200, 250, 32, 32)
blue = pygame.Rect(650, 250, 32, 32)
run = True
clock = pygame.time.Clock()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run == False
keys_pressed = pygame.key.get_pressed()
P1_moves(keys_pressed, yellow)
draw(yellow, blue)
pygame.quit()
if __name__ == "__main__":
main()
The keys_pressed[pygame.K_a] should be keys_pressed[pygame.K_A] (capital 'A').
Rabbid76 answered this problem in a comment.
run = False instead of run == False
WIN.blit(P1, (yellow.x, yellow.y)) instead of WIN.blit(P1, (yellow.y, yellow.y))
Rabbid76 Sep 15 at 18:18
So I was making a game in python with pygame and I had some assets as characters. I coded everything correctly. But when I run the program none of the images show up and the window crashes immediately.
import pygame
import os
import random
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Fly game")
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
FPS = 60
VEL = 5
BORDER = pygame.Rect(WIDTH//2 - 5, 0, 10, HEIGHT)
PLAYER_WIDTH, PLAYER_HEIGHT = 55, 40
SKY = pygame.image.load(
os.path.join('C:\\Users\\Kostadin Klemov\\Desktop\\Programms\\Python\\projects\\Fly game\\Assets\\SKY.jpg')), (WIDTH, HEIGHT)
JETPACK_MAN_IMAGE = pygame.image.load(
os.path.join('C:\\Users\\Kostadin Klemov\\Desktop\\Programms\\Python\\projects\\Fly game\\Assets\\JETPACK_MAN.jpg'))
JETPACK_MAN = pygame.transform.scale(
JETPACK_MAN_IMAGE, (PLAYER_WIDTH, PLAYER_HEIGHT))
FLY_IMAGE = pygame.image.load(
os.path.join('C:\\Users\\Kostadin Klemov\\Desktop\\Programms\\Python\\projects\\Fly game\\Assets\\FLY.png'))
FLY = pygame.transform.scale(
FLY_IMAGE, (PLAYER_WIDTH, PLAYER_HEIGHT))
def draw_window(jetpack, fly):
WIN.blit(SKY, (0, 0))
pygame.draw.rect(WIN, BLACK, BORDER)
WIN.blit(JETPACK_MAN, (jetpack.x, jetpack.y))
WIN.blit(FLY, (fly.x, fly.y))
pygame.display.update()
def main():
jetpack = pygame.Rect(225, 250, PLAYER_WIDTH, PLAYER_HEIGHT)
fly = pygame.Rect(675, 250, PLAYER_WIDTH, PLAYER_HEIGHT)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
draw_window(jetpack, fly)
main()
if __name__ == "__main__":
main
No error showed up so I didn't know what was wrong.
If you can, please check out the code and try to fix it!
This is an indentation error.
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
# <---- INDENTATION
# this should be in the while loop, the "game loop", not in the quit condition
draw_window(jetpack, fly)
Also, you probably don't want to call main() after you program terminates. (Assuming you want people to be able to exit your game easily.
if __name__ == "__main__":
main
This main does nothing, it needs to be called, like main(). With the parentheses. It's not "crashing instantly," it's just not running anything.
SKY = pygame.image.load(
os.path.join('C:\\Users\\Kostadin Klemov\\Desktop\\Programms\\Python\\projects\\Fly game\\Assets\\SKY.jpg')), (WIDTH, HEIGHT)
That (WIDTH, HEIGHT) at the end is very suspicious. Presumably you just want the image put in the SKY variable, not another random tuple.
On another note, os.path.join() does nothing if you give it the full path as an argument.
Here's the code, i'm working on Atom. I've been using pygame for a lot of time, and that rarely happens. I never knew what the problem was, but i never needed to, until now.
import pygame
from random import randint as rnd
from colorama import Cursor
import math
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (600,90)
pygame.init()
xsize, ysize = 700, 700
screen = pygame.display.set_mode((xsize, ysize))
screen.fill((0, 0, 0))
def dis(p1, a1):
return math.sqrt((p1[0] - a1[0])**2 + (p1[1] - a1[1])**2)
inner = 0
tot = 0
pygame.draw.circle(screen, (255, 255, 255), (350, 350), 350, 2)
while True:
pos = (rnd(0, xsize), rnd(0, ysize))
if dis((350, 350), pos) < 350:
color = (50, 255, 50)
inner += 1
else:
color = (50, 50, 250)
tot += 1
pygame.draw.circle(screen, color, pos, 2)
print(" pi = " + str(4 * inner / tot) + "\nnÂș dots: " + str(tot), Cursor.UP(2))
pygame.display.flip()
The window freeze, because you do not handle the events. You have to handle the events by either pygame.event.pump() or pygame.event.get(), to keep the window responding.
Add an event loop, for instance:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# [...]
I am starting to write a game but whenever I run my code it takes 2 minutes to boot up and even then some methods are not working. The main ones that's not working are quitting pygame and drawGameScene().
My code is:
import os, random
from pygame import *
init()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(0, 20)
scalefactor = 2
FPS = 60
screenWidth = round(224 * scalefactor)
screenHeight = round(298 * scalefactor)
size = screenWidth, screenHeight
screen = display.set_mode(size)
button = 0
RED = (255, 0, 0)
BLUE = (0,0,255)
STATEGAME = 1
STATEQUIT = 3
curState = STATEGAME
titleFont = font.SysFont("Times New Roman",45)
def drawText(words, screen,position, color, font):
text = font.render(words, False, color)
textSize = text.get_size()
position[0] = position[0] - textSize[0]//2
position[1] = position[1] - textSize[1]//2
#centers the text
screen.blit(text,position)
def gameRun():
while curState != STATEQUIT:
if curState == STATEGAME:
drawGameScene()
eventCheck()
updater()
def eventCheck():
for evnt in event.get():
if evnt.type == QUIT:
curState == STATEQUIT
def updater():
pass
def drawGameScene():
draw.rect(screen,RED,(0,0,screenWidth,screenHeight))
drawText("High Score", screen, [0,0], BLUE, titleFont)
display.update
gameRun()
display.flip()
no error messages are given
Please Help, It's for a project
For the quitting pygame:
You should use the code as below:
for events in event.get():
if events.type == QUIT:
pygame.quit()
exit() #this is from sys module
This way, your pygame is quitted at the first place. So, you don't need anything about curstate, etc.
Also, you need to use while True statement to repeat the blitting process.
Full code:
import os, random
from pygame import *
from sys import exit
init()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(0, 20)
scalefactor = 2
FPS = 60
screenWidth = round(224 * scalefactor)
screenHeight = round(298 * scalefactor)
size = screenWidth, screenHeight
screen = display.set_mode(size)
button = 0
RED = (255, 0, 0)
BLUE = (0,0,255)
titleFont = font.SysFont("Times New Roman",45)
def drawText(words,screen,position,color,font):
text = font.render(words, False, color)
textSize = text.get_size()
position[0] = position[0] - textSize[0]//2
position[1] = position[1] - textSize[1]//2
#centers the text
screen.blit(text,position)
def gameRun():
drawGameScene()
eventCheck()
updater()
def eventCheck():
for events in event.get():
if events.type == QUIT:
quit()
exit()
def updater():
pass
def drawGameScene():
draw.rect(screen,RED,(0,0,screenWidth,screenHeight))
drawText("High Score", screen, [0,0], BLUE, titleFont)
#display.update()
while True:
gameRun()
display.flip()
Question
I'm pretty new at Python and Pygame so I figured I'd jump right it head first and work on making a little rpg style game. I keep getting the error message below. I keep checking the code and re-watching the tutorial I'm following and I can't seem to find the problem.
I'm sure it's pretty obvious but I don't see the problem. I'm pretty sure I formatted the code in this post right but I don't know.
Error Message
Traceback (most recent call last):
File "C:\Users\Clayton\PycharmProjects\newgame\main.py", line 42, in <module>
gameDisplay.blit(Tiles.grass(x, y))
TypeError: 'pygame.Surface' object is not callable
Main.py
import pygame
from gamescripts.textures import *
# initialize PyGame
pygame.init()
# display information
# int defines number a an integer (ex1)
display_width = int(800)
display_height = int(600)
tile_size = 32
# color definitions
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
skyblue = (135, 206, 235)
yellow = (255, 255, 0)
# window
gameDisplay = pygame.display.set_mode((display_width, display_height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('test game')
clock = pygame.time.Clock()
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
print(event)
# render graphics
gameDisplay.fill(skyblue)
for x in range(0, 620, tile_size):
for y in range(0, 480, tile_size):
gameDisplay.blit(Tiles.grass(x, y))
# draws everything to window
pygame.display.update()
# num entered is game fps
clock.tick(60)
# quit PyGame
pygame.quit()
# quit python
quit()
Textures.py
import pygame
pygame.init()
class Tiles:
Size = 32
def load_texture(file, Size):
bitmap1 = pygame.image.load(file)
bitmap2 = pygame.transform.scale(bitmap1, (Size, Size))
surface = pygame.Surface((Size, Size), pygame.HWSURFACE | pygame.SRCALPHA)
surface.blit(bitmap2, (0, 0))
return surface
grass = load_texture('graphics\\grass.png', Size)
You have to create an instance of your Tiles class.
Your Tiles class cannot be directly blitted without creating an instance first.
#create a instance of `Tiles`
tile=Tiles()
tile.load_texture('graphics\\grass.png',32)
Implemented into your code:
import pygame
from gamescripts.textures import *
# initialize PyGame
pygame.init()
# display information
# int defines number a an integer (ex1)
display_width = int(800)
display_height = int(600)
tile_size = 32
# color definitions
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
skyblue = (135, 206, 235)
yellow = (255, 255, 0)
# window
gameDisplay = pygame.display.set_mode((display_width, display_height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('test game')
clock = pygame.time.Clock()
#create an instance of your `Tile` class
tile=Tile()
tile.load_texture('graphics\\grass.png',32)
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
print(event)
# render graphics
gameDisplay.fill(skyblue)
for x in range(0, 620, tile_size):
for y in range(0, 480, tile_size):
#choose example coordinates for x and y
gameDisplay.blit(tile,(x,y))
# draws everything to window
pygame.display.update()
# num entered is game fps
clock.tick(60)
# quit PyGame
pygame.quit()
# quit python
quit()
import pygame
pygame.init()
You should change your Tile class as well.
class Tiles:
#initialize your class
def__init__(self):
pass
#ALWAYS use self as the first parameter
def load_texture(self,file, Size):
bitmap1 = pygame.image.load(file)
bitmap2 = pygame.transform.scale(bitmap1, (Size, Size))
surface = pygame.Surface((Size, Size), pygame.HWSURFACE | pygame.SRCALPHA)
surface.blit(bitmap2, (0, 0))
return surface
I suggest you really take a look at the the pygame documentation and the python documentation.
You should also look at SO if your question was already posted. For example, I found this example.