summaryrefslogtreecommitdiff
path: root/jeu-test/Lemmini/0.84/src/Game/Core.java
blob: 65fbb2b4f4d555a0a1696f77fd9febebeee924c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package Game;
import java.awt.Component;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import Extract.Extract;
import Extract.ExtractException;
import GUI.LegalDialog;
import Tools.Props;
import Tools.ToolBox;

/*
 * Copyright 2009 Volker Oth
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Well, this started as some kind of core class to collect all global stuff
 * Now lots of the functionality moved to GameController.
 * Would need some cleaning up, maybe remove the whole thing?
 * @author Volker Oth
 */
public class Core {
	/** The revision string for resource compatibility - not necessarily the version number */
	private final static String REVISION = "0.80";
	/** name of the ini file */
	private final static String INI_NAME = "lemmings.ini";
	/** extensions accepted for level files in file dialog */
	public final static String[] LEVEL_EXTENSIONS = {"ini", "lvl"};
	/** extensions accepted for replay files in file dialog */
	public final static String[] REPLAY_EXTENSIONS = {"rpl"};

	/** program properties */
	public static Props programProps;
	/** path of (extracted) resources */
	public static String resourcePath;
	/** current player */
	public static Player player;

	/** parent component (main frame) */
	private static Component cmp;
	/** name of program properties file */
	private static String programPropsFileStr;
	/** name of player properties file */
	private static String playerPropsFileStr;
	/** player properties */
	private static Props playerProps;
	/** list of all players */
	private static ArrayList<String> players;

	/**
	 * Initialize some core elements.
	 * @param frame parent frame
	 * @param isWebstartApp true if this was started via Webstart, false otherwise
	 * @throws LemmException
	 */
	public static void init(final JFrame frame, final boolean isWebstartApp) throws LemmException  {
		// get ini path
		if (isWebstartApp) {
			programPropsFileStr = ToolBox.exchangeSeparators(System.getProperty("user.home"));
			programPropsFileStr = ToolBox.addSeparator(programPropsFileStr);
		} else {
			String s = frame.getClass().getName().replace('.','/') + ".class";
			URL url = frame.getClass().getClassLoader().getResource(s);
			int pos;
			try {
				programPropsFileStr = URLDecoder.decode(url.getPath(),"UTF-8");
			} catch (UnsupportedEncodingException ex) {};
			// special handling for JAR
			if (( (pos=programPropsFileStr.toLowerCase().indexOf("file:")) != -1))
				programPropsFileStr = programPropsFileStr.substring(pos+5);
			if ( (pos=programPropsFileStr.toLowerCase().indexOf(s.toLowerCase())) != -1)
				programPropsFileStr = programPropsFileStr.substring(0,pos);

			/** @todo doesn't work if JAR is renamed...
			 *  Maybe it would be a better idea to search only for ".JAR" and then
			 *  for the first path separator...
			 */

			s = (frame.getClass().getName().replace('.','/') + ".jar").toLowerCase();
			if ( (pos=programPropsFileStr.toLowerCase().indexOf(s)) != -1)
				programPropsFileStr = programPropsFileStr.substring(0,pos);
		}
		programPropsFileStr += INI_NAME;
		// read main ini file
		programProps = new Props();

		if (!programProps.load(programPropsFileStr)) {// might exist or not - if not, it's created
			LegalDialog ld = new LegalDialog(null,true);
			ld.setVisible(true);
			if (!ld.isOk())
				throw new LemmException("User abort");
		}

		resourcePath = programProps.get("resourcePath", "");
		String sourcePath = programProps.get("sourcePath", "");
		String rev = programProps.get("revision", "");
		GameController.setMusicOn(programProps.get("music", false));
		GameController.setSoundOn(programProps.get("sound", true));
		double gain;
		gain = programProps.get("musicGain", 1.0);
		GameController.setMusicGain(gain);
		gain = programProps.get("soundGain", 1.0);
		GameController.setSoundGain(gain);
		GameController.setAdvancedSelect(programProps.get("advancedSelect", true));
		if (resourcePath.length()==0 || !REVISION.equalsIgnoreCase(rev)) {
			// extract resources
			try {
				Extract.extract(null, sourcePath, resourcePath, null, "patch");
				resourcePath = Extract.getResourcePath();
				programProps.set("resourcePath", ToolBox.addSeparator(Extract.getResourcePath()));
				programProps.set("sourcePath", ToolBox.addSeparator(Extract.getSourcePath()));
				programProps.set("revision", REVISION);
				programProps.save(programPropsFileStr);
			} catch (ExtractException ex) {
				programProps.set("resourcePath", ToolBox.addSeparator(Extract.getResourcePath()));
				programProps.set("sourcePath", ToolBox.addSeparator(Extract.getSourcePath()));
				programProps.save(programPropsFileStr);
				throw new LemmException("Ressource extraction failed\n"+ex.getMessage());
			}
		}
		System.gc(); // force garbage collection here before the game starts

		// read player names
		playerPropsFileStr = Core.resourcePath+"players.ini";
		playerProps = new Props();
		playerProps.load(playerPropsFileStr);
		String defaultPlayer = playerProps.get("defaultPlayer", "default");
		players = new ArrayList<String>();
		for (int idx=0; true; idx++) {
			String p = playerProps.get("player_"+Integer.toString(idx), "");
			if (p.length() == 0)
				break;
			players.add(p);
		}
		if (players.size() == 0) {
			// no players yet, establish default player
			players.add("default");
			Core.playerProps.set("player_0", "default");
		}
		player = new Player(defaultPlayer);


		cmp = frame;
	}

