2014-09-07 6 views
-3

извинения за длинный код. Моя проблема в том, что когда я запускаю код и выбираю вариант 2 в меню, запускается окно pygame, но через несколько секунд он перестает отвечать на запросы. Раньше я делал немного пирога и понятия не имею, в чем проблема. Ниже мой кодОкно Pygame перестает отвечать на запросы при запуске кода

import pygame, sys, time, random#Imports the modules pygame, sys, time and random form the python libary 
from pygame.locals import *#Imports all of the pygame modules 
global randomNumber 
#randomNumber = random.randint(1,4) 
redandBlackCounters = [120, 735, 250, 735, 560, 735, 690, 735] 
pygame.init#Initiates the pygame modules 
pygame.font.init()#Initites pygame fonts 

class AQADO:#Defines a class called AQADO 

    def Game_Board():#Defines a function called Game_Board 
     global DISPLAYSURF#DISPLAYSURF is set to global so all functions can access it 
     BOXSIZE = 70#Assigns 40 to the constant BOXSIZE 
     GRIDSIZE = 11#Assigns 5 to the constant GRIDSIZE 
     BOXLENGTH = 700#Assigns 700 to the constant BOXLENGTH 

     G = (13,158,30)#Constant G is set to the colour green 
     W = (255,255,255)#Constant W is set to the colour white 
     B = (0,0,0)#Constant B is set to the colour black 
     R = (245,10,10)#Constant R is set to the colour red 

     WINDOW_X_MAX = BOXSIZE*GRIDSIZE#The constant WINDOW_X_MAX is BOXSIZE multiplyed by GRIDSIZE 
     WINDOW_Y_MAX = 900#The constant WINDOW_X_MAX is BOXSIZE multiplyed by GRIDSIZE 
     DISPLAYSURF = pygame.display.set_mode((WINDOW_X_MAX, WINDOW_Y_MAX)) 
     pygame.display.set_caption("AQADo")#Sets the caption of the game window to AQADo 

     DISPLAYSURF.fill(W)#fills the background white 
     pygame.draw.rect(DISPLAYSURF,G,(BOXSIZE,0,BOXLENGTH,BOXSIZE))#draws a green rectangle at BOXSIZE, 0 length BOXLENGTH, width BOXSIZE 
     pygame.draw.rect(DISPLAYSURF,G,(BOXSIZE,420,BOXLENGTH,BOXSIZE))#draws a green rectangle at BOXSIZE, 420 length BOXLENGTH, width BOXSIZE 
     pygame.draw.rect(DISPLAYSURF,G,(BOXSIZE,700,BOXLENGTH,BOXSIZE))#draws a green rectangle at BOXSIZE, 700 length BOXLENGTH, width BOXSIZE 
     pygame.draw.rect(DISPLAYSURF,B,(0,770,780,200))#draws a green rectangle at 0, 770 length 780, width 200 

     for item in range (1, GRIDSIZE):#repeats below code 11 times 
      pygame.draw.line(DISPLAYSURF, B, (0,item*BOXSIZE),(WINDOW_Y_MAX,item*BOXSIZE))#draws a line 
     pygame.draw.line(DISPLAYSURF, B, (BOXSIZE,0), (BOXSIZE,WINDOW_X_MAX))#draws a line 

     pygame.draw.circle(DISPLAYSURF, R,(redandBlackCounters[0],redandBlackCounters[1]),30)#draws a red circle at 120,735 with a radius of 30 
     pygame.draw.circle(DISPLAYSURF, R,(redandBlackCounters[2],redandBlackCounters[3]),30)#draws a red circle at 250,735 with a radius of 30 
     pygame.draw.circle(DISPLAYSURF, B,(redandBlackCounters[4],redandBlackCounters[5]),30)#draws a black circle at 560,735 with a radius of 30 
     pygame.draw.circle(DISPLAYSURF, B,(redandBlackCounters[6],redandBlackCounters[7]),30)#draws a black circle at 690,735 with a radius of 30 


    def call_Game_Board():#defines a function called call_Game_Board 
     print("called the game board") 
     AQADO.Game_Board()#returns function AQADO.Game_Board 
     pygame.display.update()#Updates the pygame window 

    #def Choose_Counters(): 
     #playerOneChoose = int(input("Please input 1 to move the red counter on the left or 2 to move the red counter one the right")) 
     #if playerOneChoose == "1": 
      #print("") 
    def playerMove(): 
     if counter == 1 or 2 or 3 or 4: 
      Check_Move() 

    def Check_Move(counter): 
     if redandBlackCounters[1,3,5,7] == 735 or 35 and randomNumber == 4: 
      Counter_Move(move = False) 
      print("move not possible") 
     if redandBlackCounters[1] == 35 and redandBlackCounters[3] != 35 or 735 and randomNumber == 4: 
      print("Counter 2 has to move one space back") 
      redandBlackCounters[3] += 70 
     if redandBlackCounters[3] == 35 and redandBlackCounters[1] != 35 or 735 and randomNumber == 4: 
      print("Counter 1 has to move one space back") 
      redandBlackCounters[1] += 70 
     if redandBlackCounters[5] == 35 and redandBlackCounters[7] != 35 or 735 and randomNumber == 4: 
      print("Counter 3 has to move one space back") 
      redandBlackCounters[7] += 70 
     if redandBlackCounters[7] == 35 and redandBlackCounters[5] != 35 or 735 and randomNumber == 4: 
      print("Counter 4 has to move one space back") 
      redandBlackCounters[5] += 70 
     if redandBlackCounters[1,3] == 35: 
      print(playerOne,"Wins") 
     if redandBlackCounters[5,7] == 35: 
      print(playerTwo,"Wins") 
     #else: 
      #Counter_Move(counter) 

    def Counter_Move(redandBlackCounters, move, counter, randomNumber): 
     if randomNumber == 1 and counter == 1 and move != False: 
      redandBlackCounters[1] -= 70 
      AQADO.Game_Board()#returns function AQADO.Game_Board 
      pygame.display.update()#Updates the pygame window 
      print("") 
     if randomNumber == 1 and counter == 2 and move != False: 
      redandBlackCounters[3] -= 70 
      AQADO.Game_Board()#returns function AQADO.Game_Board 
      pygame.display.update()#Updates the pygame window 
      print("") 
     if randomNumber == 1 and counter == 3 and move != False: 
      redandBlackCounters[5] -= 70 
      AQADO.Game_Board()#returns function AQADO.Game_Board 
      pygame.display.update()#Updates the pygame window 
      print("") 
     if randomNumber == 1 and counter == 4 and move != False: 
      redandBlackCounters[7] -= 70 
      AQADO.Game_Board()#returns function AQADO.Game_Board 
      pygame.display.update()#Updates the pygame window 
      print("") 

     if randomNumber == 2 and counter == 1 and move != False: 
      redandBlackCounters[1] -= 140 
      call_Game_Board() 
      print("") 
     if randomNumber == 2 and counter == 2 and move != False: 
      redandBlackCounters[3] -= 140 
      call_Game_Board() 
      print("") 
     if randomNumber == 2 and counter == 3 and move != False: 
      redandBlackCounters[5] -= 140 
      call_Game_Board() 
      print("") 
     if randomNumber == 2 and counter == 4 and move != False: 
      redandBlackCounters[7] -= 140 
      call_Game_Board() 
      print("") 

     if randomNumber == 3 and counter == 1 and move != False: 
      redandBlackCounters[1] -= 210 
      call_Game_Board() 
      print("") 
     if randomNumber == 3 and counter == 2 and move != False: 
      redandBlackCounters[3] -= 210 
      call_Game_Board() 
      print("") 
     if randomNumber == 3 and counter == 3 and move != False: 
      redandBlackCounters[5] -= 210 
      call_Game_Board() 
      print("") 
     if randomNumber == 3 and counter == 4 and move != False: 
      redandBlackCounters[7] -= 210 
      call_Game_Board() 
      print("") 

     if randomNumber == 4 and counter == 1 and move != False: 
      redandBlackCounters[1] += 70 
      call_Game_Board() 
      print("") 
     if randomNumber == 4 and counter == 2 and move != False: 
      redandBlackCounters[3] += 70 
      call_Game_Board() 
      print("") 
     if randomNumber == 4 and counter == 3 and move != False: 
      redandBlackCounters[5] += 70 
      call_Game_Board() 
      print("") 
     if randomNumber == 4 and counter == 4 and move != False: 
      redandBlackCounters[7] += 70 
      call_Game_Board() 
      print("") 

    def safe_Move(): 
     safe = 0 
     if redandBlackCounters[1,3,5] != 735 or 435 and redandBlackCounters[1,3] == redandBlackCounters[5]: 
      safe = 1 
     if redandBlackCounters[1,3,7] != 735 or 435 and redandBlackCounters[1,3] == redandBlackCounters[7]: 
      safe = 2 
     if redandBlackCounters[5,7,1] != 735 or 435 and redandBlackCounters[5,7] == redandBlackCounters[1]: 
      safe = 3 
     if redandBlackCounters[5,7,3] != 735 or 435 and redandBlackCounters[5,7] == redandBlackCounters[3]: 
      safe = 4 

    def Game_Function(playerOne, playerTwo): 
     while True:#while True is equal to True 
      AQADO.Game_Board()#returns AQADO.Game_Board function 
      pygame.display.update()#Updates the pygame window 
      for event in pygame.event.get():#checks for events in the pygame window 
       if event.type == QUIT:#if event is quit 
        pygame.quit()#pygame is quit 
        sys.exit()#code is exited 
       dieRoll = input("Please input r to roll the die") 
       if dieRoll == "r":#If the key pressed is r 
        randomNumber = 1#random.randint(1,4)#random number between 1 and 4 is generated and set to variable randomNumber 
        #if randomNumber == 1: 
         #player_Information(playerInfo = 1, player = playerOne) 
        #if randomNumber == 2: 
         #player_Information(playerInfo = 2, player = playerOne) 
        #if randomNumber == 3: 
         #player_Information(playerInfo = 3, player = playerOne) 
        #if randomNumber == 4: 
         #player_Information(playerInfo = 4, player = playerOne) 
        counterInput = int(input("Which counter do you want to move 1 or 2?")) 
        if counterInput == "1": 
         AQADO.Counter_Move(redandBlackCounters, move, randomNumber, counter = 1) 
        if counterInput == "2": 
         AQADO.Counter_Move(redandBlackCounters, move, randomNumber, counter = 2) 
       dieRoll = input("Please input a to roll the die") 
       if dieRoll == "a": 
        randomNumber = 1 
        counterinput = int(input("Which counter do you want to move 3 or 4?")) 
        if counterInput == "3": 
         AQADO.Counter_Move(redandBlackCounters, move, randomNumber, counter = 3) 
        if counterInput == "4": 
         AQADO.Counter_Move(redandBlackCounters, move, randomNumber, counter = 4) 

