2016-11-03 6 views
-1

저는 자바로 셀 진화 시뮬레이션을 해왔습니다. 모든 사람들이 알기에, 저는 초보자/중급 자바 프로그래머입니다. 나는 거의 모든 기본 사항을 알고 있으며 약간은 알지만 코드를 처음부터 작성하는 기술은별로 없다. 여기에있는 코드는 대략 온라인에서 찾은 소스를 기반으로하고 있으며, 필자 만의 접촉과 온라인에서 찾은 다른 조각을 추가했습니다. 화면 깜박임을 제외하고는 정상적으로 작동하는 것 같습니다. 그것은 repaint()가 깜박일 때마다, 아마도 지우고 다시 그릴 때마다 나타납니다. 실제로 볼 수없는 것을 만듭니다. 내 코드에는 오류가 없습니다. 애플릿을 처음 사용하기 때문에 더 좋은 방법이 있다면 알려 주시기 바랍니다. 화면이 깜박 거리지 않게하려면 어떻게합니까? 그것을 방지하기 위해 이미지를 버퍼링하는 쉬운 방법이 있습니까? 여기에 애플릿자바 애플릿 paint() 메서드가 깜박임

/* <!-- Defines the applet element used by the appletviewer. --> 
<applet code='CellLife.java' width='1920' height='1080'></applet> */ 

import java.applet.Applet; 
import java.awt.Event; 
import java.awt.Graphics; 
import java.util.Enumeration; 
import java.util.Vector; 

public class CellLife extends Applet implements Runnable { 
// ======================================================================== 
// VARIABLES 
// ======================================================================== 

// Data 

/** Thread object for CellLife applet */ 
private Thread m_cellLife = null; 

// Static constants 

/** 
* the maximum number of creatures in the world. When the number of 
* creatures alive drops below half this, a new one is created to bring the 
* numbers back up. 
*/ 
protected static final int MAX_CREATURES = 60; 

// Data 

/** 
* A list of the creatures currently alive. Stores CLCreature references. 
*/ 
protected Vector creatures; 

/** The world is a rectangle from (0,0) to (limit.x,limit,y) */ 
protected CL2dVector limit; 

/** 
* The number of creatures that have been born since the simulation started 
*/ 
protected long generations; 

/** A test creature controllable by the user to allow response testing */ 
private CLCreature testCreature; 

/** space-partitioning structure to speed collision detection */ 
protected CLBuckets buckets; 

// ======================================================================== 
// METHODS 
// ======================================================================== 

public CellLife() { 
    creatures = new Vector(); 
    limit = new CL2dVector(500.0F, 500.0F); 
    generations = 0; 

    // initilaize our bucket structure 
    float bucketScale = CLCell.RADIUS; // could stretch to root-two times 
             // this 
    buckets = new CLBuckets(bucketScale, (int) Math.ceil(limit.x/bucketScale), (int) Math.ceil(limit.y/bucketScale)); 
} 

public String getAppletInfo() { 
    return "Name: Cell Evolution\r\n" + "Author: Josh Marchand\r\n" + "Made in Eclipse"; 
} 

// first time initialazion 
public void init() { 
    resize((int) limit.x, (int) limit.y); 

    for (int i = 0; i < MAX_CREATURES; i++) { 
     CLCreature new_creature = new CLCreature(); 
     new_creature.InitSimple(limit, buckets); 
     creatures.addElement(new_creature); 
    } 
} 

public void destroy() { 
    // TODO: Place applet cleanup code here 
} 

public void paint(Graphics g) { 
    g.drawString("No. creatures: " + creatures.size(), 0, 11); 
    g.drawString("Births: " + generations, 0, 22); 

    // draw cells 
    for (int i = 0; i < creatures.size(); i++) { 
     ((CLCreature) creatures.elementAt(i)).Draw(g); 
    } 

    // DEBUG: also indicate the contents of the buckets 
    // buckets.Draw(g); 

    // get all creatures to do their stuff 
    CLCreature creature; 
    for (int i = 0; i < creatures.size(); i++) { 

     creature = (CLCreature) creatures.elementAt(i); 

     if (creature.DoTimeStep(g, buckets, limit) && creatures.size() < MAX_CREATURES) { 
      // inherit new creature from current 
      CLCreature newCreature = new CLCreature(); 
      newCreature.InheritFrom(creature, buckets, limit); 
      creatures.addElement(newCreature); 
      generations++; 
     } 
    } 

    // delete the ones that died doing it 
    for (Enumeration e = creatures.elements(); e.hasMoreElements();) { 
     creature = (CLCreature) e.nextElement(); 
     if (creature.hasDied) creatures.removeElement(creature); 
    } 

    // breed nwe creatures if pop. is low 
    if (creatures.size() < MAX_CREATURES/2) { 
     // just add one for now,fix later 
     CLCreature newCreature = new CLCreature(); 
     newCreature.InheritFrom((CLCreature) creatures.elementAt((int) Math.random() * creatures.size()), buckets, limit); 
     creatures.addElement(newCreature); 
     generations++; 
    } 

} 

public void start() { 
    if (m_cellLife == null) { 
     m_cellLife = new Thread(this); 
     m_cellLife.start(); 
    } 
    // TODO: place any additional startup code here 
} 

public void stop() { 
    if (m_cellLife != null) { 
     m_cellLife.stop(); 
     m_cellLife = null; 
    } 
} 

public void run() { 
    while (true) { 
     try { 
      repaint(); 

      // quick nap here to allow user interface to catch up 
      Thread.sleep(100); 
     } catch (InterruptedException e) { 
      stop(); 
     } 
    } 
} 

public boolean mouseDown(Event e, int x, int y) { 
    // create a single celled creature at specific loc 
    testCreature = new CLCreature(); 
    testCreature.rootCell.location.x = x; 
    testCreature.rootCell.location.y = y; 
    testCreature.rootCell.type = CLGene.RED; 
    creatures.addElement(testCreature); 
    buckets.PutCell(testCreature.rootCell); 
    return true; 
} 

public boolean mouseDrag(Event e, int x, int y) { 
    testCreature.rootCell.location.x = x; 
    testCreature.rootCell.location.y = y; 
    return true; 
} 

public boolean mouseUp(Event evt, int x, int y) { 
    creatures.removeElement(testCreature); 
    buckets.RemoveCell(testCreature.rootCell); 
    return true; 
} 
} 
당신이 도움을 너무 많이 모두 감사합니다, 나는 내 "noobiness"매우 유감을 그리는 클래스이다, 나는 나 자신을 가르치기 위해 내 최선을 다하고 있어요!

답변

0

이중 버퍼링이라는 기술을 사용하는 것이 좋습니다. 여기서는 이미지에 바인딩 된 오프 스크린 그래픽 객체를 만들고 그 위에 모든 그림을 수행 한 다음 결과를 화면에 페인트합니다. here 이미지에서 그래픽을 만드는 방법을 쉽게 찾을 수 있습니다. 보다 완전한 샘플은 here입니다.

+0

고맙습니다. 그것은 완벽하게 작동하고 아직 응용 프로그램에 지체하지 않습니다. 다행스럽게도, 매우 작은 창으로 작업하고 있는데, 큰 이미지로 작업하는 경우이 문제가 발생할 수 있습니다. 매우 큰 이미지를 끊임없이 변화시키지 않는다면 애플릿이 뒤떨어 질까? –

+0

@JoshMarchand 더블 버퍼링은 때때로 약간의 성능을 제거하지만, 오늘날의 하드웨어에서는 문제가되지 않습니다. 성능 문제가 발생하면 다른 곳에 있습니다. – Durandal