在Pygame event.get()循环中使用缩进事件

时间:2016-05-01 17:47:37

标签: python-2.7 loops events pygame

我再次遇到Pygame事件的麻烦(Pygame seems to "avoid" loop

我似乎无法在事件循环中检测到缩进条件:

for event in pygame.event.get(): 
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    if event.type == MOUSEBUTTONDOWN:
        print 'mb'
        if event.type == KEYDOWN: #NOT DETECTED
            print 'keydown'
            if event.key == K_e:
                print 'key_e_pressed'

    if event.type == variables.set_ennemies_dest:
        print 'moves

我确保我正在使用event.type和event.key,我的缩进是正确的。我从那里删除了所有代码,并用print语句替换它,以确保问题不是来自其他地方。

非常欢迎任何帮助!

如果上面看起来很好,这是我的完整游戏循环:

import pygame, sys, variables
from pygame.locals import *
from classes import *
from instances import *
from functions import *

pygame.init()
clock = pygame.time.Clock()
pygame.time.set_timer(variables.set_ennemies_dest, 10000) #for ennemi movement
#game loop    
while True:
    clock.tick(60)
    variables.screen.fill((0,0,0)) #make background black
    for event in pygame.event.get(): #setting up quit
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == MOUSEBUTTONDOWN:
            get_offset(hero,event) # sets the movement offset for the iteration
            print 'mb'
            if event.type == KEYDOWN:
                print 'keydown'
                if event.key == K_e:
                    for i in variables.item_list:
                        i.use(hero)

        if event.type == variables.set_ennemies_dest:
            print 'moves'
            for o in variables.char_list: 
                if isinstance(o, Ranger): #moves characters
                    o.set_rand_dest()



    for o in variables.char_list: 
        if isinstance(o, Ranger): #moves characters
            o.move()
    #offset checks
    group_collision_check(variables.all_sprites_list,hero) #edits the offest based on hero collision
    group_offset(variables.building_list) #new building position using offset
    group_push(variables.item_list,hero)
    scroll_map.offset() #offsets grass background map
    group_offset(variables.ennemi_list)

    variables.screen.blit(scroll_map.image, scroll_map.rect) # blits the grass map to new pos

    variables.building_list.draw(variables.screen) #blits the buildings to new pos

    #blitting characters
    variables.screen.blit(hero.image, hero.rect) #blits hero to screen center
    for o in variables.ennemi_list:
        variables.screen.blit(o.image, o.rect)

    variables.item_list.draw(variables.screen)  

    pygame.display.update()
    variables.offset_time -= 1 #removes on step from the offset counter to keep track of when
    #offset needs to be reset to 0, i.e. position is reached

1 个答案:

答案 0 :(得分:1)

import java.util.ArrayList;
import java.util.Scanner;
import java.lang.*;


public class ContactDatabase
{
    private ArrayList<Contact> contacts;        // ArrayList of contact
    private static final int QUIT = 0;          // Menu choices
    private static final int ADD = 1;
    private static final int LISTALL = 2;
    private static final int SEARCH = 3;
    private static final int DELETE = 4;
/**
* Default constructor - make a new ArrayList object with parameter type Contact
*/
ContactDatabase()
{
     contacts = new ArrayList<Contact>();
}


/**
* inputContact inputs contact information from the keyboard.
* It then stores this new contact in the contacts ArrayList.
*/
public void inputContact()
{
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter first and last names: ");
    String firstName = input.next();
    String lastName = input.nextLine();
    /*  while (input != null || input != " ") {
            //firstLast = input.nextLine();
        }
    contacts.add(firstName);
    contacts.add(lastName);
    */
    System.out.println("Now enter " + firstName + " " + lastName + "\'s email address: ");
    String emailAddress = input.nextLine();

        if (emailAddress.indexOf('@') < 0) {
            System.out.println("No '@' in email address\n Please enter a correct email address: ");
        }

        if (emailAddress.indexOf('.') < 0) {
            System.out.println("No '.' in email address!");
        } else {
            //emailAddress = input.nextLine();
            System.out.println("Email address accepted!");
        }

    System.out.println("Please enter " + firstName + " " + lastName + "\'s phone number: ");
    String phoneNumber = input.nextLine();

        boolean number = false;
        int n = 0;
        while (n < phoneNumber.length()) {
            char c = phoneNumber.charAt(n);

            if (!(c >= '0' && c <= '9'))
                number = false;
                n++;
        }
        number = true;

        phoneNumber = phoneNumber.replaceAll("\\-","");
        phoneNumber = phoneNumber.replaceAll("\\(","");
        phoneNumber = phoneNumber.replaceAll("\\)","");
    System.out.println("Phone number accepted.");

    Contact newContact = new Contact(firstName, lastName, phoneNumber, emailAddress);
    contacts.add(newContact);
    System.out.println(firstName + "" + lastName + " has been added as a contact.");
}

/**
* displayAll iterates through the ArrayList of contacts and outputs each one
* to the screen.
*/
public void displayAll()
{   

    System.out.println("Your contacts are: ");
    for (Contact c : contacts)
    {   
        if (contacts.isEmpty()) {
            System.out.println("No contacts.");
        } else {
            System.out.println(c);
        }
    }   
}

/**
* displayMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and outputs each one
* to the screen if the contact information contains the keyword.
*/
public void displayMatch()
{

    System.out.println("Enter keyword: ");
    Scanner input = new Scanner(System.in);
    String in = input.next();

        for (Contact c : contacts)
        {
            if (in.equals(c)) {
                System.out.println(c);
            } else {
                System.out.println("No matches.");
            }
        }   
}

/**
* deleteMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and asks the user
* if the contact should be deleted, if the contact information contains the keyword.
*/
public void deleteMatch()
{

    System.out.println("Enter keyword: ");
    Scanner input = new Scanner(System.in);
    String in = input.next();

    for (Contact c : contacts) 
    {
        if (in.equals(c)) {
            System.out.println("Should " + c + " be deleted? (type 'YES' or 'Y')");
            //in = input.nextLine();

            boolean done = false;
            while (! done)
            {   
                if (in.equalsIgnoreCase("yes") || in.equalsIgnoreCase("y")) {
                    contacts.remove(c);
                } else {
                    done = true;
                }
            }   

        } else {
            System.out.println("No matches!");
        }
    }
}

// Main class
public static void main(String[] args)
{
    ContactDatabase cdb = new ContactDatabase();
    Scanner scan = new Scanner(System.in);
    int choice = ADD;

    // Main menu
    while (choice != QUIT)
    {
        System.out.println();
        System.out.println("Choose from the following:");
        System.out.println("0) Quit");
        System.out.println("1) Add new contact");
        System.out.println("2) List all contacts");
        System.out.println("3) Search contacts by keyword and display");
        System.out.println("4) Search contacts by keyword and remove");
        choice = scan.nextInt();
        switch (choice)
        {
            case ADD: cdb.inputContact();
                        break;
            case LISTALL: cdb.displayAll();
                        break;
            case SEARCH: cdb.displayMatch();
                        break;
            case DELETE: cdb.deleteMatch();
                        break;
        }
    }
}

/**
 * The inner class, Contact, stores the details for a single contact.  
 *  There is no error checking on any of the input.  Whatever string is 
 *  passed in for a given attribute is accepted.  
 */
class Contact
{
   private String first, last, phone, email;

   /**
    * Constructors.
    */
   public Contact()
   {
   }

   public Contact(String first, String last, String phone, String email)
   {
      this.first = first;
      this.last = last;
      this.phone = phone;
      this.email = email;
   }

   /*
    * Accessor Methods
    */

   public String getFirst()
   {
      return first;
   }

   public String getLast()
   {
      return last;
   }

   public String getPhone()
   {
      return phone;
   }

   public String getEmail()
   {
      return email;
   }

   /* 
    * Mutator Methods
    */
   public void setFirst(String first)
   {
      this.first = first;
   }

   public void setLast(String last)
   {
      this.last = last;
   }

   public void setPhone(String phone)
   {
      this.phone = phone;
   }

   public void setEmail(String em)
   {
      this.email = em;
   }



   /*
    * Return all fields concatenated into a string
    */
   public String toString()
   {
      return last + ", " + first + ". " + phone + ", " + email;
   }


   public boolean equals(Object otherObject)
   {
      if (otherObject ==null)
      {
         return false;
      }
      else if (getClass() != otherObject.getClass())
      {
         return false;
      }
      else
      {
         Contact otherContact = (Contact)otherObject;
         return (first.equals(otherContact.first) && 
               last.equals(otherContact.last)&&
               phone.equals(otherContact.phone)&&
               email.equals(otherContact.email));
      }
   }

} // end inner class, Contact
} // end class, ContactDatabase

为您的代码添加了评论,以解决您遇到的问题。在一个坚果壳中,你的一些if语句永远不会像你现在的结构一样真实。

编辑:

event.get()列表中的每个事件都将是一个单独的实体。所以它不能同时是一个mousebuttondown事件和一个keydown事件。每个人都将成为他们自己的活动。如果你想测试这两个条件,你可能不得不依靠bool切换来测试两个事件何时发生。像这样:

for event in pygame.event.get(): 
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    if event.type == MOUSEBUTTONDOWN:
        print 'mb'
        if event.type == KEYDOWN: # This will NEVER be true. If the event is a mouse button down event, it will never be a keydown event. Solution? Unindent!
            print 'keydown'
            if event.key == K_e: # which means this can also never be true.
                print 'key_e_pressed'

    if event.type == variables.set_ennemies_dest: # have a feeling this is a typo "ennemies dest"
        print 'moves