def player_Information(playerInfo, player): #This function prints the value of the dice roll as well as the player's name, it parses the variables playerInfo 
    W = (255,255,255)                              #and player 
    diceInformation = ["rolled a 1, move one of your pieces 1 space nearer to FINISH", "rolled a 2, move on of your pieces 2 spaces nearer to FINISH", 
         "rolled a 3, move one of your oieces 3 spaces nearer to FINNISH", "rolled a 4, move one of your pieces 1 space back toward START"] 
    #Defines an array called diceInformation which stores the text which is blitted to the screen 
    if playerInfo == 1:#if player eqauls 11                      
     turnOne = (player, diceInformation[0])#turnOne is set to player, and index 0 of diceInformation 
    if playerInfo == 2:#if player eqauls 12 
     turnOne = (player, diceInformation[1])#turnOne is set to player, and index 1 of diceInformation 
    if playerInfo == 3:#if player eqauls 13 
     turnOne = (player, diceInformation[2])#turnOne is set to player, and index 2 of diceInformation 
    if playerInfo == 4:#if player eqauls 14 
     turnOne = (player, diceInformation[3])#turnOne is set to player, and index 3 of diceInformation 

    font = pygame.font.SysFont("arial", 20)#Sets the font and font size 
    turnOne = font.render(str(turnOne),True,W)#Sets what text is blitted to the screen an the colour of the text 
    DISPLAYSURF.blit(turnOne,(100, 800))#Sets the coordinates where the text is blitted and blits the code to the screen 
    pygame.display.update()#Updates the pygame window 
    pygame.time.wait(1000)#freezes the pygame window for 1000 miliseconds (1 second) 


