.ניתן להשתמש בחומרים לצורך הוראה בלבד לא ניתן לפרסם את החומרים או לעשות בהם כל שימוש מסחרי ללא קבלת אישור מראש מצוות הפיתוח Arkenoid Game הצעה לתרגיל מסכם יאנה זמוסטיאנו:פיתוח using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Y_Game { class Program { static void Main(string[] args) { int pgia = 5, x=40, y=24,i,j,score=0; Ball B=new Ball(x, y);; Racket K=new Racket(35);; Console.ResetColor(); Console.Clear(); ElementS e=new ElementS(); for (y = 5; y <= 10; y = y + 5) { for (i = 0, x = 3; i < 13; i++, x += 6) for (j = 0; j < 3; j++) { Element e1; e1 = new Element(x + j, y); e.Add(e1); } } Game_Screen(); e.ElementSDraw();Racket.KereshReDraw(K); bool Escape = false; while ((!Escape) && (pgia > 0)) { Console.SetCursorPosition(20, 1); Console.ForegroundColor = ConsoleColor.Red; Console.BackgroundColor = ConsoleColor.Green; Console.Write("You have " + pgia + " chances "); Console.SetCursorPosition(60, 1); Console.Write("Your score " + score); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Ball.ballReDraw(B); System.Threading.Thread.Sleep(70); Ball.ballReDraw(B); System.Threading.Thread.Sleep(30); Ball.ballMove(B); Check_status(ref pgia,B,K); Check_pgia(ref score, B, e); if (Console.KeyAvailable) { ConsoleKeyInfo KeyInfo = Console.ReadKey(true); switch (KeyInfo.Key.ToString()) { case "LeftArrow": Racket.KereshMove(K, -1);break; case "RightArrow": Racket.KereshMove(K, 1);break; case "Escape": Escape = true; break; } Racket.KereshReDraw(K); } } Finish_Game(); } private static void Check_pgia(ref int score, Ball B, ElementS e) { for (int i = 0; i < 20; i++) { bool f = e.Check(B); if (f) { score += 100; e.ElementSDraw(); } } } public static void Check_status(ref int pgia,Ball B,Racket K) { if (B.GetY() == 24) if (!((B.GetX() >= K.GetPos()) && (B.GetX() <= K.GetPos() + 11))) pgia--; else Racket.KereshReDraw(K); } public static void Game_Screen() { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.SetCursorPosition(30, 10); Console.Write("You have 5 times to loose your ball."); Console.SetCursorPosition(30, 12); Console.Write("You can use the arrow to move the keresh."); Console.SetCursorPosition(30, 14); Console.Write("Press <Esc> to quit. "); Console.SetCursorPosition(30, 16); Console.Write("Press any key to start game... "); Console.ReadKey(); Console.Clear(); Console.BackgroundColor = ConsoleColor.Green; for (int i=0;i<80;i++) { Console.SetCursorPosition(i,1); Console.WriteLine(" "); } for (int i=2;i<=25;i++) { Console.SetCursorPosition(0,i); Console.WriteLine(" "); Console.SetCursorPosition(79,i); Console.WriteLine(" "); } Console.BackgroundColor = ConsoleColor.Black; } public static void Finish_Game() { Console.ResetColor(); Console.Clear(); Console.BackgroundColor = ConsoleColor.Cyan; for (int j = 10; j < 15; j++) for (int i = 20; i <= 60; i++) { Console.SetCursorPosition(i, j); Console.WriteLine(" "); } Console.BackgroundColor = ConsoleColor.Black; Console.SetCursorPosition(28, 12); Console.WriteLine("G A M E Console.ReadKey(); } } } O V E R ! ! !"); Racket namespace Y_Game { class Racket { private int Pos; private int direction; private int oldPos; public Racket(int x) { this.Pos = x; this.direction = 1; this.oldPos = this.Pos; } public int GetPos() { return this.Pos; } public int Getdirection() { return this.direction; } public int GetoldPos() { return this.oldPos; } //==================================== public void setPos(int pos) { this.Pos = pos; } public void setdirection(int dx) { this.direction = dx; } public void setoldPos(int oldPos) { this.oldPos = oldPos; } private void KereshDraw(int x, string Action) { Console.SetCursorPosition(x, 25); if (Action == "draw") { Console.ForegroundColor = ConsoleColor.Cyan; Console.BackgroundColor = ConsoleColor.Cyan; Console.Write("==========="); //11 char Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; } else Console.Write(" "); } public static void KereshMove(Racket K, int dX) { K.setoldPos(K.GetPos()); if (dX == 1 && (K.GetPos() + dX) < Console.BufferWidth - 14 || dX == -1 && (K.GetPos() + dX) >= 3 ) K.setPos(K.GetPos() + dX * 3); } public static void KereshReDraw(Racket K) { K.KereshDraw(K.GetoldPos(), "erase"); K.KereshDraw(K.GetPos(), "draw"); } } } Keresh namespace Y_Game { class Keresh { private int Pos; private int direction; private int oldPos; public Keresh(int x) { this.Pos = x; this.direction = 1; this.oldPos = this.Pos; } public int GetPos() { return this.Pos; } public int Getdirection() { return this.direction; } public int GetoldPos() { return this.oldPos; } //==================================== public void setPos(int pos) { this.Pos = pos; } public void setdirection(int dx) { this.direction = dx; } public void setoldPos(int oldPos) { this.oldPos = oldPos; } private void KereshDraw(int x, string Action) { Console.SetCursorPosition(x, 25); if (Action == "draw") { Console.ForegroundColor = ConsoleColor.Cyan; Console.BackgroundColor = ConsoleColor.Cyan; Console.Write("==========="); //11 char Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; } else Console.Write(" "); } public static void KereshMove(Keresh K, int dX) { K.setoldPos(K.GetPos()); if (dX == 1 && (K.GetPos() + dX) < Console.BufferWidth - 14 || dX == -1 && (K.GetPos() + dX) >= 3 ) K.setPos(K.GetPos() + dX * 3); } public static void KereshReDraw(Keresh K) { K.KereshDraw(K.GetoldPos(), "erase"); K.KereshDraw(K.GetPos(), "draw"); } } } Ball namespace Y_Game { class Ball { private int X; private int Y; private int directionX; private int directionY; private int oldX; private int oldY; public Ball(int X, int Y) { this.X = X; this.Y = Y; this.directionX = 1; this.directionY = 1; this.oldX = X; this.oldY = Y; } public int GetX() { return this.X; } public int GetY() { return this.Y; } public int GetDirectionX() { return this.directionX; } public int GetDirectionY() { return this.directionY; } public int GetOldX() { return this.oldX; } public int GetOldY() { return this.oldY; } //==================================== public void setX(int x) { this.X = x; } public void setY(int y) { this.Y = y; } public void setDirectionX(int dx) { this.directionX = dx; ; } public void setDirectionY(int dy) { this.directionY = dy; } public void setOldX(int ox) { this.oldX = ox; ; } public void setOldY(int oy) { this.oldY = oy; } //==================================== private void ballDraw(Ball B, string Action) { if (Action == "draw" ) { Console.SetCursorPosition(B.GetX(), B.GetY()); Console.Write("O"); } else { Console.SetCursorPosition(B.GetOldX(), B.GetOldY()); Console.Write(" "); } } public static void ballMove(Ball B) { B.setOldX(B.GetX()); B.setOldY(B.GetY()); B.setX(B.GetX() + B.GetDirectionX()); B.setY(B.GetY() + B.GetDirectionY()); if (B.GetX() >= Console.BufferWidth - 2) B.setDirectionX(-1) ; else if (B.GetX() == 2) B.setDirectionX(1); if (B.GetY() >= 24) B.setDirectionY(-1); else if (B.GetY() == 2) B.setDirectionY(1); } public static void ballReDraw(Ball B) { B.ballDraw(B, "erase"); B.ballDraw(B, "draw"); } } } Element namespace Y_Game { class Element { private int x; private int y; //private static int cy=0; //private ConsoleColor Color; private bool f; //private static int cx = 5; public Element(int x,int y) { this.x = x; this.y = y; // this.Color = ConsoleColor.DarkYellow; this.f = true; } public int GetX() { return this.x; } public int GetY() { return this.y; } public bool Getf() { return this.f; } public void Setf(bool x) { this.f=x; } } } ElementS namespace Y_Game { class ElementS { private Element[] array; private static int x = 0; public ElementS() { array = new Element[200]; } public void Add(Element e) { array[x] = e; x++; } public void ElementSDraw() { for (int i = 0; i < 78; i++) { if (array[i].Getf() == true) { Console.SetCursorPosition(array[i].GetX(), array[i].GetY()); Console.ForegroundColor = ConsoleColor.Magenta; Console.BackgroundColor = ConsoleColor.Magenta; Console.Write((char)(1)); } else { Console.SetCursorPosition(array[i].GetX(), array[i].GetY()); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Black; Console.Write(" "); } } Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Black; } internal bool Check(Ball B) { bool f = false; for (int i = 0; i < 77; i++) { if (B.GetX() == array[i].GetX() && B.GetY() == array[i].GetY()) { f = true; array[i].Setf(false); if (i == 0) { array[0].Setf(false); array[1].Setf(false); array[2].Setf(false); } if (i>1 && i<=76 && array[i].GetX() - array[i-1].GetX()==1) array[i - 1].Setf(false); if (i > 1 && i<=76 && array[i+1].GetX() - array[i].GetX() == 1) array[i + 1].Setf(false); if (i > 1 && i<75 &&array[i].GetX() - array[i - 2].GetX() == 2) array[i - 2].Setf(false); if (i > 1 && i<75 &&array[i].GetX() - array[i + 2].GetX() == -2) array[i + 2].Setf(false); //if (i >= 76 && array[i].GetX() - array[i - 1].GetX() == 1) array[i + 1].Setf(false); } } return f; } } } .ניתן להשתמש בחומרים לצורך הוראה בלבד לא ניתן לפרסם את החומרים או לעשות בהם כל שימוש מסחרי ללא קבלת אישור מראש מצוות הפיתוח מערכת לניהול טיסות:הצעה לתרגיל מסכם וג'יה כבהה:פיתוח using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Tisot { public static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } } Tisa namespace Tisot { public class Tisa { public int freeSeats { get; private set; } public string destination { get; private set; } private Passenger[,] seat; public Passenger[,] Seat { get { return seat; } } public string GetPassengerName(int x, int y) { return seat[x, y].name; } public Tisa(int rows, int cols, string dest) { destination = dest; freeSeats = cols * rows; seat = new Passenger[rows, cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) seat[i, j] = null; } public bool EmptySeat(int x, int y) { return (seat[x, y] == null); } public string AddPassenger(int x, int y, Passenger p) { if (!EmptySeat(x-1, y-1)) return ";"המושב אינו פנוי seat[x-1, y-1] = p; freeSeats--; return " "ההזמנה נקלטה במושב המבוקש+ x.ToString() + "," + y.ToString(); ; } public string AddPassenger(Passenger p) { int i, j; for (i = 0; i < seat.GetLength(0); i++) for (j = 0; j < seat.GetLength(1); j++) if (EmptySeat(i, j)) { seat[i, j] = p; freeSeats--; return " " ההזמנה נקלטה במושב+ (i+1).ToString()+","+(j+1).ToString(); } return ";" אין מושב פנוי } public bool DelPassenger(int id) { for (int i = 0; i < seat.GetLength(0); i++) for (int j = 0; j < seat.GetLength(1); j++) if (seat[i, j].id == id) { seat[i, j] = null; freeSeats++; return true; } return false; } public bool RowIsEmpty(int i) { int k; for (k = 0; k < seat.GetLength(1); k++) if (!EmptySeat(i, k)) return false; return true; } public int EmptyRow() { int i; for (i = 0; i < seat.GetLength(0); i++) if (RowIsEmpty(i)) return i + 1; return 0; } public int Gruop(int members) { int i, j, counter; int r = members / 4; if (members % 4 > 0) r++; for (i = 0; i < seat.GetLength(0) - r; i++) { counter = 0; for (j = 0; j < r; j++) if (RowIsEmpty(i + j)) counter++; if (counter == r) return i+1; } return 0; } public string Tostring() { string s = ""; for (int i = 0; i < seat.GetLength(0); i++) { for (int j = 0; j < seat.GetLength(1); j++) { if (!EmptySeat(i, j)) { s = s + "{ " + (i+1).ToString() + ", " + (j+1).ToString()+" " +seat[i, j].name + " }"; } else s = s + "{ " + (i+1).ToString() + "," + (j+1).ToString() + " **** }"; } s = s + "\r"; } return s; } } } Passenger namespace Tisot { public class Passenger { public int id { get; private set; } public string name { get; set; } public Passenger(int id, string name) { this.id = id; this.name = name; } } } InitPlanes namespace Tisot { public partial class InitPlanes : Form { public InitPlanes() { InitializeComponent(); } } } Form1 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Collections; namespace Tisot { public partial class frmMain : Form { public static Tisa tisa; public Tisa[] l; Label[,] arr; int k; public frmMain() { InitializeComponent(); } public void BuildSeats() { int left = 0, top = 0; int x = tisa.Seat.GetLength(0); int y = tisa.Seat.GetLength(1); arr = new Label[x, y]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { Label lbl = new Label(); lbl.Text = (i + 1) + "," + (j + 1); if (!tisa.EmptySeat(i, j)) { lbl.Text = lbl.Text + tisa.GetPassengerName(i, j); } else { lbl.Text = lbl.Text + "*****"; } arr[i, j] = lbl; lbl.BackColor = Color.Yellow; lbl.Width = 50; lbl.Left = left; lbl.Top += top; left += lbl.Width + 2; } top += 50; left = 0; } } public void ReBuildSeats() { //int left = 0, top = 0; int x = tisa.Seat.GetLength(0); int y = tisa.Seat.GetLength(1); //Label[,] arr = new Label[x, y]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { //Label lbl = new Label(); arr[i, j].Text = (i + 1) + "," + (j + 1); if (!tisa.EmptySeat(i, j)) { arr[i, j].Text = arr[i, j].Text + tisa.GetPassengerName(i, j); } else { arr[i, j].Text = arr[i, j].Text + "*****"; } //arr[i, j] = lbl; //lbl.BackColor = Color.Yellow; //lbl.Width = 50; //lbl.Left = left; //lbl.Top += top; //left += lbl.Width + 2; //panel1.Controls.Add(lbl); } //top += 50; //left = 0; } } private void btNewTisa_Click(object sender, EventArgs e) { int r, c; string s; if (txtRows.Text.Length < 1) MessageBox.Show(";)"שדה השורות אינו יכול להיות ריק else if (txtCols.Text.Length < 1) MessageBox.Show(";)"שדה העמודות אינו יכול להיות ריק else if (txtDest.Text.Length < 1) MessageBox.Show(";)"שדה היעד אינו יכול להיות ריק else { r = int.Parse(txtRows.Text); c = int.Parse(txtCols.Text); s = txtDest.Text; tisa = new Tisa(r, c, s); showPlain(); l[k] = tisa; k++; dg1.DataSource = l; dg1.Refresh(); for (int i = 1; i <= tisa.Seat.GetLength(0); i++) cmbRow.Items.Add(i); for (int i = 1; i <= tisa.Seat.GetLength(1); i++) cmbCol.Items.Add(i); txtRows.Text = ""; txtCols.Text = ""; txtDest.Text = ""; } lblPlain.Text = tisa.Tostring(); } private void button1_Click(object sender, EventArgs e) { grNewFlight.Visible = true; txtId.Text = ""; txtName.Text = ""; } private void frmMain_Load(object sender, EventArgs e) { l = new Tisa[10]; k = 0; arr = null; } private void btAddPassenger_Click(object sender, EventArgs e) { string msg; int x, y; if (txtId.Text.Length < 1) MessageBox.Show(";)"שדה מספר נוסע אינו יכול להיות ריק else if (txtName.Text.Length < 1) MessageBox.Show(";)"שדה שם אינו יכול להיות ריק else { Passenger p = new Passenger(int.Parse(txtId.Text), txtName.Text); if (cmbCol.Text != "" && cmbRow.Text != "") { x = int.Parse(cmbRow.Text); y = int.Parse(cmbCol.Text); msg = tisa.AddPassenger(x, y, p); } else { msg = tisa.AddPassenger(p); } MessageBox.Show(msg); //are you sure *** txtId.Text = ""; txtName.Text = ""; showPlain(); } } private void button2_Click(object sender, EventArgs e) { for (int i = 1; i <= tisa.Seat.GetLength(0); i++) cmbRow.Items.Add(i); for (int i = 1; i <= tisa.Seat.GetLength(1); i++) cmbCol.Items.Add(i); } private void dg1_CellContentClick(object sender, DataGridViewCellEventArgs e) { int r = e.RowIndex; tisa = l[r]; showPlain(); } private void showPlain() { lblPlaces.Text = tisa.freeSeats.ToString(); lbldest1.Text = tisa.destination; lblPlain.Text = tisa.Tostring(); dg1.Refresh(); } private void dg1_CellClick(object sender, DataGridViewCellEventArgs e) { int r = e.RowIndex; tisa = l[r]; showPlain(); } private void button4_Click(object sender, EventArgs e) { int r = tisa.EmptyRow(); if (r == 0) MessageBox.Show(";)"אין שורה פנויה else MessageBox.Show(" "שורה מספר+r.ToString()+" ;)"פנויה } private void button3_Click(object sender, EventArgs e) { } private void bFindPlace_Click(object sender, EventArgs e) { int x, y; if (txtRow.Text == "" || txtCol.Text == "") MessageBox.Show(";)"חובה להכניס מספר שורה ומספר עמודה else { x = int.Parse(txtRow.Text)-1; y = int.Parse(txtCol.Text)-1; if (x >= tisa.Seat.GetLength(0) || y >= tisa.Seat.GetLength(1)) MessageBox.Show(";)"הערכים מחוץ לטווח else { x = int.Parse(txtRow.Text); y = int.Parse(txtCol.Text); if (tisa.EmptySeat(x - 1, y - 1)) MessageBox.Show(";)"המקום פנוי else MessageBox.Show(";)"המקום אינו פנוי } } } private void btDel_Click(object sender, EventArgs e) { if (txtId.Text.Length < 1) MessageBox.Show(";)"שדה ריק else tisa.DelPassenger(int.Parse(txtId.Text)); txtId.Text = ""; txtName.Text = ""; showPlain(); } private void btfindGroup_Click(object sender, EventArgs e) { int k,r; if (txtnum.Text == "") MessageBox.Show("Sorry 1"); else { k = int.Parse(txtnum.Text); r = tisa.Gruop(k); txtr.Text = r.ToString(); } } } } InitPlanes.Designer namespace Tisot { partial class InitPlanes { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing"> true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.label3); this.panel1.Controls.Add(this.textBox2); this.panel1.Controls.Add(this.textBox1); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.label1); this.panel1.Location = new System.Drawing.Point(359, 37); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(306, 189); this.panel1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(229, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(63, 13); this.label1.TabIndex = 0; this.label1.Text = ";"מספר מטוס // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(210, 62); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(82, 13); this.label2.TabIndex = 1; this.label2.Text = ";"מספר המקומות // // textBox1 // this.textBox1.Location = new System.Drawing.Point(89, 18); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 2; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(89, 59); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(100, 20); this.textBox2.TabIndex = 3; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(263, 99); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 13); this.label3.TabIndex = 4; this.label3.Text = "label3"; // // InitPlanes // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(687, 351); this.Controls.Add(this.panel1); this.Name = "InitPlanes"; this.Text = "InitPlanes"; this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; } } Form1.Designer namespace Tisot { partial class frmMain { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.grNewFlight = new System.Windows.Forms.GroupBox(); this.btNewTisa = new System.Windows.Forms.Button(); this.txtDest = new System.Windows.Forms.TextBox(); this.txtCols = new System.Windows.Forms.TextBox(); this.txtRows = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.lblPlain = new System.Windows.Forms.Label(); this.lbldest1 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.lblPlaces = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.button4 = new System.Windows.Forms.Button(); this.dg1 = new System.Windows.Forms.DataGridView(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.btDel = new System.Windows.Forms.Button(); this.cmbCol = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.cmbRow = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.btAddPassenger = new System.Windows.Forms.Button(); this.txtName = new System.Windows.Forms.TextBox(); this.txtId = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.bFindPlace = new System.Windows.Forms.Button(); this.txtCol = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.txtRow = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.btfindGroup = new System.Windows.Forms.Button(); this.txtnum = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.txtr = new System.Windows.Forms.TextBox(); this.label14 = new System.Windows.Forms.Label(); this.grNewFlight.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dg1)).BeginInit(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(721, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(168, 26); this.label1.TabIndex = 0; this.label1.Text = ";"מערכת לניהול טיסות // // grNewFlight // this.grNewFlight.Controls.Add(this.btNewTisa); this.grNewFlight.Controls.Add(this.txtDest); this.grNewFlight.Controls.Add(this.txtCols); this.grNewFlight.Controls.Add(this.txtRows); this.grNewFlight.Controls.Add(this.label4); this.grNewFlight.Controls.Add(this.label3); this.grNewFlight.Controls.Add(this.label2); this.grNewFlight.Location = new System.Drawing.Point(848, 38); this.grNewFlight.Name = "grNewFlight"; this.grNewFlight.Size = new System.Drawing.Size(248, 132); this.grNewFlight.TabIndex = 2; this.grNewFlight.TabStop = false; this.grNewFlight.Text = ";"טיסה חדשה // // btNewTisa // this.btNewTisa.Location = new System.Drawing.Point(0, 96); this.btNewTisa.Name = "btNewTisa"; this.btNewTisa.Size = new System.Drawing.Size(224, 31); this.btNewTisa.TabIndex = 6; this.btNewTisa.Text = ";"שמור this.btNewTisa.UseVisualStyleBackColor = true; this.btNewTisa.Click += new System.EventHandler(this.btNewTisa_Click); // // txtDest // this.txtDest.Location = new System.Drawing.Point(6, 70); this.txtDest.Name = "txtDest"; this.txtDest.Size = new System.Drawing.Size(101, 20); this.txtDest.TabIndex = 5; // // txtCols // this.txtCols.Location = new System.Drawing.Point(6, 51); this.txtCols.Name = "txtCols"; this.txtCols.Size = new System.Drawing.Size(101, 20); this.txtCols.TabIndex = 4; // // txtRows // this.txtRows.Location = new System.Drawing.Point(6, 33); this.txtRows.Name = "txtRows"; this.txtRows.Size = new System.Drawing.Size(101, 20); this.txtRows.TabIndex = 3; // // label4 // this.label4.AutoSize = true; this.label4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label4.Location = new System.Drawing.Point(173, 70); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(57, 15); this.label4.TabIndex = 2; this.label4.Text = ";"יעד טיסה // // label3 // this.label3.AutoSize = true; this.label3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label3.Location = new System.Drawing.Point(111, 54); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(121, 15); this.label3.TabIndex = 1; this.label3.Text = ";"מספר כיסאות בשוררה // // label2 // this.label2.AutoSize = true; this.label2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label2.Location = new System.Drawing.Point(161, 36); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(71, 15); this.label2.TabIndex = 0; this.label2.Text = ";"מספר שורות // // groupBox1 // this.groupBox1.Controls.Add(this.lblPlain); this.groupBox1.Controls.Add(this.lbldest1); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.lblPlaces); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Location = new System.Drawing.Point(0, 9); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(323, 375); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = "groupBox1"; // // lblPlain // this.lblPlain.AutoSize = true; this.lblPlain.Location = new System.Drawing.Point(16, 49); this.lblPlain.Name = "lblPlain"; this.lblPlain.Size = new System.Drawing.Size(41, 13); this.lblPlain.TabIndex = 7; this.lblPlain.Text = "label13"; // // lbldest1 // this.lbldest1.AutoSize = true; this.lbldest1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lbldest1.Location = new System.Drawing.Point(12, 16); this.lbldest1.Name = "lbldest1"; this.lbldest1.Size = new System.Drawing.Size(33, 15); this.lbldest1.TabIndex = 6; this.lbldest1.Text = " "; // // label6 // this.label6.AutoSize = true; this.label6.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label6.Location = new System.Drawing.Point(60, 16); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(57, 15); this.label6.TabIndex = 5; this.label6.Text = ";"יעד טיסה // // lblPlaces // this.lblPlaces.AutoSize = true; this.lblPlaces.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblPlaces.Location = new System.Drawing.Point(135, 16); this.lblPlaces.Name = "lblPlaces"; this.lblPlaces.Size = new System.Drawing.Size(33, 15); this.lblPlaces.TabIndex = 3; this.lblPlaces.Text = " "; // // label5 // this.label5.AutoSize = true; this.label5.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label5.Location = new System.Drawing.Point(194, 16); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(114, 15); this.label5.TabIndex = 2; this.label5.Text = ";"מספר מקומות פנויים // // button4 // this.button4.Location = new System.Drawing.Point(653, 73); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(168, 20); this.button4.TabIndex = 6; this.button4.Text = ";"מצא שורה פנויה this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // dg1 // this.dg1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dg1.Location = new System.Drawing.Point(344, 23); this.dg1.Name = "dg1"; this.dg1.Size = new System.Drawing.Size(253, 327); this.dg1.TabIndex = 8; this.dg1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler (this.dg1_CellClick); this.dg1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler (this.dg1_CellContentClick); // // groupBox2 // this.groupBox2.Controls.Add(this.btDel); this.groupBox2.Controls.Add(this.cmbCol); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.cmbRow); this.groupBox2.Controls.Add(this.label7); this.groupBox2.Controls.Add(this.btAddPassenger); this.groupBox2.Controls.Add(this.txtName); this.groupBox2.Controls.Add(this.txtId); this.groupBox2.Controls.Add(this.label8); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Location = new System.Drawing.Point(862, 197); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(234, 220); this.groupBox2.TabIndex = 10; this.groupBox2.TabStop = false; this.groupBox2.Text = " ביטול נוסע/ ;"הוספה // // btDel // this.btDel.Location = new System.Drawing.Point(8, 165); this.btDel.Name = "btDel"; this.btDel.Size = new System.Drawing.Size(224, 31); this.btDel.TabIndex = 28; this.btDel.Text = ";"מחק נוסע this.btDel.UseVisualStyleBackColor = true; this.btDel.Click += new System.EventHandler(this.btDel_Click); // // cmbCol // this.cmbCol.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbCol.FormattingEnabled = true; this.cmbCol.Location = new System.Drawing.Point(8, 102); this.cmbCol.Name = "cmbCol"; this.cmbCol.Size = new System.Drawing.Size(121, 21); this.cmbCol.TabIndex = 27; // // label10 // this.label10.AutoSize = true; this.label10.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label10.Location = new System.Drawing.Point(185, 105); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(37, 15); this.label10.TabIndex = 26; this.label10.Text = ";"מושב // // cmbRow // this.cmbRow.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbRow.FormattingEnabled = true; this.cmbRow.Location = new System.Drawing.Point(8, 64); this.cmbRow.Name = "cmbRow"; this.cmbRow.Size = new System.Drawing.Size(121, 21); this.cmbRow.TabIndex = 25; // // label7 // this.label7.AutoSize = true; this.label7.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label7.Location = new System.Drawing.Point(162, 70); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(66, 15); this.label7.TabIndex = 24; this.label7.Text = ";"מספר שורה // // btAddPassenger // this.btAddPassenger.Location = new System.Drawing.Point(8, 128); this.btAddPassenger.Name = "btAddPassenger"; this.btAddPassenger.Size = new System.Drawing.Size(224, 31); this.btAddPassenger.TabIndex = 23; this.btAddPassenger.Text = ";"הוסף נוסע this.btAddPassenger.UseVisualStyleBackColor = true; this.btAddPassenger.Click += new System.EventHandler(this.btAddPassenger_Click); // // txtName // this.txtName.Location = new System.Drawing.Point(2, 44); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(101, 20); this.txtName.TabIndex = 22; // // txtId // this.txtId.Location = new System.Drawing.Point(2, 25); this.txtId.Name = "txtId"; this.txtId.Size = new System.Drawing.Size(101, 20); this.txtId.TabIndex = 21; // // label8 // this.label8.AutoSize = true; this.label8.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label8.Location = new System.Drawing.Point(176, 44); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(52, 15); this.label8.TabIndex = 20; this.label8.Text = ";"שם נוסע // // label9 // this.label9.AutoSize = true; this.label9.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label9.Location = new System.Drawing.Point(167, 25); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(63, 15); this.label9.TabIndex = 19; this.label9.Text = ";"מספר נוסע // // groupBox3 // this.groupBox3.Controls.Add(this.bFindPlace); this.groupBox3.Controls.Add(this.txtCol); this.groupBox3.Controls.Add(this.label11); this.groupBox3.Controls.Add(this.txtRow); this.groupBox3.Controls.Add(this.label12); this.groupBox3.Location = new System.Drawing.Point(616, 115); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(220, 73); this.groupBox3.TabIndex = 11; this.groupBox3.TabStop = false; this.groupBox3.Text = ";"מקום פנוי // // bFindPlace // this.bFindPlace.Location = new System.Drawing.Point(20, 19); this.bFindPlace.Name = "bFindPlace"; this.bFindPlace.Size = new System.Drawing.Size(84, 38); this.bFindPlace.TabIndex = 4; this.bFindPlace.Text = ";"מצא מקום this.bFindPlace.UseVisualStyleBackColor = true; this.bFindPlace.Click += new System.EventHandler(this.bFindPlace_Click); // // txtCol // this.txtCol.Location = new System.Drawing.Point(110, 35); this.txtCol.Name = "txtCol"; this.txtCol.Size = new System.Drawing.Size(47, 20); this.txtCol.TabIndex = 5; // // label11 // this.label11.AutoSize = true; this.label11.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label11.Location = new System.Drawing.Point(155, 16); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(36, 15); this.label11.TabIndex = 3; this.label11.Text = ";"שורה // // txtRow // this.txtRow.Location = new System.Drawing.Point(162, 35); this.txtRow.Name = "txtRow"; this.txtRow.Size = new System.Drawing.Size(35, 20); this.txtRow.TabIndex = 2; // // label12 // this.label12.AutoSize = true; this.label12.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label12.Location = new System.Drawing.Point(110, 16); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(42, 15); this.label12.TabIndex = 1; this.label12.Text = ";"עמודה // // groupBox4 // this.groupBox4.Controls.Add(this.btfindGroup); this.groupBox4.Controls.Add(this.txtnum); this.groupBox4.Controls.Add(this.label13); this.groupBox4.Controls.Add(this.txtr); this.groupBox4.Controls.Add(this.label14); this.groupBox4.Location = new System.Drawing.Point(616, 197); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(220, 73); this.groupBox4.TabIndex = 12; this.groupBox4.TabStop = false; this.groupBox4.Text = ";"מקום לקבוצה // // btfindGroup // this.btfindGroup.Location = new System.Drawing.Point(20, 19); this.btfindGroup.Name = "btfindGroup"; this.btfindGroup.Size = new System.Drawing.Size(84, 38); this.btfindGroup.TabIndex = 4; this.btfindGroup.Text = ";"מצא מקום this.btfindGroup.UseVisualStyleBackColor = true; this.btfindGroup.Click += new System.EventHandler(this.btfindGroup_Click); // // txtnum // this.txtnum.Location = new System.Drawing.Point(126, 37); this.txtnum.Name = "txtnum"; this.txtnum.Size = new System.Drawing.Size(47, 20); this.txtnum.TabIndex = 5; // // label13 // this.label13.AutoSize = true; this.label13.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label13.Location = new System.Drawing.Point(178, 16); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(36, 15); this.label13.TabIndex = 3; this.label13.Text = ";"שורה // // txtr // this.txtr.Location = new System.Drawing.Point(179, 35); this.txtr.Name = "txtr"; this.txtr.Size = new System.Drawing.Size(35, 20); this.txtr.TabIndex = 2; // // label14 // this.label14.AutoSize = true; this.label14.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label14.Location = new System.Drawing.Point(110, 16); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(73, 15); this.label14.TabIndex = 1; this.label14.Text = ";"מספר אנשים // // frmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1108, 429); this.Controls.Add(this.groupBox4); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox2); this.Controls.Add(this.dg1); this.Controls.Add(this.button4); this.Controls.Add(this.groupBox1); this.Controls.Add(this.grNewFlight); this.Controls.Add(this.label1); this.Name = "frmMain"; this.Text = ";"ראשי this.Load += new System.EventHandler(this.frmMain_Load); this.grNewFlight.ResumeLayout(false); this.grNewFlight.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dg1)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox grNewFlight; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button btNewTisa; private System.Windows.Forms.TextBox txtDest; private System.Windows.Forms.TextBox txtCols; private System.Windows.Forms.TextBox txtRows; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label lblPlaces; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label lbldest1; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button button4; private System.Windows.Forms.DataGridView dg1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button btDel; private System.Windows.Forms.ComboBox cmbCol; private System.Windows.Forms.Label label10; private System.Windows.Forms.ComboBox cmbRow; private System.Windows.Forms.Label label7; private System.Windows.Forms.Button btAddPassenger; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtId; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Label label12; // private System.Windows.Forms.Label txtRow; private System.Windows.Forms.TextBox txtRow; private System.Windows.Forms.Button bFindPlace; private System.Windows.Forms.TextBox txtCol; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label lblPlain; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.Button btfindGroup; private System.Windows.Forms.TextBox txtnum; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox txtr; private System.Windows.Forms.Label label14; } } .ניתן להשתמש בחומרים לצורך הוראה בלבד לא ניתן לפרסם את החומרים או לעשות בהם כל שימוש מסחרי ללא קבלת אישור מראש מצוות הפיתוח הצעה לתרגיל מסכם משחק צוללות לביא בונימוביץ:פיתוח import java.awt.Graphics2D; /* * Implements game for 2 players: human and computer */ public class Game { private Player human, computer; private String turn; // "HUMAN" or "PC" private Sound hit, notHit; // sound effects public Game(String turn) { this.turn = turn; this.computer = new Player("PC"); this.human = new Player("HUMAN"); this.hit = new Sound("explosion.wav"); this.notHit = new Sound("click.wav"); } public void draw(Graphics2D g ) { this.human.updateShips(); this.human.draw(g); this.computer.updateShips(); this.computer.draw(g); } /** * (x,y) - user's click coordinates * Update the game data by the user click * @param x * @param y */ public void setShot(double x, double y) { boolean hitFlag; // true - ig the user hit the ship if (this.turn.equals("PC")) hitFlag = this.human.setShot(x,y, "PC"); else hitFlag = this.computer.setShot(x,y, "HUMAN"); if ( ! hitFlag) { if (this.turn.equals("HUMAN")) this.turn = "PC"; else this.turn = "HUMAN"; this.notHit.playSoundOnce(); } else this.hit.playSoundOnce(); } public String getTurn() { return this.turn; } /** * Returns the name of the winner ("HUMAN"/"PC") * if still no winner, returns null * @return */ public String checkWin() { if (!this.human.isAlive()) return "PC"; if (!this.computer.isAlive()) return "HUMAN"; return null; } } . המשחק יכול להיות אדם או מחשב. מממשת משחקPlayer מחלקה import java.awt.Color; import java.awt.Graphics2D; import java.util.Random; /* * Implements the player. * A player may be one of two kinds: human or computer */ /** * * @author Lavy Bunimovich */ public class Player { // The name of a player is "PC" for computer or "HUMAN" for human player private String name; // gameField can contain following characters: // 'o' - en empty cell of a game field // '.' - a shot cell of a game field // 'a' - an alive cell of a ship // 'x' - a shot cell of a ship private char [][] gameField; // The collection of ships private Ship [] ships; // the game field size private static final int SIZE = 10; // the number of ships private static final int NUM_SHIPS = 10; // Graphical attributes // the left upper corner coordinates private double xStart, yStart; // the cell size private double cellSize; /** * Creates the player * The kind of player (human/computer) is defined by the name */ public Player(String name) { this.name = name; // init game field this.gameField = new char[SIZE][SIZE]; for(int i = 0; i < SIZE; i++) for(int j = 0; j < SIZE; j++) this.gameField[i][j] = 'o'; //empty cell //sets the ships this.ships = new Ship [NUM_SHIPS]; setShips(); // init graphical attributes this.cellSize = 20; this.xStart = 30; this.yStart = 30; if (this.name.equals("PC")) this.xStart += NUM_SHIPS * this.cellSize + 30; } // Returns true if ship touchs one of the first count ships private boolean touch(int count, Ship ship) { for(int i = 0; i < count; i++) if (this.ships[i].touch(ship)) return true; return false; } /** * Sets the player's ships to randomal location. * No one touches the other ship */ private void setShips() { Random rnd = new Random(); // init 1 cell ships for(int i = 0; i < 4; i++) this.ships[i] = new Ship(1); // init 2 cell ships for(int i = 4; i < 7; i++) this.ships[i] = new Ship(2); // init 3 cell ships for(int i = 7; i < 9; i++) this.ships[i] = new Ship(3); // init 4 cell ship this.ships[9] = new Ship(4); for(int i = 0; i < SIZE; i++) { do{ boolean horizontal = rnd.nextBoolean(); int maxR, maxC; if ( horizontal) { maxR = rnd.nextInt(SIZE); maxC = rnd.nextInt(SIZE -this.ships[i].getSize()); } else { maxR = rnd.nextInt(SIZE -this.ships[i].getSize()); maxC = rnd.nextInt(SIZE); } this.ships[i].setShip(maxR, maxC, horizontal); } while (touch(i, this.ships[i])); } } public void draw(Graphics2D g) { double x = this.xStart, y = this.yStart; for(int i = 0; i < SIZE; i++) { for(int j = 0; j < SIZE; j++) { // empty cell g.setColor(Color.BLUE); g.fillRect((int)x, (int)y, (int)this.cellSize, (int)this.cellSize); if (this.gameField[i][j] == '.') //shot cell of game field { g.setColor(Color.red); g.fillOval((int)(x + this.cellSize/4), (int)(y + this.cellSize/4), (int)(this.cellSize/2), (int)(this.cellSize/2)); } else if(this.gameField[i][j] == 'a') // alive cell of ship { g.setColor(Color.GRAY); g.fillRect((int)x, (int)y, (int)this.cellSize, (int)this.cellSize); } else if(this.gameField[i][j] == 'x') // shot cell of ship { g.setColor(Color.GRAY); g.fillRect((int)x, (int)y, (int)this.cellSize, (int)this.cellSize); g.setColor(Color.YELLOW); g.drawLine((int)x, (int)y, (int)(x+this.cellSize), (int)(y+this.cellSize)); g.drawLine((int)x, (int)(y + this.cellSize), (int)(x+this.cellSize), (int)y); } // cell frame g.setColor(Color.WHITE); g.drawRect((int)x, (int)y, (int)this.cellSize, (int)this.cellSize); x += this.cellSize; } x = this.xStart; y += this.cellSize; } g.setColor ( Color.BLACK); g.drawString(this.name, (int)this.xStart, (int)(this.yStart - 5) ); } /** * Update cells of the game field by values of ships */ public void updateShips() { for(int i = 0; i < NUM_SHIPS; i++ ) for(int j = 0; j < this.ships[i].getSize(); j++) { int r = this.ships[i].getCell(j).getRow(); int c = this.ships[i].getCell(j).getCol(); if ( this.name.equals("HUMAN")) { if (this.ships[i].getCell(j).isAlive()) this.gameField[r][c] = 'a'; else this.gameField[r][c] = 'x'; } else // "PC" { if (!this.ships[i].getCell(j).isAlive()) this.gameField[r][c] = 'x'; } } } /** * x,y - coordinates of user click * Set a shot to the ship that contains the cell located in (x, y) * If the shot hits the alive ship, the method returns true, otherwise - false * If user missed target, updates thgame field * @param x * @param y * @return */ public boolean setShot(double x, double y, String player) { int row, col; Random rnd = new Random(); if (player.equals("PC")) { // randomal selection do{ row = rnd.nextInt(SIZE); col = rnd.nextInt(SIZE); } while (this.gameField[row][col] != 'o' && this.gameField[row][col] != 'a'); } else { row = (int)(y - this.yStart)/(int)this.cellSize; col = (int)(x - this.xStart)/(int)this.cellSize; } if ( row > -1 && row < SIZE && col > -1 && col < SIZE) { for(int i = 0; i < NUM_SHIPS; i++) if (this.ships[i].setShot(row, col)) return true; this.gameField[row][col] = '.'; } return false; } /** * Returns true if the player contains one alive ship, otherwise - false * @return */ public boolean isAlive() { for(int i = 0; i < NUM_SHIPS; i++) if (this.ships[i].isAlive()) return true; return false; } } . מממשת צוללתShip מחלקה /* * Implements a ship * A ship can be composed dro 1 to 4 cells */ /** * * @author Lavy Bunimovich */ public class Ship { private Cell [] cells; /** * Creates a ship the size of n cells * @param numCells */ public Ship (int n) { this.cells = new Cell[n]; } /** * Set a shot to the cell located in the row and col * If the shot hits the cell alive, the method returns true, otherwise - false * @param row * @param col * @return */ public boolean setShot(int row, int col) { for( int i = 0; i < this.cells.length; i++) { if (this.cells[i].getRow() == row && this.cells[i].getCol() == col && this.cells[i].isAlive()) { this.cells[i].setAlive(false); return true; } } return false; } /** * Returns true if at least one of the ship's cells remained alive, * otherwise returns false * @return */ public boolean isAlive () { for (int i = 0; i < this.cells.length; i++) if (this.cells[i].isAlive()) return true; return false; } /** * Returns ship's size * @return */ public int getSize() { return this.cells.length; } /** * Sets the rows and cols of all ship's cells * @param row - the row number of the upper cell of the ship * @param col - the column number of the left cell of the ship * @param horizontal - true - the ship deployed horizontally * false - vertically */ public void setShip(int row, int col, boolean horizontal) { for(int i = 0; i < this.cells.length; i++) { this.cells[i]= new Cell(row, col); if ( horizontal ) col++; else row++; } } /** * Returns true if this ship touchs the other ship or cross it, * otherwise returns false * @return */ public boolean touch(Ship other) { for (int i = 0; i < this.cells.length; i++) for(int j = 0; j < other.cells.length; j++) if (this.cells[i].touch(other.cells[j])) return true; return false; } public String toString() { String st = "["; for(int i = 0; i < this.cells.length; i++) st += this.cells[i].toString(); st += "]"; return st; } /** * Returns the cell i * @param i * @return */ public Cell getCell(int i) { return this.cells[i]; } } . מממשת את התא (משבצת) של צוללתCell מחלקה /* *Implements the cell of ship */ /** * * @author Lavy Bunimovich */ public class Cell { private int row, col; // location on the game board private boolean isAlive; // true - the cell isn't shot, otherwase - false /** * Creates a living cell */ public Cell(int row, int col) { this.row = row; this.col = col; this.isAlive = true; } public int getCol() { return col; } public void setCol(int col) { this.col = col; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public boolean isAlive() { return isAlive; } public void setAlive(boolean isAlive) { this.isAlive = isAlive; } public String toString() { return "(" + this.row + ", " + this.col + ")"; } /** * Returns true if this cell touchs the other cell or match it, * otherwise returns false * @return */ public boolean touch(Cell other) { //Boundaries of the area around the other cell int startRow = other.row - 1, startCol = other.col - 1, endRow = other.row + 1, endCol = other.col + 1; for (int i = startRow; i <= endRow; i++) for (int j = startCol; j <= endCol; j++) if (this.row == i && this.col == j) return true; return false; } } Model public class Model { // model status private Rectangle bounds; // the bounds of the graphic context private boolean runFlag; // true- if the application is running, otherwise - false private static final int delayInterval = 100; private int delayCounter; // list of objects private Game game; public Model(Rectangle bounds) { // init the model status this.bounds = bounds; this.runFlag = true; this.delayCounter = this.delayInterval; //init the model's object this.game = new Game("HUMAN"); } // moves all animated object public void update() { // computer's shot if (this.game.getTurn().equals("PC")) { this.delayCounter--; if (this.delayCounter<= 0) { this.game.setShot(0, 0); this.delayCounter = this.delayInterval; } } updateResults(); } /** * Checks the winner and update the game according to results */ private void updateResults() { String winnerName = this.game.checkWin(); if ( winnerName != null) { String msg; if ( winnerName.equals("HUMAN")) msg = "Congratulations!! You won!\n"; else msg = "We're sorry! You lost!\n"; msg += "Do you want to start a new game?"; int reply = JOptionPane.showConfirmDialog(null, msg, "Ships Battle", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { this.game = new Game("HUMAN"); } else System.exit(0); } } // draws all drawable objects public void draw(Graphics2D g) { this.game.draw(g); } // return true - if the application is still running public boolean isRunning() { return this.runFlag; } // handling mouse events public void mouseInput(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1 && this.game.getTurn().equals("HUMAN")) { this.game.setShot(evt.getX(), evt.getY()); } } } Sound /* * Implements the sound play possibility */ /** * * @author Lavy Bunimovich */ import java.applet.*; import java.net.*; public class Sound // Holds one audio file { private AudioClip song; // Sound player private URL songPath; // Sound path Sound(String filename) { try { songPath = this.getClass().getClassLoader().getResource(filename); // Get the Sound URL song = Applet.newAudioClip(songPath); // Load the Sound } catch(Exception e){} // Satisfy the catch } public void playSound() { song.loop(); // Play } public void stopSound() { song.stop(); // Stop } public void playSoundOnce() { song.play(); // Play only once } } View import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; /** * The template for the grapic application * */ public class View extends javax.swing.JFrame { private Model model; // the application model private BufferedImage offscreen; // for double buffering private Image bgImage; public View() { initComponents(); appInit(); appStart(); } public void appInit() { // Reference to the application model this.model = new Model(this.pnlCanvas.getBounds()); // Create offscreen graphics image for double-buffering this.offscreen = new BufferedImage(this.pnlCanvas.getWidth(), this.pnlCanvas.getHeight(), BufferedImage.TYPE_INT_RGB); // Ignor OS repaint callback No flickers this.setIgnoreRepaint(true); this.pnlCanvas.setIgnoreRepaint(true); this.setVisible(true); // load background Image URL url = this.getClass().getClassLoader().getResource("sea.jpg"); try { this.bgImage = ImageIO.read(url); } catch (IOException ex){} } public void appStart() { // while the application isn't closed and the game not over while(this.model.isRunning()) { // request focuse to handle keyboard & mouse events this.pnlCanvas.requestFocus(); // Get offscreen graphics context Graphics2D g = this.offscreen.createGraphics(); //this.offscreen.createGraphics(); // Make the graphics smooth g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // clear screen g.setColor(this.pnlCanvas.getBackground()); g.fillRect(0, 0, this.pnlCanvas.getWidth(), this.pnlCanvas.getHeight() ); // Clear offscreen graphics context g.drawImage(this.bgImage, 0, 0, this.pnlCanvas.getWidth(), this.pnlCanvas.getHeight(), this); // game logic this.model.update(); this.model.draw(g); // Put offscreen graphics context on the panel canvas (double buffering) this.pnlCanvas.getGraphics().drawImage(offscreen, 0, 0, null); // delay Thread.yield(); } } public static void main(String[] args) { new View(); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GENBEGIN:initComponents private void initComponents() { pnlCanvas = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Ships Game"); setForeground(java.awt.Color.white); setResizable(false); pnlCanvas.setBackground(new java.awt.Color(255, 255, 255)); pnlCanvas.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { pnlCanvasMousePressed(evt); } }); javax.swing.GroupLayout pnlCanvasLayout = new javax.swing.GroupLayout(pnlCanvas); pnlCanvas.setLayout(pnlCanvasLayout); pnlCanvasLayout.setHorizontalGroup( pnlCanvasLayout.createParallelGroup (javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 490, Short.MAX_VALUE) ); pnlCanvasLayout.setVerticalGroup( pnlCanvasLayout.createParallelGroup (javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 291, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlCanvas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlCanvas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void pnlCanvasMousePressed(java.awt.event.MouseEvent evt) { //GEN-FIRST:event_pnlCanvasMousePressed this.model.mouseInput(evt); }//GEN-LAST:event_pnlCanvasMousePressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel pnlCanvas; // End of variables declaration//GEN-END:variables } Tests import javax.swing.JOptionPane; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Lavy Bunimovich */ public class Tests { public static void main(String [] args) { // Ship s2 = new Ship(2); // // horizontal // s2.setShip(1, 1, true); // System.out.println(s2); // //vertical // s2.setShip(1, 1, false); // System.out.println(s2); // Ship s1 = new Ship(2); // s1.setShip(1, 1, true); // Ship s2 = new Ship(2); // s2.setShip(2, 3, false); // System.out.println(s1.toString() + " " + s2.toString() + " " + s1.touch(s2)); // // JOptionPane.showMessageDialog(null, // "Eggs are not supposed to be green.", // "Inane warning", // JOptionPane.WARNING_MESSAGE); } }