Mouse control not responding [closed] - python

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've just started using pygame. I've created my game but it's really unstable and crashes (having issues exiting).
I've created a welcome page but it has created a bug with game control (the character controlled by the mouse has stopped responding), I've tried few methods but just results in more game crashes and errors. can you please help me out to debug anything you might spot. you download the game from her http://dl.dropbox.com/u/47312995/Twerk.rar
the code:
import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *
black = (0,0,0)
white = (255,255,255)
pygame.init()
def game():
os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
screen = display.set_mode((800,500))
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
display.set_caption('Twerk')
back = pygame.Surface(screen.get_size())
def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)
text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2)
textpos.top = x_pos
screen.blit(text, textpos)
start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")
#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)
#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()
while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=1
velocity=1
for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))
font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(backdrop, (0,0))
screen.blit(text, textRect)
pygame.display.update()
game=time.localtime()
while start == True:
end=time.localtime()
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break
first=True
strtTime=time.localtime()
while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()
if first:
while True:
end=time.localtime()
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False
if falling:
for i in range(enemies):
positionymove[i]=1000
positionxmove[i]=0
for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])
if falling:
falling=False
for posy in positiony:
if posy<600: falling=True
if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp
for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1
for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:
endTime=time.localtime()
score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
falling = True
finish = True
game()
Thank you in advance

The problem is that you're not checking for input. EACH time through your game loop, you should call pygame.event.get(). For example, from my template code:
def quit():
pygame.quit(); sys.exit()
def GetInput():
key = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT: quit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: quit()
def Draw():
pygame.display.flip()
def main():
Clock = pygame.time.Clock()
while True:
GetInput()
Draw()
Clock.tick(60)

Related

Pygame screen doesn't seem to refresh

