2015.02.28-03.01

This commit is contained in:
Norbi Peti 2017-01-07 23:18:03 +01:00
parent 40f0dd7b4a
commit ddd16cfd3e
14 changed files with 602 additions and 76 deletions

View file

@ -1,6 +1,3 @@
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

View file

@ -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;
}
}

View file

@ -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;
}
}
}

View file

@ -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<int>(delegate(object s, int input)
MSGBox.ShowMSGBox("New singleplayer game", "Size:", MSGBoxType.SizeInput, new EventHandler<string>(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<string>(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<string>(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<SqCoord>(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

View file

@ -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)
{

View file

@ -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<int> 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<string> 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
}
}

24
SnakeGame/NetMatch.cs Normal file
View file

@ -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<string> PlayerNames = new List<string>();
public List<Player> Players = new List<Player>();
public string OwnerName = "";
public IPAddress OwnerIP;
public Player GetPlayerByID(int id)
{
return Players.Single(entry => entry.ID == id);
}
}
}

View file

@ -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<string, string>
{
{ "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<NetMatch> Matches = new List<NetMatch>();
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.");
}
}
}

27
SnakeGame/Player.cs Normal file
View file

@ -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++;
}
}
}

View file

@ -8,10 +8,10 @@
// </auto-generated>
//------------------------------------------------------------------------------
namespace SnakeGame.Properties
{
namespace SnakeGame.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
@ -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() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[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;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[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;
}
}

View file

@ -8,21 +8,17 @@
// </auto-generated>
//------------------------------------------------------------------------------
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;
}
}

View file

@ -9,8 +9,9 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SnakeGame</RootNamespace>
<AssemblyName>SnakeGame</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -32,8 +33,24 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions.Desktop">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Net" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
@ -42,6 +59,7 @@
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
@ -55,6 +73,8 @@
<Compile Include="MenuColorTable.cs" />
<Compile Include="MSGBox.cs" />
<Compile Include="Network.cs" />
<Compile Include="NetMatch.cs" />
<Compile Include="Player.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SquareCoord.cs" />
@ -69,7 +89,9 @@
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
@ -84,6 +106,11 @@
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl" version="1.1.8" targetFramework="net451" />
<package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net451" />
<package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net451" />
</packages>

View file

@ -5,7 +5,47 @@ if(!isset($_POST['client']) || $_POST['client']=="")
<a>Project home</a>";
die();
}
else
{
//echo "Client data";
$conn = mysqli_connect("mysql.hostinger.hu", "u821146919_games", "SLp7q9m60J", "u821146919_games");
if($_POST['client']=="cheesecrescent")
{ //GameList
$res=mysqli_query($conn, "SELECT * FROM games");
while($row=mysqli_fetch_array($res))
{
$namecount=count(explode(',', $row['playernames']));
if($namecount==0 || $row['startdate']<time()-60*60*1000)
{
mysqli_query($conn, "DELETE FROM games
WHERE name='".$row['name']."'
AND ownername='".$row['ownername']."'
AND maxplayers='".$row['maxplayers']."'
AND playernames='".$row['playernames']."'
AND startdate='".$row['startdate']."'
AND ip='".$row['ip']."'
") or die(mysqli_error($conn));
}
else
{
echo $row['name']."|".$row['ownername']."|".$row['maxplayers']."|".$namecount."|".$row['playernames']."|".$row['ip']."|";
}
}
}
else
{
if($_POST['name']=="" || $_POST['maxplayers']=="" || $_POST['client']=="" || $_POST['ip'])
die("A field is or more fields are empty!");
mysqli_query($conn, "INSERT INTO games
(
name, maxplayers, playernames, ownername, startdate, ip
) VALUES (
'".$_POST['name']."', '".$_POST['maxplayers']."', '".$_POST['client']."', '".$_POST['client']."', '".time()."', '".$_POST['ip']."'
)") or die(mysqli_error($conn));
echo "OK";
}
}
//WebPass: vhwfsQOv9E
//fötöpö: (sznpadmin) VKiSh7i1og
//fötöpö: (...sznpadmin) VKiSh7i1og
?>