	/**
	 * Get parent component (main frame).
	 * @return parent component
	 */
	public static Component getCmp() {
		return cmp;
	}

	/**
	 * Get String to resource in resource path.
	 * @param fname file name (without path)
	 * @return absolute path to resource
	 */
	public static String findResource(final String fname) {
		return resourcePath+fname;
	}

	/**
	 * Store program properties.
	 */
	public static void saveProgramProps() {
		programProps.save(programPropsFileStr);
		playerProps.set("defaultPlayer", Core.player.getName());
		playerProps.save(playerPropsFileStr);
		player.store();
	}

	/**
	 * Output error message box in case of a missing resource.
	 * @param rsrc name missing of resource.
	 */
	public static void resourceError(final String rsrc) {
		String out = "The resource "+rsrc+" is missing\n" +
		"Please restart to extract all resources.";
		JOptionPane.showMessageDialog(null,out,"Error",JOptionPane.ERROR_MESSAGE);
		// invalidate resources
		programProps.set("revision", "invalid");
		programProps.save(programPropsFileStr);
		System.exit(1);
	}

	/**
	 * Load an image from the resource path.
	 * @param tracker media tracker
	 * @param fName file name
	 * @return Image
	 * @throws ResourceException
	 */
	public static Image loadImage(final MediaTracker tracker, final String fName) throws ResourceException {
		String fileLoc = findResource(fName);
		if (fileLoc == null)
			return null;
		return loadImage(tracker, fileLoc, false);
	}

	/**
	 * Load an image from either the resource path or from inside the JAR (or the directory of the main class).
	 * @param tracker media tracker
	 * @param fName file name
	 * @param jar true: load from the jar/class path, false: load from resource path
	 * @return Image
	 * @throws ResourceException
	 */
	private static Image loadImage(final MediaTracker tracker, final String fName, final boolean jar) throws ResourceException {
		Image image;
		if (jar)
			image = Toolkit.getDefaultToolkit().createImage(ToolBox.findFile(fName));
		else
			image = Toolkit.getDefaultToolkit().createImage(fName);
		if (image != null) {
			tracker.addImage(image, 0);
			try {
				tracker.waitForID(0);
				if (tracker.isErrorAny()) {
					image = null;
				}
			} catch (Exception ex) {
				image = null;
			}
		}
		if (image == null)
			throw new ResourceException(fName);
		return image;
	}

	/**
	 * Load an image from the resource path.
	 * @param fname file name
	 * @return Image
	 * @throws ResourceException
	 */
	public static Image loadImage(final String fname) throws ResourceException {
		MediaTracker tracker = new MediaTracker(Core.getCmp());
		Image img = loadImage(tracker, fname);
		if (img == null)
			throw new ResourceException(fname);
		return img;
	}

	/**
	 * Load an image from inside the JAR or the directory of the main class.
	 * @param fname
	 * @return Image
	 * @throws ResourceException
	 */
	public static Image loadImageJar(final String fname) throws ResourceException {
		MediaTracker tracker = new MediaTracker(Core.getCmp());
		Image img = loadImage(tracker, fname, true);
		if (img == null)
			throw new ResourceException(fname);
		return img;
	}

	/**
	 * Get player name via index.
	 * @param idx player index
	 * @return player name
	 */
	public static String getPlayer(final int idx) {
		return players.get(idx);
	}

	/**
	 * Get number of players.
	 * @return number of player.
	 */
	public static int getPlayerNum() {
		if (players == null)
			return 0;
		return players.size();
	}

	/**
	 * Reset list of players.
	 */
	public static void clearPlayers() {
		players.clear();
		playerProps.clear();
	}

	/**
	 * Add player.
	 * @param name player name
	 */
	public static void addPlayer(final String name) {
		players.add(name);
		playerProps.set("player_"+(players.size()-1), name);
	}
}