#def safe_Space(safeSpace, redandBlackCounters):#Defines a function called safe_Space which is passed the variable safeSpace and array redandBlackCounters 
    #if safeSpace == 1:#if safe Space is equal to 1     
     #if redandBlackCounters[1] and redandBlackCounters[5] != 735 and redandBlackCounters[1] == 455 and redandBlackCounters[5] or redandBlackCounters[7] == 455: 
      #print("Safe") 
     #elif redandBlackCounters[1] and redandBlackCounters[5] != 735 and redandBlackCounters[1] == redandBlackCounters[5]: 
      #print("1") 
      #redandBlackCounters[5] = 735#blackCounterOneY is set to 735 
      #AQADO.call_Game_Board()#returns function call_Game_Board in the class AQADO 
     #elif redandBlackCounters[1] and redandBlackCounters[7] != 735 and redandBlackCounters[1] == redandBlackCounters[7]: 
      #print("2") 
      #blackCounterTwoY = 735#blackCounterTwoY is set to 735 
      #AQADO.call_Game_Board()#returns function call_Game_Board in the class AQADO 
    #if safeSpace == 2: 
     #if redandBlackCounters[1] and redandBlackCounters[5] != 735 and redandBlackCounters[1] == 455 and redandBlackCounters[5] or redandBlackCounters[7] == 455: 
      #print("Safe") 
     #if redandBlackCounters[1] and redandBlackCounters[5] != 735 and redandBlackCounters[1] == redandBlackCounters[5]: 
      #print("1") 
      #redandBlackCounters[1] = 735#redCounterOneY is set to 735 
      #AQADO.call_Game_Board()#returns function call_Game_Board in the class AQADO 
     #elif redandBlackCounters[1] and redandBlackCounters[7] != 735 and redandBlackCounters[1] == redandBlackCounters[7]: 
      #print("2") 
      #redandBlackCounters[3] = 735#redCounterTwoY is set to 735 
      #AQADO.call_Game_Board()#returns function call_Game_Board in the class AQADO 

