该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
我写的一个很简单的字母游戏,要求增加存档的功能,保存文件在本地,要能够开始新游戏也能继续之前的游戏,请问具体要怎么做?
我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LetterGame {
static int frameWidth =600,frameHeight =768;
public static void main(String[] args) {
JFrame frame = new JFrame();
//frame.getContentPane().setBackground(Color.BLACK);
frame.setSize( frameWidth, frameHeight);
MyPanel panel = new MyPanel();
frame.add(panel);
frame.addKeyListener(panel);
panel.addKeyListener(panel);
Thread t = new Thread(panel) ;
t.start() ;
frame.add(panel);
frame.setVisible(true);
frame.setResizable(false);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
class MyPanel extends JPanel implements Runnable,KeyListener{
int score=1000;
int x[] = new int[10];
int y[] = new int[10];
char c[] = new char[10];
public MyPanel(){
for(int i = 0; i < 10; i++){
c[i] = (char)(Math.random() * 26 + 97);
x[i] = (int)(Math.random() * LetterGame.frameWidth);
y[i] = (int)(Math.random() * LetterGame.frameHeight*0.5);
}
}
public void paint(Graphics g){
super.paint(g);
setBackground(Color.ORANGE);
g.setFont(new Font("Tahoma", Font.BOLD, 50));
g.setColor(Color.WHITE);
for(int i = 0; i < 10; i++)
g.drawString(new Character(c[i]).toString(),x[i], y[i]) ;
g.setColor(Color.RED);
g.setFont(new Font("Tahoma", Font.ITALIC, 20));
g.drawString("YOUR SCORE:"+score, 10, 30);
}
@Override
public void run() {
while(true){
try{
for(int i = 0; i < 10; i++){
y[i]++;
if(y[i] > LetterGame.frameHeight)
score -= 100;
if(y[i] > LetterGame.frameHeight){
x[i] = (int)(Math.random() * LetterGame.frameWidth);
y[i] = 0;
c[i] = (char)(Math.random() * 26 + 97);
}
}
Thread.sleep(30);
}catch(Exception e){};
repaint();
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0) {
char inputChar = arg0.getKeyChar();
int maxY = -1, maxIndex = -1;
for(int i = 0; i < 10; i++){
if(c[i] == inputChar){
if(y[i] > maxY){
maxY = y[i];
maxIndex = i;
}
}
}
if(maxIndex != -1){
c[maxIndex] = (char)(Math.random() * 26 + 97);
x[maxIndex] = (int)(Math.random() * LetterGame.frameWidth);
y[maxIndex] = 0;
score += 10;
}
else
score -= 100;
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
谢谢各位大神了,明天两节实验课就要写完检查,但是文件的操作我们还没讲多少,现在我一点都不知道要怎么才能实现这个存档功能,搜了很久也没明白...