diff --git a/SnakeGame/App.config b/SnakeGame/App.config
index 8e15646..1b99773 100644
--- a/SnakeGame/App.config
+++ b/SnakeGame/App.config
@@ -1,6 +1,3 @@
-
+
-
-
-
\ No newline at end of file
diff --git a/SnakeGame/Form1.Designer.cs b/SnakeGame/Form1.Designer.cs
index 75d93ce..449a7fd 100644
--- a/SnakeGame/Form1.Designer.cs
+++ b/SnakeGame/Form1.Designer.cs
@@ -34,6 +34,7 @@
this.newSingleplayerGameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newMultiplayerGameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.joinMultiplayerGameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox();
this.scoreLabel = new System.Windows.Forms.Label();
this.livesLabel = new System.Windows.Forms.Label();
this.DialogPanel = new System.Windows.Forms.Panel();
@@ -56,10 +57,11 @@
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.gameToolStripMenuItem});
+ this.gameToolStripMenuItem,
+ this.toolStripTextBox1});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
- this.menuStrip1.Size = new System.Drawing.Size(624, 24);
+ this.menuStrip1.Size = new System.Drawing.Size(624, 27);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
@@ -70,7 +72,7 @@
this.newMultiplayerGameToolStripMenuItem,
this.joinMultiplayerGameToolStripMenuItem});
this.gameToolStripMenuItem.Name = "gameToolStripMenuItem";
- this.gameToolStripMenuItem.Size = new System.Drawing.Size(50, 20);
+ this.gameToolStripMenuItem.Size = new System.Drawing.Size(50, 23);
this.gameToolStripMenuItem.Text = "Game";
//
// newSingleplayerGameToolStripMenuItem
@@ -79,7 +81,7 @@
this.newSingleplayerGameToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.newSingleplayerGameToolStripMenuItem.Name = "newSingleplayerGameToolStripMenuItem";
this.newSingleplayerGameToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
- this.newSingleplayerGameToolStripMenuItem.Size = new System.Drawing.Size(240, 22);
+ this.newSingleplayerGameToolStripMenuItem.Size = new System.Drawing.Size(269, 22);
this.newSingleplayerGameToolStripMenuItem.Text = "New singleplayer game";
this.newSingleplayerGameToolStripMenuItem.Click += new System.EventHandler(this.newSingleplayerGameToolStripMenuItem_Click);
//
@@ -92,6 +94,7 @@
| System.Windows.Forms.Keys.N)));
this.newMultiplayerGameToolStripMenuItem.Size = new System.Drawing.Size(269, 22);
this.newMultiplayerGameToolStripMenuItem.Text = "New multiplayer game";
+ this.newMultiplayerGameToolStripMenuItem.Click += new System.EventHandler(this.newMultiplayerGameToolStripMenuItem_Click);
//
// joinMultiplayerGameToolStripMenuItem
//
@@ -103,6 +106,16 @@
| System.Windows.Forms.Keys.N)));
this.joinMultiplayerGameToolStripMenuItem.Size = new System.Drawing.Size(269, 22);
this.joinMultiplayerGameToolStripMenuItem.Text = "Join multiplayer game";
+ this.joinMultiplayerGameToolStripMenuItem.Click += new System.EventHandler(this.joinMultiplayerGameToolStripMenuItem_Click);
+ //
+ // toolStripTextBox1
+ //
+ this.toolStripTextBox1.BackColor = System.Drawing.Color.Black;
+ this.toolStripTextBox1.ForeColor = System.Drawing.Color.White;
+ this.toolStripTextBox1.Name = "toolStripTextBox1";
+ this.toolStripTextBox1.Size = new System.Drawing.Size(100, 23);
+ this.toolStripTextBox1.Text = "UserName";
+ this.toolStripTextBox1.TextChanged += new System.EventHandler(this.toolStripTextBox1_TextChanged);
//
// scoreLabel
//
@@ -152,6 +165,7 @@
this.Deactivate += new System.EventHandler(this.Form1_Deactivate);
this.Load += new System.EventHandler(this.Form1_Load);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
+ this.Resize += new System.EventHandler(this.Form1_Resize);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
@@ -170,6 +184,7 @@
private System.Windows.Forms.Label scoreLabel;
private System.Windows.Forms.Label livesLabel;
private System.Windows.Forms.Panel DialogPanel;
+ private System.Windows.Forms.ToolStripTextBox toolStripTextBox1;
}
}
diff --git a/SnakeGame/Form1.cs b/SnakeGame/Form1.cs
index 0029fb3..404cb6b 100644
--- a/SnakeGame/Form1.cs
+++ b/SnakeGame/Form1.cs
@@ -4,9 +4,11 @@ using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
+using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
+using WPFInput = System.Windows.Input;
namespace SnakeGame
{
@@ -24,12 +26,16 @@ namespace SnakeGame
}
set
{
- if (value && !timerenabled) //Only start if not running already
+ if (!MSGBox.Shown)
{
- Timer.Start();
- SpeedTimer.Start();
+ if (value && !timerenabled) //Only start if not running already
+ {
+ Timer.Start();
+ SpeedTimer.Start();
+ }
+ timerenabled = value;
+ Instance.toolStripTextBox1.Enabled = !value;
}
- timerenabled = value;
}
}
public Form1()
@@ -48,6 +54,7 @@ namespace SnakeGame
Game.LivesLabel = livesLabel;
Game.DialogPanel = DialogPanel;
Instance = this;
+ toolStripTextBox1.Text = "Player";
Timer = new Timer();
Timer.Interval = Game.UpdateTime;
Timer.Tick += delegate
@@ -81,8 +88,10 @@ namespace SnakeGame
GameRenderer.Render();
}
+ private static bool playerpaused = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
+ //if (e.KeyCode == Keys.Down && WPFInput.Keyboard.IsKeyDown(WPFInput.Key.Down))
if (e.KeyCode == Keys.Down)
Game.MoveDirection = Direction.Down;
else if (e.KeyCode == Keys.Up)
@@ -93,9 +102,21 @@ namespace SnakeGame
Game.MoveDirection = Direction.Right;
else if (e.KeyCode == Keys.Enter)
{
- MSGBox.CloseMSGBox();
+ //MSGBox.CloseMSGBox();
+ MSGBox.OnCloseEvent(sender, e);
}
- Game.Refresh();
+ else if (e.KeyCode == Keys.P || e.KeyCode == Keys.Pause)
+ {
+ Game.Paused = !Game.Paused;
+ if (Game.Paused)
+ playerpaused = true;
+ else
+ playerpaused = false;
+ }
+ else
+ return;
+ if (!Game.Paused)
+ Game.Refresh();
}
private void newSingleplayerGameToolStripMenuItem_Click(object sender, EventArgs e)
@@ -116,5 +137,54 @@ namespace SnakeGame
formdeactivated = !Game.Paused;
Game.Paused = true;
}
+
+ private void newMultiplayerGameToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ Game.Start(GameStartMode.MultiPlayer);
+ }
+
+ private void joinMultiplayerGameToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ Game.Start(GameStartMode.Connect);
+ }
+
+ private void toolStripTextBox1_TextChanged(object sender, EventArgs e)
+ {
+ Game.UserName = toolStripTextBox1.Text;
+ }
+
+ private void Form1_Resize(object sender, EventArgs e)
+ {
+
+ GameRenderer.Render();
+ }
+ }
+ public static class Ext
+ {
+ public static void ClearEventInvocations(this object obj, string eventName)
+ {
+ var fi = obj.GetType().GetEventField(eventName);
+ if (fi == null) return;
+ fi.SetValue(obj, null);
+ }
+
+ private static FieldInfo GetEventField(this Type type, string eventName)
+ {
+ FieldInfo field = null;
+ while (type != null)
+ {
+ /* Find events defined as field */
+ field = type.GetField(eventName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);
+ if (field != null && (field.FieldType == typeof(MulticastDelegate) || field.FieldType.IsSubclassOf(typeof(MulticastDelegate))))
+ break;
+
+ /* Find events defined as property { add; remove; } */
+ field = type.GetField("EVENT_" + eventName.ToUpper(), BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);
+ if (field != null)
+ break;
+ type = type.BaseType;
+ }
+ return field;
+ }
}
}
diff --git a/SnakeGame/Game.cs b/SnakeGame/Game.cs
index 86be85d..081003c 100644
--- a/SnakeGame/Game.cs
+++ b/SnakeGame/Game.cs
@@ -26,6 +26,7 @@ namespace SnakeGame
public static Label ScoreLabel;
public static Label LivesLabel;
public static Panel DialogPanel;
+ public static string UserName;
private static int score;
public static int Score
{
@@ -72,20 +73,68 @@ namespace SnakeGame
switch(mode)
{
case GameStartMode.SinglePlayer:
- MSGBox.ShowMSGBox("New singleplayer game", "Size (X Y):", MSGBoxType.SizeInput, new EventHandler(delegate(object s, int input)
+ MSGBox.ShowMSGBox("New singleplayer game", "Size:", MSGBoxType.SizeInput, new EventHandler(delegate(object s, string inp)
{
//string[] strs=input.Split(' ');
//int x, y;
//if (strs.Length == 2 && int.TryParse(strs[0], out x) && int.TryParse(strs[1], out y))
+ int input = int.Parse(inp);
if (input > 5)
{
//GameSize = new Point(x, y);
GameRenderer.Panel.CreateGraphics().FillRectangle(new SolidBrush(Color.Black), new Rectangle(new Point(), GameRenderer.Panel.Size));
- int xy=GameRenderer.Panel.Size.Width/input;
+ int xy = GameRenderer.Panel.Size.Width / input;
GameSize = new Point(xy, xy);
Game.Reset();
Form1.TimerEnabled = true;
}
+ else
+ Game.Paused = true;
+ }));
+ break;
+ case GameStartMode.MultiPlayer:
+ if (Game.UserName == "Player")
+ {
+ MSGBox.ShowMSGBox("Please change your username from default.", "", MSGBoxType.Text);
+ break;
+ }
+ MSGBox.ShowMSGBox("New multiplayer game", "Name:\nMax. players:", MSGBoxType.MultipleInput, new EventHandler(delegate(object s, string input)
+ {
+ string[] strs = input.Split('\n');
+ int num = 0;
+ if (int.TryParse(strs[1], out num))
+ {
+ var match = new NetMatch { Name = strs[0], MaxPlayers = num, OwnerIP = Network.GetIPs() };
+ Network.CreateGame(match);
+ Game.Paused = false;
+ }
+ else
+ Game.Paused = true;
+ }));
+ break;
+ case GameStartMode.Connect:
+ if (Game.UserName == "Player")
+ {
+ MSGBox.ShowMSGBox("Please change your username from default.", "", MSGBoxType.Text);
+ break;
+ }
+ Network.DownloadGameList();
+ string matches = "";
+ for (int i = 0; i < Network.Matches.Count; i++)
+ {
+ matches += Network.Matches[i].Name + " " + Network.Matches[i].Players.Count + "/" + Network.Matches[i].MaxPlayers + " " + Network.Matches[i].OwnerName + "\n";
+ }
+ MSGBox.ShowMSGBox("Connect to game", matches, MSGBoxType.List, new EventHandler(delegate(object s, string input)
+ {
+ //Network.Connect(Network.Matches[int.Parse(input)]);
+ int num = 0;
+ if (int.TryParse(input, out num) && num != -1)
+ {
+ Network.Connect(Network.Matches[num]);
+ Game.Paused = false;
+ }
+ else
+ Game.Paused = true;
}));
break;
default:
@@ -101,6 +150,7 @@ namespace SnakeGame
//GameField = new List(GameSize.X * GameSize.Y);
//GameField = new int[GameSize.X, GameSize.Y];
GameSize = new Point { X = size.Width / 20, Y = size.Height / 20 };
+ UserName = "Player";
Game.Reset();
//GameField.Single(entry => entry.X == PlayerPos.X && entry.Y == PlayerPos.Y).Tick;
/*for (int i = 0; i < GameField.Count; i++)
@@ -198,7 +248,7 @@ namespace SnakeGame
if (Game.GameField[nextcoord.X, nextcoord.Y].Tick != 0 && Game.GameField[nextcoord.X, nextcoord.Y].Type != SquareType.Point)
{
Lives--;
- if (Lives == 0)
+ if (Lives <= 0)
Stop();
else
Reset(false);
@@ -219,8 +269,10 @@ namespace SnakeGame
GameField[nextcoord.X, nextcoord.Y].Tick = Length;
GameField[nextcoord.X, nextcoord.Y].Type = SquareType.Player;
PlayerPos = new Point { X = nextcoord.X, Y = nextcoord.Y };
+ /*if (Score > 0)
+ Score--;*/
if (Score > 0)
- Score--;
+ Score -= new Random().Next(1, 20);
/* }
}
}*/
@@ -251,7 +303,8 @@ namespace SnakeGame
//Form1.Timer.Stop();
//Form1.TimerEnabled = false;
//MessageBox.Show("Game over!");
- MSGBox.ShowMSGBox("Game over!", "", MSGBoxType.Text, pauseafter: true);
+ MSGBox.ShowMSGBox("Game over!", "", MSGBoxType.Text);
+ Game.Paused = true;
}
}
public enum GameStartMode
diff --git a/SnakeGame/GameRenderer.cs b/SnakeGame/GameRenderer.cs
index 67e21de..6cf7b10 100644
--- a/SnakeGame/GameRenderer.cs
+++ b/SnakeGame/GameRenderer.cs
@@ -11,9 +11,19 @@ namespace SnakeGame
public static class GameRenderer
{
public static Panel Panel;
+ //private static Timer timer = new Timer();
public static void Render()
{
//foreach(var coord in Game.GameField)
+ /*if (timer.Enabled)
+ return;
+ else
+ {
+ timer.Interval = 1;
+ timer.ClearEventInvocations("Tick");
+ timer.Tick += delegate
+ {
+ timer.Stop();*/
for (int i = 0; i < Game.GameField.GetLength(0); i++)
{
for (int j = 0; j < Game.GameField.GetLength(1); j++)
@@ -25,13 +35,19 @@ namespace SnakeGame
else if (Game.GameField[i, j].Type == SquareType.Wall)
RenderSquare(new Point { X = i, Y = j }, Color.Red);
else if (Game.GameField[i, j].Type == SquareType.Player)
- RenderSquare(new Point { X = i, Y = j }, Color.Green);
+ if (Network.ConnectedMatch == null)
+ RenderSquare(new Point { X = i, Y = j }, Color.Green);
+ else
+ RenderSquare(new Point { X = i, Y = j }, Network.ConnectedMatch.GetPlayerByID(Game.GameField[i, j].PlayerID).Color);
else if (Game.GameField[i, j].Type == SquareType.Point)
RenderSquare(new Point { X = i, Y = j }, Color.Blue);
else
RenderSquare(new Point { X = i, Y = j }, Color.Gray);
}
}
+ /* };
+ timer.Start();
+ }*/
}
private static void RenderSquare(Point coord, Color color)
{
diff --git a/SnakeGame/MSGBox.cs b/SnakeGame/MSGBox.cs
index 1f5ac50..32dde01 100644
--- a/SnakeGame/MSGBox.cs
+++ b/SnakeGame/MSGBox.cs
@@ -12,19 +12,23 @@ namespace SnakeGame
{
private static int slidervalue;
private static bool pause;
- public static void ShowMSGBox(string text, string inputtext, MSGBoxType type, EventHandler doneevent = null, bool pauseafter = false)
+ public static EventHandler OnCloseEvent { get; private set; }
+ public static bool Shown = false;
+ public static void ShowMSGBox(string text, string inputtext, MSGBoxType type, EventHandler doneevent = null)
{
- Game.DialogPanel.Controls.Add(new Label { Text = text, Location = new Point(10, 10), Font = new Font(FontFamily.GenericSansSerif, 10f), Size = new Size(200, 20) });
+ if (Shown)
+ return;
+ Game.DialogPanel.Controls.Add(new Label { Text = text, Location = new Point(10, 10), Font = new Font(FontFamily.GenericSansSerif, 10f), Size = new Size(200, 50) });
//TextBox input = null;
switch (type)
{
case MSGBoxType.Text:
- Game.DialogPanel.Size = new Size(200, 100);
+ Game.DialogPanel.Size = new Size(200, 150);
slidervalue = 0;
break;
case MSGBoxType.SizeInput:
Game.DialogPanel.Size = new Size(200, 200);
- Game.DialogPanel.Controls.Add(new Label { Text = inputtext, Location = new Point(10, 40), Size = new Size(100, 20) });
+ Game.DialogPanel.Controls.Add(new Label { Text = inputtext, Location = new Point(10, 60), Size = new Size(100, 20) });
slidervalue = 20;
/*Game.DialogPanel.Controls.Add(input = new TextBox
{
@@ -35,12 +39,12 @@ namespace SnakeGame
Size = new Size(100, 1)
});*/
Graphics gr = Game.DialogPanel.CreateGraphics();
- gr.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(10, 60, slidervalue, slidervalue));
+ gr.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(10, 80, slidervalue, slidervalue));
Game.DialogPanel.Paint += delegate
{
if (slidervalue == 0)
return;
- gr.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(10, 60, slidervalue, slidervalue));
+ gr.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(10, 80, slidervalue, slidervalue));
};
Game.DialogPanel.Click += delegate
{
@@ -55,6 +59,32 @@ namespace SnakeGame
}
};
break;
+ case MSGBoxType.MultipleInput:
+ string[] txts = inputtext.Split('\n');
+ for (int i = 0; i < txts.Length; i++)
+ {
+ Game.DialogPanel.Controls.Add(new Label { Text = txts[i], Location = new Point(10, 60 + i * 30), Size = new Size(80, 30) });
+ Game.DialogPanel.Controls.Add(new TextBox
+ {
+ Text = "",
+ Location = new Point(100, 60 + i * 30),
+ Size = new Size(100, 30),
+ Multiline = false
+ });
+ }
+ Game.DialogPanel.Size = new Size(200, 60 + txts.Length * 30 + 40);
+ break;
+ case MSGBoxType.List:
+ Game.DialogPanel.Size = new Size(200, 200);
+ string[] strs = inputtext.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
+ //Game.DialogPanel.Controls.Add(new Label { Text = strs[0], Location = new Point(10, 60), Size = new Size(100, 20) });
+ ListBox listbox = new ListBox { Location = new Point(10, 60), Size = new Size(190, 100) };
+ for (int i = 0; i < strs.Length; i++)
+ {
+ listbox.Items.Add(strs[i]);
+ }
+ Game.DialogPanel.Controls.Add(listbox);
+ break;
default:
throw new NotImplementedException();
}
@@ -62,13 +92,65 @@ namespace SnakeGame
Game.DialogPanel.Location = Game.DialogPanel.Parent.PointToClient(GameRenderer.Panel.PointToScreen(Game.DialogPanel.Location));
Button btn = new Button();
btn.Text = "OK";
- btn.Click += delegate
+ switch (type)
{
- CloseMSGBox();
- if (doneevent != null)
- //doneevent(btn, (input == null ? "" : input.Text));
- doneevent(btn, slidervalue);
- };
+ case MSGBoxType.Text:
+ OnCloseEvent += delegate
+ {
+ CloseMSGBox();
+ if (doneevent != null)
+ doneevent(btn, "");
+ };
+ break;
+ case MSGBoxType.SizeInput:
+ OnCloseEvent += delegate
+ {
+ CloseMSGBox();
+ if (doneevent != null)
+ //doneevent(btn, (input == null ? "" : input.Text));
+ doneevent(btn, slidervalue.ToString());
+ };
+ break;
+ case MSGBoxType.MultipleInput:
+ OnCloseEvent += delegate
+ {
+ if (doneevent != null)
+ {
+ string str = "";
+ foreach (Control control in Game.DialogPanel.Controls)
+ {
+ if (control is TextBox)
+ {
+ str += control.Text + "\n";
+ }
+ }
+ str = str.Remove(str.Length - 1);
+ doneevent(btn, str);
+ }
+ CloseMSGBox();
+ };
+ break;
+ case MSGBoxType.List:
+ OnCloseEvent += delegate
+ {
+ if (doneevent != null)
+ {
+ int index = -1;
+ foreach (Control control in Game.DialogPanel.Controls)
+ {
+ if (control is ListBox)
+ {
+ index = (control as ListBox).SelectedIndex;
+ break;
+ }
+ }
+ doneevent(btn, index.ToString());
+ }
+ CloseMSGBox();
+ };
+ break;
+ }
+ btn.Click += OnCloseEvent;
btn.FlatStyle = FlatStyle.Flat;
btn.FlatAppearance.BorderColor = Color.Blue;
btn.FlatAppearance.BorderSize = 2;
@@ -77,24 +159,30 @@ namespace SnakeGame
btn.Location = new Point(Game.DialogPanel.Size.Width / 2 - 40, Game.DialogPanel.Size.Height - 40);
btn.Size = new Size(80, 30);
Game.DialogPanel.Controls.Add(btn);
+ pause = Game.Paused;
Game.Paused = true;
- pause = pauseafter;
+ //pause = pauseafter;
Game.DialogPanel.Visible = true;
+ Shown = true;
}
public static void CloseMSGBox()
{
Game.DialogPanel.Visible = false;
Game.DialogPanel.Controls.Clear();
+ OnCloseEvent = null;
Game.Paused = pause;
//Form1.Instance.Activate();
//GameRenderer.Panel.Select();
//Form1.Instance.Select();
Form1.Instance.Focus();
+ Shown = false;
}
}
public enum MSGBoxType
{
Text,
- SizeInput
+ SizeInput,
+ MultipleInput,
+ List
}
}
diff --git a/SnakeGame/NetMatch.cs b/SnakeGame/NetMatch.cs
new file mode 100644
index 0000000..1f86518
--- /dev/null
+++ b/SnakeGame/NetMatch.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SnakeGame
+{
+ public class NetMatch
+ {
+ public string Name = "";
+ public int MaxPlayers = 0;
+ //public List PlayerNames = new List();
+ public List Players = new List();
+ public string OwnerName = "";
+ public IPAddress OwnerIP;
+ public Player GetPlayerByID(int id)
+ {
+ return Players.Single(entry => entry.ID == id);
+ }
+ }
+}
diff --git a/SnakeGame/Network.cs b/SnakeGame/Network.cs
index 1324a7d..f4502e8 100644
--- a/SnakeGame/Network.cs
+++ b/SnakeGame/Network.cs
@@ -4,6 +4,13 @@ using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
+using System.Net.Http;
+using System.Collections.Specialized;
+using System.Windows.Forms;
+using System.IO;
+using Newtonsoft.Json.Linq;
+using System.Net.Sockets;
+using System.Threading;
namespace SnakeGame
{
@@ -11,8 +18,176 @@ namespace SnakeGame
{
public static void SyncUpdate()
{
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://snakegame.16mb.com/");
- request.Method = "POST";
+ /*using (var client = new HttpClient())
+ {
+ var values = new Dictionary
+ {
+ { "thing1", "hello" },
+ { "thing2", "world" }
+ };
+
+ var content = new FormUrlEncodedContent(values);
+
+ //var response = await client.PostAsync("http://snakegame.16mb.com", content);
+ Task task = client.PostAsync("http://snakegame.16mb.com", content);
+ task.RunSynchronously();
+ HttpResponseMessage response = (HttpResponseMessage)task.AsyncState;
+
+ //var responseString = await response.Content.ReadAsStringAsync();
+ task = response.Content.ReadAsStringAsync();
+ task.RunSynchronously();
+ string responseString = (string)task.AsyncState;
+ Console.WriteLine("Received response: " + responseString);
+ }*/
+ using (var client = new WebClient())
+ {
+ var values = new NameValueCollection();
+ values["client"] = "test";
+
+ var response = client.UploadValues("http://snakegame.16mb.com", values);
+
+ var responseString = Encoding.Default.GetString(response);
+ Console.WriteLine("Received response: " + responseString);
+ }
+ }
+ public static List Matches = new List();
+ public static NetMatch ConnectedMatch { get; private set; }
+ public static void DownloadGameList()
+ {
+ using (var client = new WebClient())
+ {
+ var values = new NameValueCollection();
+ values["client"] = "cheesecrescent"; //Sajtoskifli
+
+ try
+ {
+ var response = client.UploadValues("http://snakegame.16mb.com", values);
+
+ Matches.Clear();
+ var responseString = Encoding.Default.GetString(response);
+ string[] responses = responseString.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ int x = 0;
+ while (x < responses.Length)
+ {
+ var match = new NetMatch();
+ match.Name = responses[x];
+ x++;
+ match.OwnerName = responses[x];
+ x++;
+ if (!Int32.TryParse(responses[x], out match.MaxPlayers))
+ MessageBox.Show("Error! The received text is in wrong format.");
+ x++;
+ int players;
+ if (!Int32.TryParse(responses[x], out players))
+ MessageBox.Show("Error! The received text is in wrong format.");
+ x++;
+ for (int i = x; i < x + players; i++)
+ match.Players.Add(new Player(responses[i]));
+ x += players;
+ match.OwnerIP = IPAddress.Parse(responses[x]);
+ x++;
+ Matches.Add(match);
+ }
+ }
+ catch (WebException) { }
+ }
+ }
+ public static void CreateGame(NetMatch match)
+ {
+ MessageBox.Show("Create game: " + match.Name + " (" + match.MaxPlayers + " players)");
+ using (var client = new WebClient())
+ {
+ var values = new NameValueCollection();
+ values["client"] = Game.UserName;
+ values["name"] = match.Name;
+ values["maxplayers"] = match.MaxPlayers.ToString();
+
+ IPAddress ip = GetIPs();
+ if (ip == null)
+ return;
+ values["ip"] = ip.ToString();
+
+ var response = client.UploadValues("http://snakegame.16mb.com", values);
+
+ var responseString = Encoding.Default.GetString(response);
+ if (responseString != "OK")
+ MessageBox.Show("Error!\n" + responseString);
+ else
+ {
+ if (ConnectedMatch != null)
+ Leave();
+ ConnectedMatch = match;
+ StartListening();
+ //HttpWebRequest request = WebRequest.Create("http://masterserver2.raknet.com/testServer") as HttpWebRequest;
+ //JObject obj = new JObject();
+ //obj.Add("__gameId", JToken.Parse("mygame"));
+ /*obj["__gameId"] = "mygame";
+ obj["__clientReqId"] = "0";
+ obj["__timeoutSec"] = "300";
+ obj["__updatePW"] = "up";
+ obj["__readPW"] = "rp";
+ obj["gamename"] = "Test";
+ obj["gameport"] = "60000";*/
+ /*var postData = "{" +
+ "\"__gameId\": \"mygame\"," +
+ "\"__clientReqId\": \"0\"," +
+ "\"__timeoutSec\": \"300\"," +
+ "\"__updatePW\": \"up\"," +
+ "\"__readPW\": \"rp\"," +
+ "\"mapname\": \"DoomCastle\"," +
+ "\"gameport\": \"60000\"" +
+ "}";*/
+ //var data = Encoding.ASCII.GetBytes(postData);
+ /*var data = Encoding.ASCII.GetBytes(obj.ToString());
+ request.Method = "POST";
+ request.ContentType = "application/x-www-form-urlencoded";
+ request.ContentLength = data.Length;
+
+ using (var stream = request.GetRequestStream())
+ {
+ stream.Write(data, 0, data.Length);
+ }
+
+ var response2 = (HttpWebResponse)request.GetResponse();
+
+ responseString = new StreamReader(response2.GetResponseStream()).ReadToEnd();
+ obj = JObject.Parse(responseString);
+ MessageBox.Show(obj.ToString());*/
+
+ }
+ }
+ }
+ public static void Connect(NetMatch match)
+ {
+ MessageBox.Show("Connect to game: " + match.Name + " (" + match.MaxPlayers + " players)");
+ }
+ public static void Leave()
+ {
+ if (ConnectedMatch == null)
+ return;
+ }
+ public static IPAddress[] GetIPs()
+ {
+ //https://msdn.microsoft.com/en-us/library/ee663252%28v=vs.110%29.aspx
+ try
+ {
+ return Dns.GetHostEntry(Dns.GetHostName()).AddressList.Single(entry => entry.AddressFamily == AddressFamily.InterNetworkV6);
+ }
+ catch
+ {
+ MessageBox.Show("Error! Failed to get IP address.\nDoes your system support IPv6?");
+ return null;
+ }
+ }
+ public static Thread ReceiverThread;
+ public static void StartListening()
+ {
+ if (ReceiverThread == null)
+ ReceiverThread = new Thread(new ThreadStart(ThreadRun));
+ }
+ public static void ThreadRun()
+ {
+ MessageBox.Show("Listener thread started.");
}
}
}
diff --git a/SnakeGame/Player.cs b/SnakeGame/Player.cs
new file mode 100644
index 0000000..394dd8c
--- /dev/null
+++ b/SnakeGame/Player.cs
@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SnakeGame
+{
+ public class Player
+ {
+ public static int NextID = 0;
+ public string Name;
+ public Color Color;
+ public int ID;
+ public Player(string name)
+ {
+ Name = name;
+ var values=Enum.GetValues(typeof(KnownColor));
+ KnownColor[] colors = new KnownColor[values.Length];
+ values.CopyTo(colors, 0);
+ Color = Color.FromKnownColor(colors[new Random().Next(colors.Length)]);
+ ID = NextID;
+ NextID++;
+ }
+ }
+}
diff --git a/SnakeGame/Properties/Resources.Designer.cs b/SnakeGame/Properties/Resources.Designer.cs
index 2ccc43d..62eee40 100644
--- a/SnakeGame/Properties/Resources.Designer.cs
+++ b/SnakeGame/Properties/Resources.Designer.cs
@@ -8,10 +8,10 @@
//
//------------------------------------------------------------------------------
-namespace SnakeGame.Properties
-{
-
-
+namespace SnakeGame.Properties {
+ using System;
+
+
///
/// A strongly-typed resource class, for looking up localized strings, etc.
///
@@ -22,48 +22,40 @@ namespace SnakeGame.Properties
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- internal class Resources
- {
-
+ internal class Resources {
+
private static global::System.Resources.ResourceManager resourceMan;
-
+
private static global::System.Globalization.CultureInfo resourceCulture;
-
+
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal Resources()
- {
+ internal Resources() {
}
-
+
///
/// Returns the cached ResourceManager instance used by this class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Resources.ResourceManager ResourceManager
- {
- get
- {
- if ((resourceMan == null))
- {
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SnakeGame.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
-
+
///
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Globalization.CultureInfo Culture
- {
- get
- {
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
return resourceCulture;
}
- set
- {
+ set {
resourceCulture = value;
}
}
diff --git a/SnakeGame/Properties/Settings.Designer.cs b/SnakeGame/Properties/Settings.Designer.cs
index 30862b8..66d28a1 100644
--- a/SnakeGame/Properties/Settings.Designer.cs
+++ b/SnakeGame/Properties/Settings.Designer.cs
@@ -8,21 +8,17 @@
//
//------------------------------------------------------------------------------
-namespace SnakeGame.Properties
-{
-
-
+namespace SnakeGame.Properties {
+
+
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
- internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
- {
-
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
+
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
-
- public static Settings Default
- {
- get
- {
+
+ public static Settings Default {
+ get {
return defaultInstance;
}
}
diff --git a/SnakeGame/SnakeGame.csproj b/SnakeGame/SnakeGame.csproj
index ef2fd1c..6b8121f 100644
--- a/SnakeGame/SnakeGame.csproj
+++ b/SnakeGame/SnakeGame.csproj
@@ -9,8 +9,9 @@
Properties
SnakeGame
SnakeGame
- v4.5
+ v4.5.1
512
+
AnyCPU
@@ -32,8 +33,24 @@
4
+
+ ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll
+
+
+ ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll
+
+
+ ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll
+
+
+ False
+ bin\Debug\Newtonsoft.Json.dll
+
+
+
+
@@ -42,6 +59,7 @@
+
@@ -55,6 +73,8 @@
+
+
@@ -69,7 +89,9 @@
True
Resources.resx
+ True
+
SettingsSingleFileGenerator
Settings.Designer.cs
@@ -84,6 +106,11 @@
+
+
+
+
+