def Menu():#Defines a function called Menu 
    menu = ["\nThis is AQADo", "1 - Enter player names", "2 - Play game"]#Defines an array called menu 
    menuLastItem = ["3 - Quit"]#Defines an array called menuLastItem 
    for items in menu:#Prints all the itmes in the array menu 
     print(items) 

    return(menuLastItem[0])#Returns the index 0 in menuLastItem 

################################################################## MAIN CODE # 

option = 0 #Sets the variable option to 0 
playerOne = 0 #Sets the variable playerOne to 0 
playerTwo = 0 #Sets the variable PlayerTwo to 0 
blackCounterOne = True 
redCounterOne = True 
playerTurn = 0 
counter = 0 
move =0 
redandBlackCounters = [120, 735, 250, 735, 560, 735, 690, 735] 
while option != 3:#When option is not 3 the while loop ends 
    menuTwo = ["Please input 1,2 or 3 ", "Please enter a valid data type, 1,2 or 3","\nYou have exited the game"]#Defines an array called menuTwo 
    menuSelectorItems = ["Please input player one's name ", "Please input player Two's name "]#Defines an array called menuSelectorItems 
    print(Menu())#The function Menu is returned 
    try:#Tries all of the inputs below for a keyboard interrupt 
     try: #Tries menuSelector for an input which is not 1,2 or 3 
      menuSelector = input(menuTwo[0])#Prints the string at index 0 in the array menuTwo 
     except:#If menuSelector does not equal 1,2 or 3 then the menu is printed again 
      print(menuTwo[1],option) 

     if menuSelector == "1":#If menuSelector equals 1 the players have to enter thier names 
      playerOneName = input(menuSelectorItems[0])#Prints the string at index 0 in the array menuSelectorItems 

      if playerOneName.isalnum():#If the input playerOneName equals alphnumeric then playerOne is set to playerOneName 
       playerOne = playerOneName 
      else: 
       playerOne = "Player One" 

      playerTwoName = input(menuSelectorItems[1])#Prints the string at index 1 in the array menuSelectorItems 

      if playerOneName.isalnum(): #If the input playerTwoName equals alphnumeric then playerTwo is set to playerTwoName 
       playerTwo = playerTwoName 
      else: 
       playerTwo = "Player Two" 

     if menuSelector == "2":#If menuSelector equals 2 the function AQADo is returned 
      if playerOne == 0:#If the playerOne equals 0 then playerOne is set to Player_One 
       playerOne = "Player One" 
      if playerTwo == 0: #If the playerTwo equals 0 then playerTwo is set to Player_Two 
       playerTwo = "Player Two" 
      AQADO.Game_Function(playerOne,playerTwo)#returns function AQADo in class AQADO and passes the variables playerOne and playerTwo 

     if menuSelector == "3": #If menuSelector equals 3 the code is exited 
      print(menuTwo[2])#Prints the string at index 2 in the array menuTwo 
      option = 3 #Sets the variable option to 3 
      pygame.quit()#Closes the pygame window 
      sys.exit()#Exits the code 

    except KeyboardInterrupt:#If there is a keyboard interrupt 
     print(menuTwo[2])#Prints the string at index 2 in the array menuTwo 
     pygame.quit()#Closes the pygame window 
     sys.exit()#Exits the code if there is a keyboard interrupt 
