이것은 Java 코스의 마지막 코스 디자인입니다. Java는 초보자이기 때문에 기술 전문가의 블로그를 언급했습니다. 여기서 감사를 표현하고 싶습니다.
의사 소통하고 배우려면 여기에 게시하십시오.
완전한 프로젝트 파일, 문서 및 실행 가능한 JAR 파일이 필요한 경우 주소 다운로드 : 링크를 열려면 클릭하십시오.
russianblocksgame.java
패키지 러시아 블록 게임; java.awt.*; import java.awt.event.*; import javax.swing.border.border; import javax.swing.border.etchedborder; /*** JFrame 클래스에서 상속 된 메인 게임 클래스는 게임의 글로벌 제어를 담당합니다. 1. GameCanvas Canvas 클래스의 인스턴스 개체, * 2. 현재 활성 블록 (RussiaBlock) 인스턴스를 보유하는 객체; 3. 현재 제어판 (ControlPanel) 인스턴스를 보유하는 객체; */ public class russiaBlocksgame은 Jframe {private static final long serialversionuid = -7333224439279674749L; / *** 채워진 각 행에 대해 계산되는 포인트 수*/ 공개 최종 정적 int per_line_score = 100; / *** 축적 후 업그레이드 할 수있는 포인트 수*/ public final static int per_level_score = per_line_score* 20; / *** 최대 시리즈는 레벨 10*/ public final static int max_level = 10입니다. / ** * 기본 시리즈는 2 */ public final static int default_level = 2입니다. 개인 Gamecanvas 캔버스; 개인 ersblock 블록; 개인 부울 연주 = 거짓; 개인 ControlPanel Ctrlpanel; // 메뉴를 초기화하는 메뉴 바 개인 jmenubar bar = new Jmenubar (); 개인 jmenu mgame = new Jmenu ( "게임"), McOntrol = new Jmenu ( "Control"), minfo = new Jmenu ( "도움말"); private jmenuitem minewgame = new jmenuitem ( "New Game"), misetBlockColor = new jmenuitem ( "Set Block Color ..."), misetbackColor = new jmenuitem ( "배경색 ..."), Miturnharder = new Jmenuitem ( "Evelate Defficent"), Mitheroneas ( "Retugtintinit (") New Jmenuitem ( "Exit"), miplay = new jmenuitem ( "start"), mipause = new jmenuitem ( "pause"), miresume = new jmenuitem ( "Resume"), mistop = new jmenuitem ( "게임 종료"), mirule = new jmenuit ( "게임 규칙")) / *** 창 메뉴 작성 및 설정*/ private void creatmenu () {bar.add (mgame); bar.add (McOntrol); bar.add (minfo); mgame.add (minewgame); mgame.addseparator (); // 수평 분할 라인 추가 mgame.add (misetBlockColor); mgame.add (misetBlockColor); mgame.addseparator (); // 수평 분할 라인 추가 mgame.add (miturnharder); mgame.add (miturneasier); mgame.addseparator (); // 수평 분할 라인 추가 mgame.add (miexit); McOntrol.add (Miplay); miplay.setenabled (true); McOntrol.add (mipause); mipause.setenabled (false); McOntrol.add (Miresume); miresume.setenabled (false); McOntrol.add (Mistop); mistop.setenabled (false); minfo.add (mirule); minfo.add (miauthor); setjmenubar (bar); minewgame.addactionListener (new ActionListener () {@override public void ActionPerformed (ActionEvent e) {stopGame (); reSet (); setLevel (default_level);}}); // 블록 색상을 설정합니다 MisetBlockColor.addactionListener (new ActionListener () {@override public void ActionPerformed (actionEvent e) {Color NewFrontColor = jcolorchooser.showdialog (RussiaBlocksGame.this, "SET THE BLOCK COLOR", cARVAS.GetBlockcolor ()); {canvas.setBlockColor (NewFrontColor); // 배경색 MisetBackColor.addactionListener (new ActionListener () {@override public void actionPerformed (actionEvent e) {color newbackcolor = jcolorchooser.showdialog (russiaBlocksgame.this, ", anget. (new backbas.)); Canvas.setbackgroundColor (NewbackColor); // 메뉴 표시 줄 "정보"의 기능을 정의하고 확인란이 나타납니다. miauthor.addactionListener (new ActionListener () {@override public void ActionPerformed (ActionEvent e) {joptionpane.showmessagedialog (null, "소프트웨어 엔지니어링 (4) 클래스/n3115005372/nyang yujie/n © eang yujie가 소유해야합니다. }); // 게임 규칙 설명 mirule.addactionListener (new ActionListener () {@override public void ActionPerformed (ActionEvent e) {joptionpane.showmessagedialog (NULL, "작은 제곱으로 구성된 다른 모양의 플레이트는 화면의 상단에서 상단에서 떨어져 있습니다. 이 수평 막대는 즉시 사라져서 새로운 플레이어가 나옵니다. // 난이도를 늘리면 miturnharder.addactionListener (new ActionListener () {@override public void actionPerformed (actionEvent e) {int curlevel = getLevel (); if (! cherlevel <max_level) {settlevel (curlevel + 1);}}); // miturneasier.addactionListener (new ActionListener () {@override public void actionPerformed (actionEvent e) {int curlevel = getLevel (); if (! playing && curlevel> 1) {settlevel (curlevel - 1)}}); // 종료 버튼 액션 응답 miexit.addactionListener (new ActionListener () {@override public void ActionPerformed (ActionEvent e) {System.Exit (0);}}); } / *** 메인 게임 클래스의 생성자 메소드* @param 제목 문자열, 창 제목* / public russiaBlocksGame (문자열 제목) {super (title); // 제목 setSize (500, 600)를 설정합니다. // 창 크기 설정 setLocationRelativeto (null); // 윈도우 센터를 설정하십시오 CreatemEnu (); 컨테이너 컨테이너 = getContentPane (); // 메뉴 바 컨테이너 생성 .SetLayout (New BorderLayout (6, 0)); // 창의 레이아웃 관리자를 설정 캔버스 = 새로운 GameCanvas (20, 15); // 새 게임 생성 캔버스 ctrlpanel = new ControlPanel (this); // 새 제어판 컨테이너를 만듭니다 .add (Canvas, BorderLayout.Center); // 캔버스 컨테이너 추가 (ctrlpanel, borderlayout.east); // 오른쪽에 제어판 추가 // 등록 창 이벤트. 닫기 버튼을 클릭하면 게임이 종료되고 시스템이 종료됩니다. AddWindowListener (새 WindowAdapter () {@override public void WindowClosing (windowevent we) {stopGame (); System.Exit (0);}}); // 창 크기에 따라 광장 크기를 자동으로 조정합니다. setvisible (true); canvas.adjust (); } /*** 게임 재설정* /public void reset () {// 캔버스를 재설정하고 제어판 ctrlpanel.setplaybuttonenable (true)을 재설정합니다. ctrlpanel.setPauseButtonenable (false); ctrlpanel.setPauseButtonLabel (true); ctrlpanel.setstopbuttonenable (false); ctrlpanel.setturnleveldownbuttonenable (true); ctrlpanel.setturnlevelupbuttonenable (true); miplay.setenabled (true); mipause.setenabled (false); miresume.setenabled (false); mistop.setenabled (false); ctrlpanel.reset (); canvas.reset (); } / *** 게임이 여전히 진행 중인지 결정** @return boolean, true- 여전히 실행 중입니다. 거짓 멈춤* / public boolean isplaying () {return playing; } / *** 현재 활성 블록을 가져옵니다** @return ersblock, 현재 활성 블록* / public ersblock getCurblock () {return block; } / *** 현재 캔버스를 가져옵니다** @return gamecanvas, 현재 캔버스에 대한 참조* / public gamecanvas getCanvas () {return canvas; } / *** 게임 시작* / public void playgame () {play (); ctrlpanel.setplaybuttonenable (false); ctrlpanel.setPauseButtonenable (true); ctrlpanel.setPauseButtonLabel (true); ctrlpanel.setstopbuttonenable (true); ctrlpanel.setturnleveldownbuttonenable (false); ctrlpanel.setturnlevelupbuttonenable (false); mistop.setenabled (true); Miturnharder.setenabled (false); miturneasier.setenabled (false); ctrlpanel.requestfocus (); // 제어판에 초점을 맞추십시오}/*** 게임 일시 정지*/public void pauseGame () {if (block! = null) {block.pauseMove (); } ctrlpanel.setplaybuttonenable (false); ctrlpanel.setPauseButtonLabel (false); ctrlpanel.setstopbuttonenable (true); miplay.setenabled (false); mipause.setenabled (false); miresume.setenabled (true); mistop.setenabled (true); } / *** 일시 정지 게임을 계속할 수있게하십시오* / public void resumegame () {if (block! = null) {block.resumemove (); } ctrlpanel.setplaybuttonenable (false); ctrlpanel.setPauseButtonenable (true); ctrlpanel.setPauseButtonLabel (true); mipause.setenabled (true); miresume.setenabled (false); ctrlpanel.requestfocus (); } / *** 사용자는 게임 중지* / public void stopgame () {재생 = false; if (block! = null) {block.stopmove (); } ctrlpanel.setplaybuttonenable (true); ctrlpanel.setPauseButtonenable (false); ctrlpanel.setPauseButtonLabel (true); ctrlpanel.setstopbuttonenable (false); ctrlpanel.setturnleveldownbuttonenable (true); ctrlpanel.setturnlevelupbuttonenable (true); miplay.setenabled (true); mipause.setenabled (false); miresume.setenabled (false); mistop.setenabled (false); Miturnharder.setenabled (true); miturneasier.setenabled (true); Reset (); // 캔버스 및 제어판 reset}/** * 플레이어가 설정 한 난이도를 얻으십시오 * * @return int, 게임 난이도 1-max_level */public int getlevel () {return ctrlpanel.getlevel (); } / ** * 사용자는 게임 난이도를 설정 * * @param 레벨 int, 게임 난이도 1-max_level * / public void setlevel (int level) {if (level <11 && level> 0) {ctrlpanel.panel.setlevel (level); }} / *** 게임 포인트 get** @return int, points* / public int getscore () {if (canvas! = null) {return canvas.getScore (); } 반환 0; } /*** 마지막 업그레이드 이후 게임 포인트를 얻습니다. 업그레이드 후이 지점은** @return int, ints*/ public int getscoreforLevelUpdate () {if (canvas! = null) {return canvas.getScoreForleVelUpDate (); } 반환 0; } / ** * 적분이 특정 값으로 축적 될 때, 한 번 업그레이드하면 * * @return boolean, true-update successe, false-update 실패 * / public boolean levelupdate () {int curlevel = getlevel (); if (curlevel <max_level) {setlevel (curlevel + 1); canvas.resetscoreforlevelupdate (); 진실을 반환하십시오. } false를 반환합니다. } / *** 게임 시작* / private void play () {reset (); 연주 = 참으로; 스레드 스레드 = 새 스레드 (new Game ()); // 게임 스레드를 시작 스레드를 시작합니다 .Start (); } / *** 게임이 끝났다고보고* / private void reportGameover () {new GameOverDialog (this, "tetris", "게임이 끝나고 점수는" + canvas.getScore ()); } /*** 런닝 가능한 인터페이스를 구현하는 한 라운드의 게임 프로세스. 라운드는 큰 루프입니다. 이 루프에서 100 밀리 초마다 게임의 현재 블록이 끝났는지 확인하십시오. 그렇지 않다면 * *는 계속 기다릴 것입니다. 그것이 끝에 있다면, 그것은 완전히 채워진 선이 있는지에 따라 다릅니다. 있으면 삭제하고 플레이어에게 점을 추가하고 새 전류 블록을 무작위로 생성하여 자동으로 떨어지게하십시오. * 새 블록이 생성되면 먼저 캔버스 상단의 선이 점유되었는지 확인하십시오. 그렇다면 게임 오버를 판단 할 수 있습니다. */ 개인 클래스 게임은 runnable {@override public void run () {int col = (int) (math.random () * (canvas.getCols () -3)); // int style의 위치를 무작위로 생성합니다 = ersblock.styles [(int) (int) (ath.random () * 7) [(int)] (Math.random ()); shape while (playing) {if (block! = null) {// 블록이 비어있다 if (block.isalive ()) {try {thread.currentthread (); Thread.sleep (500); } catch (InterruptedException IE) {ie.printstacktrace (); } 계속하다; }} checkfullline (); // (isgameover ()) {reportGameOver (); miplay.setenabled (true); mipause.setenabled (false); miresume.setenabled (false); mistop.setenabled (false); ctrlpanel.setplaybuttonenable (true); ctrlpanel.setPauseButtonLabel (false); ctrlpanel.setstopbuttonenable (false); 반품; } block = new ersblock (스타일, -1, col, getlevel (), 캔버스); block.start (); col = (int) (math.random () * (canvas.getCols () -3)); style = ersblock.styles [(int) (math.random () * 7)] [(int) (math.random () * 4); ctrlpanel.settipstyle (스타일); }} // 캔버스에 완전히 채워진 선이 있는지 확인하십시오. 하나가 있으면 공개 void checklline () {for (int i = 0; i <canvas.getrows (); i ++) {int row = -1; 부울 fulllinecolorbox = true; for (int j = 0; 부서지다; }} if (fulllinecolorbox) {row = i-; Canvas.removeline (행); }}} // 상단 행이 점유되었는지 여부에 따라 게임이 종료되었는지 판단합니다. //@return boolean, true-게임은 끝났습니다. 거짓 게임은 비공개 부울 isgameover () {for (int i = 0; i <canvas.getCols (); i ++) {ersbox box = canvas.getbox (0, i); if (box.iscolorbox ()) {return true; }} 거짓을 반환합니다. }} /*** 게임 오버 대화 상자를 정의합니다. */ @suppresswarnings ( "Serial") 개인 클래스 GameOverDialog는 JDialog Ampess ActionListener {Private JButton Agawtton, ExitButton; 개인 경계 국경 = 새로운 에칭 버더 (Etchedborder.Raised, Color.white, New Color (148, 145, 140)); public gameoverdialog (jframe 부모, 문자열 제목, 문자열 메시지) {super (부모, 제목, true); if (parent! = null) {setSize (240, 120); this.setLocationRelativeTo (부모); jpanel messagepanel = new jpanel (); MessagePanel.add (New Jlabel (메시지)); MessagePanel.setborder (테두리); 컨테이너 컨테이너 = this.getContentPane (); Container.SetLayout (New GridLayout (2, 0, 0, 10)); container.add (MessagePanel); jpanel choosepanel = 새로운 jpanel (); choosepanel.setlayout (New GridLayout (0, 2, 4, 0)); 컨테이너 .add (Choosepanel); Again Button = New JButton ( "다른 게임 플레이"); ExitButton = New Jbutton ( "Exit Game"); choosepanel.add (new jpanel (). add (acebutton)); choosepanel.add (new jpanel (). add (exitbutton)); Choosepanel.Setborder (테두리); } AgainButton.AdDactionListener (this); exitButton.AdDactionListener (this); this.set -Visible (true); } @override public void ActionPerformed (ActionEvent e) {if (e.getSource () == AgawButton) {this.setVisible (false); 다시 놓기(); } else if (e.getSource () == exitButton) {stopGame (); System.exit (0); }}}}gamecanvas.java
패키지 러시아 블록 게임; import java.awt.color; java.awt.graphics 가져 오기; import javax.swing.jpanel; import javax.swing.border.etchedborder; /*** Rows 수>* <열 수> 제곱 등급 인스턴스가있는 캔버스 클래스. JPANEL 클래스에서 상속. ersblock 스레드 클래스는 캔버스 클래스의 그리드 색상을 동적으로 변경합니다. 캔버스 클래스는 * ersblock 블록의 움직임을 반영하기 위해 그리드 색상을 점검하는 데 사용합니다. */ public class gamecanvas는 jpanel {private static final long serialversionuid = 6732901391026089276L; 개인 색상 백 컬러 = color.darkgray, frontcolor = color.white; 개인 int 행, cols, score = 0, scoreforLevelUpdate = 0; private ersbox [] [] 상자; 개인 int boxwidth, BoxHeight; / *** 캔버스 클래스의 생성자** @param 행 int, 캔버스 행의 행 수* @param cols int, 캔버스의 열 수와 열의 수는 캔버스가 가진 제곱의 수를 결정합니다*/ public gamecanvas (int rows, int cols) {this.rows = rows; this.cols = cols; Boxes = New Ersbox [행] [Cols]; for (int i = 0; i <box.length; i ++) {for (int J = 0; }} setBorder (New Etchedborder (Etchedborder.Raised, Color.White, New Color (148, 145, 140); this.backcolor. getbackgroundcolor () {return backcolor} /*** @param frontcolor* /public void setblockcolor (this.frontcolor = frontcolor)* @problockol (return color). * 캔버스에서 정사각형의 수를 얻으십시오* @return*/ public int getrows () {return rows}* @return int, Square의 열 수*/ public getcols () {return cols* @public int int int intcoer; } / *** 마지막 업그레이드 이후 포인트를 얻으십시오* @return int, 마지막 업그레이드 후 포인트* / public int getscoreforLevelUpdate () {return mac } / *** 특정 행과 열의 제곱 기준을 가져옵니다** @return 행 int, 제곱이 참조되는 행* @param col int, 제곱이 참조되는 행* @return ersbox, 행 col 열에서 제곱의 기준* / public ersbox getbox (int row, int col) {if (행 <0 || row> boxes.lengess.l 길이. 상자 [0]. i <box.length; int j = 0; J <boxes [i] .length; 창 크기에 따라 정사각형의 크기를 자동으로 조정하십시오* / public void adceld () {boxwidth = getsize (). width / cols; getsize (). row) {for (int i = row; i> 0; i-) {for (int j = 0; scoreforlevelupdate+= russiablocksgame.per_level_score; {상자 [J] .setColor (false)} retaint ();ControlPanel.java
패키지 러시아 블록 게임; java.awt.borderlayout import; import java.awt.color; java.awt.graphics 가져 오기; import java.awt.gridlayout; import java.awt.event.actionevent; import java.awt.event.actionListener; java.awt.event.componentAdapter import; java.awt.event.componentevent import; import java.awt.event.keyadapter; java.awt.event.keyevent를 가져 오기; import java.text.dateformat; import java.text.simpledateformat; import java.util.date; import javax.swing.jbutton; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jtextfield; import javax.swing.timer; import javax.swing.border.border; import javax.swing.border.etchedborder; /*** JPANEL에서 상속 된 제어판 클래스. 미리보기 창, 레벨, 스코어 및 제어 버튼이 배치됩니다. */ class ControlPanel은 JPANEL {private static final long serialversionUID = 3900659640646175724L; private jtextfield tflevel = new Jtextfield ( "" " + RussiaBlocksGame.default_level), tfscore = new Jtextfield ("0 "), tftime = new Jtextfield (" "); Private JBUTTON BTPLAY = NEW JBUTTON ( "Start"), BTPAUSE = New JBUTTON ( "PASAUS"), BTSTOP = NEW JBUTTON ( "END THE GAME"), BTTURNLEVELUP = NEW JBUTTON ( "난이도 증가"), BtturnLevelDown = New JBUTTON ( "난이도 감소"); 개인 jpanel pltip = new JPanel (New BorderLayout ()); 개인 Tippanel pltipblock = New Tippanel (); 개인 JPANEL PLINFO = NEW JPANEL (New GridLayout (4, 1)); 개인 JPANEL PLBUTTON = NEW JPANEL (New GridLayout (6, 1)); 개인 타이머 타이머; 개인 경계 국경 = 새로운 에칭 버더 (Etchedborder.Raised, Color.white, New Color (148, 145, 140)); /*** 제어판 클래스의 생성자** @param 게임 ersblocksgame, ersblocksgame 클래스의 인스턴스 참조는 ersblocksgame 클래스의 동작을 직접 제어하는 데 편리합니다. */ Public ControlPanel (Final RussiaBlocksGame 게임) {SetLayout (New GridLayout (3, 1, 0, 2)); pltip.add (New Jlabel ( "Next Square"), BorderLayout.north); // 구성 요소 추가 pltip.add (pltipblock); pltip.setborder (테두리); plinfo.add (New Jlabel ( "난이도 계수")); plinfo.add (tflevel); plinfo.add (New Jlabel ( "score")); plinfo.add (tfscore); plinfo.setborder (테두리); plbutton.add (btplay); btplay.setenabled (true); plbutton.add (btpause); btpause.setenabled (false); plbutton.add (btstop); btstop.setenabled (false); plbutton.add (btturnlevelup); plbutton.add (btturnleveldown); plbutton.add (tftime); Plbutton.Setborder (Border); tflevel.seteditable (false); tfscore.seteditable (false); tftime.seteditable (false); 추가 (pltip); 추가 (plinfo); 추가 (plbutton); addKeylistener (new keyadapter () {@override public void keypressed (keyevent ke) {if (! game.isplaying ()) {return;} ersblock block = game.getCurblock (); switch (ke.getKeyCode ()) {case keyEvent.vk_down : break.movedown (); Block.case.moveleft (); btplay.addactionListener (new ActionListener () {// 게임 시작 @override public void ActionPerformed (ActionEvent Ae) {game.playGame ();}}); btpause.addactionListener (new ActionListener () {// 게임을 일시 중지합니다 @override public void ActionPerformed (ActionEvent ae) {if (btpause.getText (). equals ( "pause")) {game.pausegame ()} else {game.resumegame ()}}); btstop.addactionListener (new ActionListener () {// 게임 중지 @override public void ActionPerformed (ActionEvent ae) {game.stopgame ();}}); btturnlevelup.addactionListener (new ActionListener () {// 난이도 증가 @override public void ActionPerformed (ActionEvent ae) {try {int level = integer.parseint (tflevel.getText ()); if (level <RusiAblocksGame.max_level) {tflevel.settext ( "" "); catch (numberformatexception e) {} requestFocus (); btturnleveldown.addactionListener (new ActionListener () {// 게임 난이도 감소 @override public void actionPerformed (actionEvent ae) {try {int level = integer.parseint (tflevel.getText ()); if (level> 1) {tflevel.settext ( "}}}); } requestFocus (); AddComponentListener (new componentAdapter () {@override public void componentresized (componentEvent ce) {pltipblock.adjust ();}}); TIMER = NEW TIMER (1000, New ActionListener () {@Override public void ActionPerformed (ActionEvent AE) {DateFormat Format = New SimpledateFormat ( "Time : HH : HH : MM : SS"); // 시스템은 시간 날짜를 얻습니다. game.getScore (); int scoreforlevelupdate = // if (sc timer.start (); } / *** 사전 디스플레이 창의 스타일 설정** @param style int, ersblock class* / public void settipstyle (int style)의 28 값에 해당하는 {pltipblock.setstyle (style); } /*** 사용자가 설정 한 게임 레벨을 가져옵니다. * * @return int, 난이도, 1-esblocksgame.max_level */ public int getlevel () {int level = 0; try {level = integer.parseint (tflevel.getText ()); } catch (numberformatexception e) {} 리턴 레벨; } /*** 사용자가 게임 난이도를 수정하도록합니다. * * @param 레벨 수정 게임 난이도 수준 */ public void setlevel (int level) {if (level> 0 && level <11) {tflevel.settext ( "" + level); }} /*** "시작"버튼의 상태를 설정합니다. */ public void setplaybuttonenable (boolean enable) {btplay.setenabled (enable); } public void setPauseButtonenable (boolean enable) {btpause.setenabled (enable); } public void setPauseButtonLabel (boolean pause) {btpause.settext (pause? "pause": "계속"); } public void setStOpButtonenable (boolean enable) {btstop.setenabled (enable); . } public void setturnleveldownbuttonenable (boolean enable) {btturnleveldown.setenabled (enable); } / *** 제어판 재설정* / public void reset () {tfscore.settext ( "0"); pltipblock.setstyle (0); } / *** tippanel* / public void adceld () {pltipblock.adjust (); } /*** 구현 세부 정보 사전 디스플레이 창의 클래스* /public class tippanel tippanel 확장 jpanel {// tippanel은 다음 블록의 모양을 표시하는 데 사용됩니다. 개인 색상 백 컬러 = color.darkgray, frontcolor = color.white; private ersbox [] [] boxes = new ersbox [esblock.boxes_rows] [esblock.boxes_cols]; 개인 int 스타일, Boxwidth, BoxHeight; 개인 부울 = 거짓; / *** 사전 디스플레이 창 클래스 생성자*/ public tippanel () {for (int i = 0; i <box.length; i ++) {for (int j = 0; }}} / *** 사전 디스플레이 창의 블록 스타일을 설정** @param style int, ersblock 클래스의 28 값에 해당합니다* / public void setstyle (int style) {this.style = style; 리 페인트 (); } /*** jcomponent 클래스의 함수를 덮어 쓰고 구성 요소를 그리십시오. * * @param g 그래픽 장치 환경 */ @override public void paintcomponent (그래픽 g) {super.paintcomponent (g); if (! istiled) {조정 (); } int key = 0x8000; for (int i = 0; i <box.length; i ++) {for (int j = 0; G. 세트 컬러 (색); g.fill3drect (j * boxwidth, i * boxHeight, boxwidth, boxHeight, true); 키 >> = 1; }}} / *** g 창의 크기에 따라 정사각형 크기를 자동으로 조정하십시오* / public void Adjub () {boxwidth = getsize (). width / ersblock.boxes_cols; BoxHeight = getsize (). 높이 / ersblock.boxes_rows; istiled = true; }}}ersbox.java
패키지 러시아 블록 게임; java.awt.dimension import; / *** 제곱 클래스는 블록을 구성하는 기본 요소이며 자체 색상을 사용하여 블록의 모양을 나타냅니다*/ public class ersbox는 클로닝 가능 {private boolean iscolor; 개인 차원 크기 = 새로운 차원 (); / ** * 제곱 등급의 생성자, * * @param iscolor 전경 색상을 사용 하여이 제곱의 진정한 전경 색상, 거짓 사용 배경 색상 */ public ersbox (부울 iscolor) {this.iscolor = iscolor; } / ***이 제곱은 전경 색상으로 표현되어 있습니다** @return boolean, True는 전경 색상으로 표현되며, 배경색으로 표현 된 거짓* / public boolean iscolorbox () {return iscolor; } / ** * 정사각형의 색상을 설정하십시오. * * @param iscolor boolean, 전경 색상으로 표현 된 진실, 배경색으로 표현 된 거짓 * / public void setcolor (부울 iscolor) {this.iscolor = iscolor; } / ***이 정사각형의 크기를 가져옵니다** @return dimension, square의 크기* / public dimension getsize () {return size; } / ** * 정사각형의 크기 * * @param 크기 치수, 정사각형의 크기 * / public void setsize (치수 크기) {this.size = size; } / *** 객체의 객체 클론 ()을 덮어 쓰고 클론을 구현하십시오** @return 객체, 클론 결과* / @override public Object Clone () {Object Clone = null; try {clone = super.clone (); } catch (예외) {ex.printstacktrace (); } 복제 복제; }}ersblock.java
패키지 러시아 블록 게임; / *** 스레드 클래스 (스레드)에서 상속 된 블록 클래스 (스레드)는 4 × 4 블록 (ERSBOX), 움직임 제어, 낙하, 블록의 변형 등으로 구성됩니다.*/ class ERSBLOCK 스레드 확장 스레드 {/ *** 블록이 차지하는 행의 수는 4 줄*/ public final int boxes_rows = 4; / *** 블록이 차지하는 열의 수는 4 개의 열*/ public final static int boxes_cols = 4; / *** 마지막 단계 사이의 속도 차이를 거의 두 배로 피하기 위해 업그레이드 변경을 부드럽게하는 요인*/ public final static int level_flatness_gene = 3; / ** * 각 행에 대해 두 개의 유사한 수준의 블록 (밀리 초)의 차이는 무엇입니까? / ** * 블록 스타일의 수는 7 */ public final static int block_kind_number = 7; / ** * 각 스타일의 반전 상태 유형은 4 */ public final static int block_status_number = 4입니다. /*** 7 개 각각 7 개 모델*/public final static int [] [] 스타일 = {// 총 28 개 주 {0x0f00, 0x4444, 0x0f00, 0x4444}, // 긴 스트라이프의 4 개 상태 {0x04e0, 0x0464, 0x00e4, 0x04c4}, // 4 States}, // 4 State} {0x4620, 0x6c00, 0x4620, 0x6c00}, // 4 개의 리버스 z 유형 {0x2640, 0xc600, 0x2640, 0xc600}, // z 유형의 4 개 상태 {0x6220, 0x1700, 0x2230, 0x0740}, // 4 States of 7 Type의 4 개 상태 {0x6440, 0x0e20, 0x44c0, 0x8e00}, // 역 7 유형의 4 개의 상태 {0x0660, 0x0660, 0x0660, 0x0660}, // 4 개의 블록 상태}; 개인 Gamecanvas 캔버스; private ersbox [] [] boxes = new ersbox [boxes_rows] [boxes_cols]; 개인 int 스타일, y, x, 레벨; 개인 부울 일시 정지 = 거짓, 움직이는 = true; / *** 생성자, 특정 블록을 생성합니다** @param 스타일은 28 개의 스타일 값* @param y 시작 위치 중 하나에 해당하는 블록의 스타일을 생성합니다.* @param x start position의 좌표 라인* @param x start position, canvas* @param 레벨 게임 레벨의 왼쪽 상단 코너의 좌표 열, @param 캔버보의 낙하 속도*/ public a artblock (int x, int x). int level, gamecanvas canvas) {this.style = style; this.y = y; this.x = x; this.level = 레벨; this.canvas = 캔버스; int key = 0x8000; for (int i = 0; i <boxes.length; i ++) {for (int j = 0; 상자 [i] [J] = New Ersbox (iscolor); 키 >> = 1; } } 표시하다(); } / *** 스레드 클래스의 run () 함수는 블록이 다시 떨어질 수 없을 때까지 블록을 덮고 삭제합니다* / @override public void run () {while (moving) {sleep (tree_levels_degress_time* (russiaBlocksGame.Max_Level -level + level_flAtness_gene)); } catch (InterruptedException IE) {ie.printstacktrace (); } // 후속 이동은 100 밀리 초의 대기 중 (! PASUSING) {moving = (moveto (y + 1, x) && move); }}}} / ** * 블록은 하나의 그리드를 왼쪽으로 이동 * / public void moveleft () {moveto (y, x -1); } / ** * 블록은 하나의 그리드를 오른쪽으로 이동 * / public void moveright () {moveto (y, x + 1); } / ** * 블록은 하나의 그리드를 오른쪽으로 이동 * / public void mizoun () {moveto (y + 1, x); } / *** 블록 변형* / public void turnnext () {for (int i = 0; i <block_kind_number; i ++) {for (int j = 0; Turnto (Newstyle); 반품; }}}} public void startMove () {pausing = false; 이동 = 참; } /** * Pause the whereabouts of the block, corresponding to the game pause*/ public void pauseMove() { pausing = true; // moving = false; } /** * Continue the whereabouts of the block, corresponding to the game continue*/ public void resumeMove() { pausing = false; moving = true; } /** * Stop the whereabouts of the block, corresponding to the game pause*/ public void stopMove() { pausing = false; moving = false; } /** * Remove the current block from the corresponding position of the canvas and will not be reflected until the next time you repaint the canvas*/ private void erase() { for (int i = 0; i < boxes.length; i++) { for (int j = 0; j < boxes[i].length; j++) { if (boxes[i][j].isColorBox()) { ErsBox box = canvas.getBox(i + y, j + x); if (box == null) { continue; } box.setColor(false); } } } } } /** * Let the current block be placed in the corresponding position of the canvas, and you have to wait until the next time you repaint the canvas*/ private void display() { for (int i = 0; i < boxes.length; i++) { for (int j = 0; j < boxes[i].length; j++) { if (boxes[i][j].isColorBox()) { ErsBox box = canvas.getBox(i + y, j + x); if (box == null) { continue; } box.setColor(true); } } } } } /** * Can the current block be moved to the location specified by newRow/newCol* * @param newRow int, the destination line* @param newCol int, destination column * @return boolean, true-can move, false-cannot move*/ public boolean isMoveAble(int newRow, int newCol) { erase(); for (int i = 0; i < boxes.length; i++) { for (int j = 0; j < boxes[i].length; j++) { if (boxes[i][j].isColorBox()) { ErsBox box = canvas.getBox(i + newRow, j + newCol); if (box == null || (box.isColorBox())) { display(); return false; } } } } 표시하다(); return true; } /** * Move the current block to the location specified by newRow/newCol* * @param newRow int, destination row* @param newCol int, destination column* @return boolean, true-move successfully, false-move failed*/ private synchronized boolean moveTo(int newRow, int newCol) { if (!isMoveAble(newRow, newCol) || !moving) { return false; } erase(); y = newRow; x = newCol; 표시하다(); canvas.repaint(); return true; } /** * Can the current block become the block style specified by newStyle, mainly considering the boundary and being blocked by other blocks and cannot be moved* * @param newSytle int, the block style you want to change corresponds to one of the 28 values of STYLES* @return boolean, true-can change, false-cannot change*/ private boolean isTurnAble(int newStyle) { int key = 0x8000; 지우다(); for (int i = 0; i < boxes.length; i++) { for (int j = 0; j < boxes[i].length; j++) { if ((newStyle & key) != 0) { ErsBox box = canvas.getBox(i + y, j + x); if (box == null || (box.isColorBox())) { display(); return false; } } key >>= 1; } } 표시하다(); return true; } /** * Turn the current block into the block style specified by newStyle* * @param newStyle int, the block style you want to change, corresponding to one of the 28 values of STYLES* @return true-change succeeds, false-change fails*/ private boolean turnTo(int newStyle) { if (!isTurnAble(newStyle) || !moving) { return false; } erase(); int key = 0x8000; for (int i = 0; i < boxes.length; i++) { for (int j = 0; j < boxes[i].length; j++) { boolean isColor = ((newStyle & key) != 0); boxes[i][j].setColor(isColor); key >>= 1; } } style = newStyle; 표시하다(); canvas.repaint(); return true; }}Main.java
package RussiaBlocksGame; /** * Program entry function* * @param args String[], accompanied by command line parameters*/ public class Main { public static void main(String[] args) { new RussiaBlocksGame("Tetris: Yang Yujie"); }} The above is all the content of this article. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.