2017-03-03 111 views
0

在我簡單的程序中,我有一個開始按鈕並檢查事件,如果單擊start,我想讓開始文本改變顏色,然後我想將其改爲false遊戲開始。這從來沒有發生過,pygame在沒有停止的情況下卡在屏幕上。我希望while循環開始,然後它將轉到另一個while循環。我該如何檢查單擊是否啓動,更改文本顏色,然後在下面的代碼中結束while循環?無法在pygame中啓動遊戲進入屏幕

import pygame, sys 
from pygame.locals import * 

pygame.init() 

FPS = 60 # frames per second setting 
clock = pygame.time.Clock() 

screen = pygame.display.set_mode((700, 800)) 

window_width = 540 
window_height = 800 

#Title screen fonts 
fontObj2 = pygame.font.Font('freesansbold.ttf', 60) 
start = fontObj2.render("Start", True,(255,255,255)) 

into=True 

while into==True: 
    screen.blit(start, (window_width/2, 600)) 

    for event in pygame.event.get(): #Closes game 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     elif start.get_rect().collidepoint(pygame.mouse.get_pos()): 
      x, y = event.pos 
      if start.get_rect().collidepoint(x, y): 
       start = fontObj2.render("Start", True, (192,192,192)) 
       into=False 
     elif event.type == pygame.MOUSEBUTTONDOWN: 
      x, y = event.pos 
      if start.get_rect().collidepoint(x, y): 
       start = fontObj2.render("Start", True, (192,192,192)) 
       into = False 
    pygame.display.flip() 
    pygame.display.update() 
    clock.tick(FPS) 

回答

0

首先要開始了,你可以擺脫start.get_rect().collidepoint(pygame.mouse.get_pos()),因爲你已經在event.type == pygame.MOUSEBUTTONDOWN定義它。

您的代碼無法正常工作,因爲start.get_rect()的位置不在其位於屏幕上的位置。如果你打印它,你會看到<rect(0, 0, 140, 61)>這是左上角的矩形。

要解決這個問題,您只需將其更改爲start.get_rect(x=window_width/2, y=600) #where you blit the font即可設置rect的位置。

所以切莫:

import pygame, sys 
from pygame.locals import * 

pygame.init() 

FPS = 60 
clock = pygame.time.Clock() 

screen = pygame.display.set_mode((700, 800)) 

window_width = 540 
window_height = 800 

fontObj2 = pygame.font.Font('freesansbold.ttf', 60) 
start = fontObj2.render("Start", True,(255,255,255)) 

into=True 

while into: #Equivalent to into == True 
    screen.blit(start, (window_width/2, 600)) 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     #got rid of another if statement 
     elif event.type == pygame.MOUSEBUTTONDOWN: 
      x, y = event.pos 
      if start.get_rect(x=window_width/2, y=600).collidepoint(x, y): #changed start.get_rect 
       start = fontObj2.render("Start", True, (192,192,192)) 
       into = False 

    #same as before 
    pygame.display.flip() 
    pygame.display.update() 
    clock.tick(FPS)