I've been trying to make a Chrome Dino Game, however, I'm struggling with this problem:
On every frame, it should draw a new one at the new position and delete the previous one to make it look as if it's moving. HOWEVER, it remains at its previous position and a new image appears on its next position. I did write the pygame.display.update() code at the end of my maintop.
In the last time I ran into a similar problem, I managed to make it work by drawing a background image, but this time, it doesn't work.
following are my codes:
import pygame
import os
from random import randint
import schedule
pygame.init()
assets = os.path.join(os.path.dirname(__file__), "Assets")
screen_size = (screen_width, screen_height) = (1280, 720)
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
fps = 120
bg = pygame.image.load(os.path.join(assets, "IMG_15.png"))
ground = 700
running = True
spacebaridx = 0
gamestart = False
tick_on_start = 0
obs1 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs1, (100, 200))
obs2 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs2, (120, 200))
obs3 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs3, (150, 200))
ls_obs = []
def create_obs():
k = randint(1, 3)
if k == 1:
info = {"type":1, "img":obs1, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
if k == 2:
info = {"type":2, "img":obs2, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
else:
info = {"type":3, "img":obs3, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
schedule.every(3).seconds.do(create_obs)
while running:
dt = clock.tick(fps)
if gamestart == True:
game_ticks = pygame.time.get_ticks() - tick_on_start
schedule.run_pending()
else:
game_ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if spacebaridx == 0: # Press space to start / to tell whether it's the first press
spacebaridx += 1
gamestart = True
tick_on_start = pygame.time.get_ticks()
else:
pass # Jump
for o in ls_obs:
o["x"] += o["tox"] * -1
screen.blit(bg, (0, 0))
for o in ls_obs:
screen.blit(o["img"], (o["x"], o["y"]))
pygame.display.update()
pygame.quit()
This issue is occurring because you aren't clearing the display within each frame. In pygame, in order to clear the display, we need to use the fill method. So in your code, at the top of your game loop before the event loop, add screen.fill((0, 0, 0)). This will fill your screen in the color black. Don't worry, the black won't be shown if you draw the background on top of it. Now, when you add a new image, the previous images won’t be displayed.
Modified Game Loop
while running:
screen.fill((0, 0, 0))
dt = clock.tick(fps)
if gamestart == True:
game_ticks = pygame.time.get_ticks() - tick_on_start
schedule.run_pending()
else:
game_ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if spacebaridx == 0: # Press space to start / to tell whether it's the first press
spacebaridx += 1
gamestart = True
tick_on_start = pygame.time.get_ticks()
else:
pass # Jump
for o in ls_obs:
o["x"] += o["tox"] * -1
screen.blit(bg, (0, 0))
for o in ls_obs:
screen.blit(o["img"], (o["x"], o["y"]))
pygame.display.update()
pygame.quit()

Can't move sprite and cant click on image [duplicate]

This question already has answers here:
Why is my pygame application loop not working properly?
(1 answer)
Pygame window freezes when it opens
(1 answer)
How to detect when a rectangular object, image or sprite is clicked
(1 answer)
Closed 2 years ago.
For my coursework for computer science I have to make a program but I've ran into issues that I can't find answers to.
Firstly in the section of code highlighted with *** I am trying to make the sprite character1 move which doesn't do anything when I press the arrow keys and don't know why
Secondly is the picture I am using as a button doesn't do anything when i click on it - highlighted with ###
I know my code isn't the most efficient but I'm trying to do what makes sense to me
import pygame
import random
import time
WIDTH = 1080
HEIGHT =720
FPS = 30
x1 = WIDTH/2.25
y1 = HEIGHT/2.5
x2 = WIDTH/20
y2 = HEIGHT/2.5
xbut = 800
ybut = 275
gameTitle = 'Hungry Ghosts'
xChange1 = 0
yChange1 = 0
xChange2 = 0
yChange2 = 0
#define colours
WHITE = (255,255,255)
BLACK = (0,0,0)
MEGAN = (123,57,202)
MOLLIE = (244,11,12)
KATIE = (164,12,69)
#initialise pygame and window
pygame.init()
pygame.mixer.init()
pygame.font.init()
screen =pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Hungry Ghosts')
clock = pygame.time.Clock()
#load immages
background_image = pygame.image.load(('purplesky.jpg'))
player1_image = pygame.image.load(('player 1.png')).convert_alpha()
player2_image = pygame.image.load(('player 2.png')).convert_alpha()
position = (0,0)
screen.blit(background_image, position)
startBut = pygame.image.load('button.jpg').convert()
#define functions
def textObjects(gameTitle, font):
textSurface = font.render(gameTitle,True, WHITE)
pygame.display.update()
return textSurface, textSurface.get_rect()
def titleText(gameTitle):
textForTitle = pygame.font.Font('VCR_OSD_MONO_1.001.ttf',115)
TextSurf, TextRect = textObjects(gameTitle, textForTitle)
TextRect.center = ((WIDTH/2),(HEIGHT/6))
screen.blit(TextSurf,TextRect)
pygame.display.update()
########################################
def titleButton(xbut,ybut):
screen.blit(startBut,(xbut,ybut))
pygame.display.update()
########################################
***************************************
def character1(x1,y1):
screen.blit(player1_image,(x1,y1))
pygame.display.update()
***************************************
def character2(x,y):
screen.blit(player2_image,(x,y))
pygame.display.update()
def homeScreen():
running = True
gameplay = False
instructions = False
home = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
################################################################
if event.type == pygame.MOUSEBUTTONDOWN:
xbut,ybut = event.pos
if startBut.get_rect().collidepoint(xbut,ybut):
print('clicked on button')
################################################################
def gameLoop():
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
*************************************************************************
#movement
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xChange1 = -5
elif event.key == pygame.K_RIGHT:
xChange1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xChange1 = 0
x1 += xChange1
*************************************************************************
#calling functions
titleText(gameTitle)
character1(x1,y1)
character2(x2,y2)
titleButton(xbut,ybut)
homeScreen()
pygame.quit()
You have to do the movement and the drawing of the scene in the game loop.
an application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
running = True
def homeScreen():
global running
start = False
home = True
while running and not start:
clock.tick(FPS)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if startBut.get_rect(topleft = (xbut, ybut)).collidepoint(event.pos):
print('clicked on button')
start = True
# draw background
screen.blit(background_image, (0, 0))
# draw scene
titleText(gameTitle)
titleButton(xbut,ybut)
# update display
pygame.display.flip()
homeScreen()
def gameLoop():
global running
global x1, y2, x2, y2, xChange1, yChange1, xChange2, yChange2
while running:
clock.tick(FPS)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xChange1 = -5
elif event.key == pygame.K_RIGHT:
xChange1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xChange1 = 0
# update position of objects
x1 += xChange1
# draw background
screen.blit(background_image, (0, 0))
# draw scene
character1(x1,y1)
character2(x2,y2)
# update display
pygame.display.flip()
gameLoop()
pygame.quit()

Why does my pygame show not responding after a few seconds?

Just to clarify, I have absolutely no idea what I'm doing, in fact I'm really not sure how I got this far. I wrote a bit of code to act as an auto clicker for a Minecraft farm (yes, I'm aware you can use much simpler methods). I've taken bits and pieces from various tutorials and have done some by myself. It is a bit of a mess. However, once the code runs and does the first click the pygame window shows not responding. I have no idea why. I would appreciate any advice and tips and it would be great if I could bet this problem fixed, thanks!
I think some of the code was messed up from me not knowing how to use this very well :(
import pygame
import keyboard
import time
import pyautogui
pygame.init()
def Click():
pyautogui.doubleClick(None, None, 1)
print('Click')
time.sleep(3)
def Img(x, y):
display_surface.blit(Piglin_Img, (x, y))
white = (255, 255, 255)
black = (0, 0, 0)
x = 280
y = 10
X = 400
Y = 100
Piglin_Img = pygame.image.load('Piglin.png')
pygame.display.set_icon(pygame.image.load("Icon.png"))
display_surface = pygame.display.set_mode((X, Y ))
pygame.display.set_caption('Gold Farm Auto Clicker')
font = pygame.font.Font('freesansbold.ttf', 20)
Start_Text = font.render('Press p to start...', True, black, white)
Run_Text = font.render('Running...', True, black, white)
Pause_Text = font.render('Paused', True, black, white)
Start_Text_pos = (10, 10)
Run_Text_pos = (10, 10)
Pause_Text_pos = (10, 10)
Continue_pos = (10, 40)
display_surface.fill(white)
display_surface.blit(Start_Text, Start_Text_pos)
Clicker = False
running = True
while running:
for event in pygame.event.get():
Img(x, y)
pygame.event.set_blocked(pygame.MOUSEMOTION)
pygame.event.set_blocked(pygame.MOUSEBUTTONDOWN)
pygame.event.set_blocked(pygame.MOUSEBUTTONUP)
if event.type == pygame.QUIT or \
event.type == pygame.KEYDOWN and \
event.key == pygame.K_z:
running = False
if event.type == pygame.KEYDOWN and \
event.key == pygame.K_p:
print('started')
display_surface.fill(white)
display_surface.blit(Run_Text, Run_Text_pos)
Img(x, y)
pygame.display.update()
Clicker = True
while Clicker:
if event.type == pygame.KEYDOWN and \
event.key == pygame.K_x:
Clicker = False
display_surface.fill(white)
display_surface.blit(Start_Text, Continue_pos)
display_surface.blit(Pause_Text, Pause_Text_pos)
Img(x, y)
pygame.display.update()
Click()
if event.type == pygame.KEYDOWN and \
event.key == pygame.K_x:
Clicker = False
display_surface.fill(white)
display_surface.blit(Start_Text, Continue_pos)
display_surface.blit(Pause_Text, Pause_Text_pos)
Img(x, y)
pygame.display.update()
pygame.display.update()
pygame.quit()
It's blocking the event queue processing when Clicker becomes True. So once clicker starts looping, no user-input is handled as this loop never re-examines the queue for new events, and just continues to re-process the same (old) event result.
You probably need to merge the event handling in the while Clicker cause into the main event loop. Maybe with an if Clicker on those events:
pygame.event.set_blocked(pygame.MOUSEMOTION)
pygame.event.set_blocked(pygame.MOUSEBUTTONDOWN)
pygame.event.set_blocked(pygame.MOUSEBUTTONUP)
while running:
# handle events and user interaction
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN : # some key was pushed
if event.key == pygame.K_p:
print('started')
Clicker = True # start the clicker
elif event.key == pygame.K_x:
print('stopped')
Clicker = False # stop the clicker
elif event.key == pygame.K_z:
running = False # Allow exit here too
# Update the screen
if Clicker:
# Click mode
display_surface.fill(white)
display_surface.blit(Run_Text, Run_Text_pos)
else:
# NOT in Click Mode
display_surface.fill(white)
display_surface.blit(Start_Text, Continue_pos)
display_surface.blit(Pause_Text, Pause_Text_pos)
Img(x, y)
pygame.display.update()
Something close to that anyway. Without comments, it's not immediately clear what the intention of the code is, so it's hard to create an exacting solution.

Python game over screen won't accept input

I'm trying to make it so when the game over screen shows the user can press space to get back into the game. Currently, when a game over happens, it displays the game over screen but accepts no input or at least doesn't do anything with the input. For some context, the game is basically about moving left and right to avoid obstacles. Currently, I only have one obstacle, but I just have not gotten to that yet. Thanks!
import pygame
import random
import math
pygame.init()
screenWidth = 700
screenHeight = 800
x = screenWidth / 2
y = (screenHeight / 4) * 3
width = 50
height = 50
win = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption("Test Game")
bg = pygame.image.load("background.png").convert()
gameover = pygame.image.load("gameover.png").convert()
bgx = (screenWidth / 6) * 2
bgy = 0
clock = pygame.time.Clock()
class enemy():
def __init__(self,c,y,width,height):
self.c = c
self.y = y
self.width = width
self.height = height
self.vel = 5
def draw(self, win):
if self.c == 1:
self.x = 250
#250
elif self.c == 2:
self.x = 350
#350
else:
self.x = 450
#450
self.y += self.vel
pygame.draw.rect(win, (0,0,255), (self.x,self.y,self.width,self.height))
evil = enemy(random.randint(1,3),0,50,50)
#def redrawGameWindow():
# evil.draw(win)
# pygame.display.update()
running = True
gameOver = False
while running:
clock.tick(60)
while gameOver:
win.blit(gameover, (0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if pygame.event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
gameOver = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
x+=100
if event.key == pygame.K_LEFT:
x-=100
win.fill((0,0,0))
win.blit(bg, (bgx, bgy))
evil.draw(win)
dist = math.hypot(evil.x - x, evil.y - y)
if dist <= 50:
print("Game Over!")
running = False
gameOver = True
pygame.draw.rect(win, (255,0,0), (x,y,width,height))
pygame.display.update()
#redrawGameWindow()
while gameOver:
win.blit(gameover, (0,0))
pygame.display.update()
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
gameOver = False
pygame.quit()
The main problem is that your game over scene is the loop behind the main while running: loop and there's no way to go back to the first loop when you reach it. When you touch the evil object, you set running = False, leave the main and enter the while gameOver: loop.
In this loop you also need to call pygame.event.pump(), otherwise the pygame.key.get_pressed() function doesn't work correctly and the window freezes after a while because the events are not handled. If you want to restart the game, you should rather use only the nested while gameOver loop. Actually, I would recommend that you restructure the scenes even more and use a finite state machine instead (here's an answer in which I use functions as scenes but check out the link in the comment below as well).
Here's a working version of your code. I've changed a few things and added comments to explain the changes.
while running:
# -----The game over scene.-----
while gameOver:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# pygame.quit only uninitializes the pygame modules and
# doesn't quit the program.
pygame.quit()
# This will quit the whole program. You need to import sys.
sys.exit()
elif event.type == pygame.KEYUP: # event.type not pygame.event.type
if event.key == pygame.K_SPACE:
# Change it to False to break out of the loop.
gameOver = False
# Reset the game. You could reset the position of the
# `evil` object or instantiate a new one.
evil.x = 350
evil.y = 0
win.blit(gameover, (0,0))
pygame.display.update()
clock.tick(60) # You need to call tick in this loop as well.
# ------------------------------
# -----The main scene.-----
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
x += 100
elif event.key == pygame.K_LEFT:
x -= 100
win.fill((0,0,0))
win.blit(bg, (bgx, bgy))
evil.draw(win)
dist = math.hypot(evil.x - x, evil.y - y)
if dist <= 50:
print("Game Over!")
# running = False # This would stop the main loop.
gameOver = True
pygame.draw.rect(win, (255,0,0), (x,y,width,height))
pygame.display.update()
clock.tick(60)
# The other while loop was removed.
pygame.quit()

pygame.error: video system not initialized

I don't seem to able to get rid of this error, when I try to exist the game. the game runs fine but only get the error when I try to exist the game.
import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *
black = (0,0,0)
white = (255,255,255)
pygame.init()
def game():
os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
#screen
screen_width = 800
screen_height = 500
screen = pygame.display.set_mode([screen_width,screen_height])
#load images etc.
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
display.set_caption('Twerk')
back = pygame.Surface(screen.get_size())
def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)
text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2)
textpos.top = x_pos
screen.blit(text, textpos)
start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")
#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)
#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()
while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=4
velocity=1
for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))
font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(backdrop, (0,0))
screen.blit(text, textRect)
pygame.display.update()
game=time.localtime()
while start == True:
end=time.localtime()
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break
first=True
strtTime=time.localtime()
while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()
if first:
while True:
end=time.localtime()
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False
if falling:
for i in range(enemies):
positionymove[i]=1000
positionxmove[i]=0
for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])
if falling:
falling=False
for posy in positiony:
if posy<600: falling=True
if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp
for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1
for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:
falling = True
finish = True
#start = False
endTime=time.localtime()
score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
break
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
game()
This is the error I get, I've changed quit() to QUIT but still no luck.
Traceback (most recent call last):
File "C:\Users\MO\Desktop\Twerk\ballbounce_changed.py", line 171, in <module>
game()
File "C:\Users\MO\Desktop\Twerk\ballbounce_changed.py", line 160, in game
for event in pygame.event.get():
pygame.error: video system not initialized
thank you :)
You should stop your main loop when you want to exit the game.
My suggestions, either of
call exit() after pygame.quit()
set finish = True and start = False (though due to some indentation issues with your pasted code it's not possible to tell that this would actually work)
You should call pygame.quit() only when you want to terminate your Python session.
My suggestion: if you want to call game() more than once, e.g. in an interactive session, you should remove the call to pygame.quit() inside game(). This function uninitializes pygame and naturally all attempts to call its functionality will fail then.
You called pygame.quit(), but I think you need to also call sys.exit().
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
This is what I do in all of my games.
I think it's because you call pygame.quit() manually. Pygame will auto-quit itself, when your script ends.
To double check pygame is working, you can run this boilerplate: http://ninmonkey.googlecode.com/hg/boilerplate/pygame/1.%20blank%20screen/1%20-%20basic.%20pygame%20--nocomments.py
When you want to quit, set done=True. ( See line 37 and line 64 in the above example. )
I had this issue trying some Kivy test files using Spyder. In my case, because I was just trying out demo files, what quickly worked was restarting the kernel.
I know it's a blunt solution, but if you are on an IDE and you don't mind doing it, it's faster than typing commands.
You can do :
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # Here we exit the Loop and execute what after.
pygame.quit()
and It works fine !

Categories

Resources