+0

См. [MCVE] (https://stackoverflow.com/help/mcve). – TidB

ответ

2

После проверки событий Pygame, Вы писали следующий код:

dieRoll = input("Please input r to roll the die") 

... которым останавливает программу до тех пор, пока что-то типа в консоль и нажмите Enter.

Как следствие, события («pygame.event.get()») больше не тянутся. Это заставляет вашу операционную систему думать, что программа нарушена. (В Windows окно становится белым, а курсор - песочными часами)

Я предлагаю использовать pygame.key -Модуль вместо консоли.

Edit:

В вашем случае, вы хотите, чтобы бросить кубик только раз на «кнопки-толчке», так что лучше использовать в pygame.event-модуль, чтобы получить ключ , Вот пример:

for event in pygame.event.get(): 
    if event.type == KEYDOWN and event.key == K_r: #If key "r" gets (not is) pressed 
     roll_die() 

Таким образом, "roll_die()" часть получает выполняется только один раз если нажать "R" -Key. В противном случае, с pygame.key-модулем, в каждом кадре нажата клавиша «r», ваш код будет снова выполнен (полезно в других ситуациях, конечно, но не здесь).

Почему это и как это работает, вы можете прочитать самостоятельно на страницах документа pygame.key и pygame.event. Это на самом деле довольно хорошо описано.

+0

Спасибо, попробуем его и сообщите, если он работает –

+0

Он работает! Мне просто нужно заставить мои счетчики двигаться, спасибо за помощь –

Смежные вопросы