Java + Guava 16 (a goiaba não é super necessária, mas tornou algumas coisas um pouco menos chatas de se escrever).
Tudo bem, você deveria estar trabalhando? Que tal um programa que realmente escreve código Java real, que realmente compila (embora não faça muito).
É difícil demonstrar a animação, mas este programa grava um programa Java usando o dicionário padrão (250 palavras comuns em inglês) ou um arquivo delimitado por nova linha (usado como argumento de linha de comando) e digita-o no console, um caractere de cada vez. em velocidades aparentemente humanas . Certifique-se de executá-lo você mesmo, porque este post não faz justiça. Quando termina, aguarda 1 minuto, depois imprime muitas linhas em branco no console e inicia novamente. Tentei escrevê-lo para tornar vários parâmetros razoavelmente ajustáveis.
Além disso, normalmente eu colocaria isso em mais de um arquivo, mas para facilitar a execução, misturei todas as classes.
package org.stackoverflow.ppcg;
import java.io.*;
import java.util.*;
import com.google.common.base.CaseFormat;
import com.google.common.base.Converter;
import com.google.common.collect.Lists;
public class CodeGenerator {
public static final Converter<String, String> TOUPPER =
CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);
public static final Converter<String, String> TOLOWER =
CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
public static final String[] TYPES = new String[]{
"int", "long", "double", "String"
};
public static final List<String> DEFAULT_LIST = Arrays.asList(new String[]{
"the", "and", "for", "you", "say", "but", "his", "not", "she", "can",
"who", "get", "her", "all", "one", "out", "see", "him", "now", "how",
"its", "our", "two", "way", "new", "day", "use", "man", "one", "her",
"any", "may", "try", "ask", "too", "own", "out", "put", "old", "why",
"let", "big", "few", "run", "off", "all", "lot", "eye", "job", "far",
"have", "that", "with", "this", "they", "from", "that", "what", "make", "know",
"will", "time", "year", "when", "them", "some", "take", "into", "just", "your",
"come", "than", "like", "then", "more", "want", "look", "also", "more", "find",
"here", "give", "many", "well", "only", "tell", "very", "even", "back", "good",
"life", "work", "down", "call", "over", "last", "need", "feel", "when", "high",
"their", "would", "about", "there", "think", "which", "could", "other", "these", "first",
"thing", "those", "woman", "child", "there", "after", "world", "still", "three", "state",
"never", "leave", "while", "great", "group", "begin", "where", "every", "start", "might",
"about", "place", "again", "where", "right", "small", "night", "point", "today", "bring",
"large", "under", "water", "write", "money", "story", "young", "month", "right", "study",
"people", "should", "school", "become", "really", "family", "system", "during", "number", "always",
"happen", "before", "mother", "though", "little", "around", "friend", "father", "member", "almost",
"change", "minute", "social", "follow", "around", "parent", "create", "others", "office", "health",
"person", "within", "result", "change", "reason", "before", "moment", "enough", "across", "second",
"toward", "policy", "appear", "market", "expect", "nation", "course", "behind", "remain", "effect",
"because", "through", "between", "another", "student", "country", "problem", "against", "company", "program",
"believe", "without", "million", "provide", "service", "however", "include", "several", "nothing", "whether",
"already", "history", "morning", "himself", "teacher", "process", "college", "someone", "suggest", "control",
"perhaps", "require", "finally", "explain", "develop", "federal", "receive", "society", "because", "special",
"support", "project", "produce", "picture", "product", "patient", "certain", "support", "century", "culture"
});
private static final int CLASS_NAME_LENGTH = 2;
private final WordList wordList;
private final Appendable out;
private final Random r = new Random();
private CodeGenerator(WordList wordList, Appendable out) {
this.wordList = wordList;
this.out = out;
}
public static void main(String... args) throws Exception {
List<?> wordSource = getWords(args);
WordList list = new WordList(wordSource);
SleepingAppendable out = new SleepingAppendable(System.out);
CodeGenerator generator = new CodeGenerator(list, out);
while(!Thread.interrupted()) {
generator.generate();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
break;
}
out.setSleeping(false);
for(int i = 0; i < 100; i++) {
out.append(System.lineSeparator());
}
out.setSleeping(true);
}
}
private static List<?> getWords(String[] args) {
if(args.length > 0) {
try {
return getListFromFile(args[0]);
} catch(IOException e) { }
}
return DEFAULT_LIST;
}
private static List<Object> getListFromFile(String string) throws IOException {
List<Object> newList = Lists.newArrayList();
File f = new File(string);
Scanner s = new Scanner(f);
while(s.hasNext()) {
newList.add(s.nextLine());
}
return newList;
}
private void generate() throws IOException {
String className = beginClass();
List<Field> finalFields = generateFields(true);
printFields(finalFields);
out.append(System.lineSeparator());
List<Field> mutableFields = generateFields(false);
printFields(mutableFields);
out.append(System.lineSeparator());
printConstructor(className, finalFields);
printGetters(finalFields);
printGetters(mutableFields);
printSetters(mutableFields);
endClass();
}
private void printGetters(List<Field> fields) throws IOException {
for(Field f : fields) {
out.append(System.lineSeparator());
f.printGetter(out);
}
}
private void printSetters(List<Field> fields) throws IOException {
for(Field f : fields) {
out.append(System.lineSeparator());
f.printSetter(out);
}
}
private void printConstructor(String className, List<Field> finalFields) throws IOException {
out.append("\tpublic ").append(className).append('(');
printArgs(finalFields);
out.append(") {").append(System.lineSeparator());
for(Field f : finalFields) {
f.printAssignment(out);
}
out.append("\t}").append(System.lineSeparator());
}
private void printArgs(List<Field> finalFields) throws IOException {
if(finalFields.size() == 0) return;
Iterator<Field> iter = finalFields.iterator();
while(true) {
Field next = iter.next();
next.printTypeAndName(out);
if(!iter.hasNext()) break;
out.append(", ");
}
}
private List<Field> generateFields(boolean isfinal) {
int numFields = r.nextInt(3) + 2;
List<Field> newFields = Lists.newArrayListWithCapacity(numFields);
for(int i = 0; i < numFields; i++) {
String type = TYPES[r.nextInt(4)];
newFields.add(new Field(type, wordList.makeLower(r.nextInt(2) + 1), isfinal));
}
return newFields;
}
private void printFields(List<Field> finalFields) throws IOException {
for(Field f : finalFields) {
f.printFieldDeclaration(out);
}
}
private String beginClass() throws IOException {
out.append("public class ");
String className = wordList.nextClassName(CLASS_NAME_LENGTH);
out.append(className).append(" {").append(System.lineSeparator());
return className;
}
private void endClass() throws IOException {
out.append("}");
}
private static class WordList {
private final Random r = new Random();
private final List<?> source;
private WordList(List<?> source) {
this.source = source;
}
private String makeUpper(int length) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
sb.append(randomWord());
}
return sb.toString();
}
private String makeLower(int length) {
return TOLOWER.convert(makeUpper(length));
}
private String randomWord() {
int sourceIndex = r.nextInt(source.size());
return TOUPPER.convert(source.get(sourceIndex).toString().toLowerCase());
}
public String nextClassName(int length) {
return makeUpper(length);
}
}
private static class Field {
private final String type;
private final String fieldName;
private final boolean isfinal;
Field(String type, String fieldName, boolean isfinal) {
this.type = type;
this.fieldName = fieldName;
this.isfinal = isfinal;
}
void printFieldDeclaration(Appendable appendable) throws IOException {
appendable.append("\tprivate ");
if(isfinal) appendable.append("final ");
printTypeAndName(appendable);
appendable.append(';').append(System.lineSeparator());
}
void printTypeAndName(Appendable appendable) throws IOException {
appendable.append(type).append(' ').append(fieldName);
}
void printGetter(Appendable appendable) throws IOException {
appendable.append("\tpublic ");
appendable.append(type).append(" get").append(TOUPPER.convert(fieldName));
appendable.append("() {").append(System.lineSeparator());
appendable.append("\t\treturn ").append(fieldName).append(';');
appendable.append(System.lineSeparator()).append("\t}").append(System.lineSeparator());
}
void printSetter(Appendable appendable) throws IOException {
appendable.append("\tpublic void set");
appendable.append(TOUPPER.convert(fieldName));
appendable.append("(").append(type).append(' ').append(fieldName);
appendable.append(") {").append(System.lineSeparator());
printAssignment(appendable);
appendable.append("\t}").append(System.lineSeparator());
}
void printAssignment(Appendable appendable) throws IOException {
appendable.append("\t\tthis.").append(fieldName).append(" = ").append(fieldName);
appendable.append(';').append(System.lineSeparator());
}
}
private static class SleepingAppendable implements Appendable {
private Random r = new Random();
private Appendable backing;
private boolean sleeping = true;
public SleepingAppendable(Appendable backing) {
this.backing = backing;
}
@Override
public Appendable append(CharSequence csq) throws IOException {
return append(csq, 0, csq.length());
}
@Override
public Appendable append(CharSequence csq, int start, int end)
throws IOException {
for(int i = start; i < end; i++) {
append(csq.charAt(i));
}
sleep(100, 300);
return this;
}
@Override
public Appendable append(char c) throws IOException {
sleep(170, 80);
backing.append(c);
return this;
}
private void sleep(int base, int variation) {
if(!sleeping) return;
try {
Thread.sleep((long) (r.nextInt(80) + 70));
} catch (InterruptedException e) {
}
}
public boolean isSleeping() {
return sleeping;
}
public void setSleeping(boolean sleeping) {
this.sleeping = sleeping;
}
}
}
Exemplo de saída do programa (apenas um programa)
public class GetGroup {
private final double thoughRight;
private final double socialYear;
private final double manOne;
private final int appear;
private double man;
private double comeHis;
private double certain;
public GetGroup(double thoughRight, double socialYear, double manOne, int appear) {
this.thoughRight = thoughRight;
this.socialYear = socialYear;
this.manOne = manOne;
this.appear = appear;
}
public double getThoughRight() {
return thoughRight;
}
public double getSocialYear() {
return socialYear;
}
public double getManOne() {
return manOne;
}
public int getAppear() {
return appear;
}
public double getMan() {
return man;
}
public double getComeHis() {
return comeHis;
}
public double getCertain() {
return certain;
}
public void setMan(double man) {
this.man = man;
}
public void setComeHis(double comeHis) {
this.comeHis = comeHis;
}
public void setCertain(double certain) {
this.certain = certain;
}
}
Outra saída de amostra:
public class TryControl {
private final int over;
private final double thatState;
private final long jobInto;
private final long canPut;
private int policy;
private int neverWhile;
public TryControl(int over, double thatState, long jobInto, long canPut) {
this.over = over;
this.thatState = thatState;
this.jobInto = jobInto;
this.canPut = canPut;
}
public int getOver() {
return over;
}
public double getThatState() {
return thatState;
}
public long getJobInto() {
return jobInto;
}
public long getCanPut() {
return canPut;
}
public int getPolicy() {
return policy;
}
public int getNeverWhile() {
return neverWhile;
}
public void setPolicy(int policy) {
this.policy = policy;
}
public void setNeverWhile(int neverWhile) {
this.neverWhile = neverWhile;
}
}