游戏开发论文 - 图文

更新时间:2024-03-10 12:14:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

游戏开发论文

游戏开发论文

题 目: 大厅五子棋

作 者: 叶志琳(学号07021327)

黄朝辉(学号07021333)

系 别: 计算机系 班级: 软件0701

专 业: 计算机应用技术专业(软件方向)

指导教师: 周长春 专业技术职务 讲师

2009 年 12月 浙江温州

游戏开发论文

前 言

五子棋是起源于中国古代的传统黑白棋种之一。现代五子棋日文称之为

“連珠”,英译为“Renju”,英文称之为“Gobang”或“FIR”(Five in a Row的缩写),亦有“连五子”、“五子连”、“串珠”、“五目”、“五目碰”、“五格”等多种称谓。

五子棋不仅能增强思维能力,提高智力,而且富含哲理,有助于修身养性。五子棋既有现代休闲的明显特征“短、平、快”,又有古典哲学的高深学问“阴阳易理”;它既有简单易学的特性,为人民群众所喜闻乐见,又有深奥的技巧和高水平的国际性比赛;它的棋文化源渊流长,具有东方的神秘和西方的直观;既有“场”的概念,亦有“点”的连接。它是中西文化的交流点,是古今哲理的结晶。

游戏开发论文

目 录

摘 要 ............................................................................................................................. 1 Abstract ............................................................................................................................ 1 第1章 项目概述 ............................................................................................................. 2

1.1 项目背景 ............................................................................................................ 2 1.2 任务概述 ............................................................................................................ 2 第2章 界面设计 ............................................................................................................. 3

2.1 服务端 ................................................................................................................ 3

2.2 客户端 ................................................................................................................ 4 第3章 构造阶段 ............................................................................................................. 8

3.1 核心代码 ............................................................................................................ 8 第4章 论文小结 ........................................................................................................... 53 致 谢........................................................................................................................ 54 参考文献........................................................................................................................ 54

游戏开发论文

摘 要

目前,以计算机技术和网络技术为核心的现代网络技术已在现实生活和生产中得以广泛的使用,休闲类网络游戏集趣味性,娱乐性,互动性和益智性于一体,已经成为多数人群的休闲方式。 本软件使用C#实现,通过对SCOKET技术的理解,在此基础上建立服务器与多客户端的连接,利用多线程处理多个客户端之间的信息。 通过对软件的编写,加深对以上技术的理解和掌握。大厅五子棋的开发能够是朋友们不见面也能下棋和聊天。

关 键 字

多线程;流套接字

Abstract

At present, computer technology and network technology as the core of modern network technology has been in real life and production to be widely used set of casual online games fun, entertaining, interactive and puzzle in one sex has become the majority population of leisure. The software uses the C # to achieve, through SCOKET understanding of technology, in this based on the server and multiple client connections, using multi-threaded processing of information between multiple clients. Through the preparation of the software to enhance the above techniques to understand and grasp. Hall Gobang development can not even meet with friends who can also play chess and

chat.

Keywords

Multithreading; Stream Sockets

1

游戏开发论文

第1章 项目概述

1.1项目背景

当前网络上流传的五子棋游戏功能并不尽善尽美,其中最主要的问题就是人机对战和网络对战不能够一起实现,所以我决定开发一个既能够人机对战,又能够进行网络对战的五子棋系统。

1.2 任务概述

1.2.1实现目标

? ?

实现在线下棋

实现多人在线互动交互.

2

游戏开发论文

第2章 界面设计

2.1服务端

2.1.1初始

如图2. 1 初始

图2. 1 初始

2.1.2启动服务

如图2. 2 启动服务

3

游戏开发论文

图2. 2 启动服务

2.2客户端

2.2.1初始

如图2. 1 初始图2. 3 初始

图2. 3 初始

4

游戏开发论文

2.2.2连接服务端

如图2. 1 初始图2. 4 连接服务器

2.2.3会员登陆

如图2. 5 会员登陆

2.2.4游戏界面

如图2. 6 游戏界面1 如图2. 7 游戏界面2 如图2. 8 游戏界面3

图2. 4 连接服务器

图2. 5 会员登陆

5

游戏开发论文

图2. 6 游戏界面1

图2. 7 游戏界面2

6

游戏开发论文

图2. 8 游戏界面3

7

游戏开发论文

第3章 构造阶段

3.1核心代码

3.1.1 服务端

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;

using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; using System.Collections; using System.Data.SqlClient; namespace FiveServer {

public partial class FiveServer : Form {

private Socket mainSocket;

public delegate void UpdateRichEditCallback(string text); public delegate void UpdateClientListCallback(); public AsyncCallback pfnWorkerCallback; public string username; public int userpicture;

private ArrayList workerSocketList = ArrayList.Synchronized(new ArrayList()); private int clientNum = 0;//客户的编号 private string all_table;//所有房间座位信息 static public string clientmsg=\; public FiveServer() {

InitializeComponent(); }

private void button1_Click(object sender, EventArgs e) { try

8

游戏开发论文

{

if (txtPort.Text == \) {

MessageBox.Show(\请先填写服务器端口!\, \提示\); return; }

Int32 port = Int32.Parse(txtPort.Text);

mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port); mainSocket.Bind(localEP);//将socket绑定到本地终接点上 mainSocket.Listen(5);

mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);//开始一个异步操作接受客户的连接请求

UpdateControls(true);

}

catch (SocketException se) {

MessageBox.Show(se.Message, \提示\); } }

private void FiveServer_Load(object sender, EventArgs e) { try {

txtIP.Text = Dns.Resolve(Dns.GetHostName()).AddressList[0].ToString(); UpdateControls(false); }

catch (Exception exc) {

MessageBox.Show(exc.Message, \提示\); } }

private void button2_Click(object sender, EventArgs e) {

CloseSockets(); UpdateControls(false);

UpdateClientListControl();//更新客户列表 }

private void button5_Click(object sender, EventArgs e)//发送

9

游戏开发论文

{

if (clientList.Items.Count != 0) { try {

string msg = txtSendMsg.Text; msg = \ + msg + \;

byte[] byData = System.Text.Encoding.UTF8.GetBytes(msg); Socket workerSocket = null;

for (int i = 0; i < workerSocketList.Count; i++) {

workerSocket = (Socket)workerSocketList[i]; if (workerSocket != null) {

if (workerSocket.Connected) {

workerSocket.Send(byData); } } } }

catch (SocketException se) {

MessageBox.Show(se.Message, \提示!\); } } else {

MessageBox.Show(\没有在线客户,不能发送信息\, \提示\); } }

private void button4_Click(object sender, EventArgs e) {

CloseSockets(); Close(); }

private void button3_Click(object sender, EventArgs e) {

txtRecvMsg.Clear(); }

//关闭socket void CloseSockets()

10

游戏开发论文

{

if (mainSocket != null) {

mainSocket.Close(); }

Socket workerSocket = null;

for (int i = 0; i < workerSocketList.Count; i++) {

workerSocket = (Socket)workerSocketList[i]; if (workerSocket != null) {

workerSocket.Close(); workerSocket = null; } } }

//更新客户列表

private void UpdateClientListControl() {

if (InvokeRequired) {

clientList.BeginInvoke(new UpdateClientListCallback(UpdateClientList), null); } else {

UpdateClientList(); } }

void UpdateClientList() {

clientList.Items.Clear();

for (int i = 0; i < workerSocketList.Count; i++) {

string clientkey = Convert.ToString(i + 1); Socket workerSocket = (Socket)workerSocketList[i]; if (workerSocket != null) {

if (workerSocket.Connected) {

clientList.Items.Add(clientkey); } } } }

11

游戏开发论文

//添加信息到txtRecvMsg中

private void OnUpdateRichEdit(string msg) {

txtRecvMsg.Text = txtRecvMsg.Text + msg; }

private void AppendToRichEditControl(string msg) {

if (InvokeRequired) {

object[] pList ={ msg };

txtRecvMsg.BeginInvoke(new UpdateRichEditCallback(OnUpdateRichEdit), pList); } else {

OnUpdateRichEdit(msg); } }

private void UpdateControls(bool onServer) {

button1.Enabled = !onServer; button2.Enabled = onServer; if (onServer) {

status.Text = \服务器启动\; } else {

status.Text = \服务器断开\; } }

//回调函数

public void OnClientConnect(IAsyncResult asyn) { try {

Socket workerSocket = mainSocket.EndAccept(asyn);//调用EndAccept完成BeginAccept异步调用,返回一个新的Socket的处理与客户的通信

Interlocked.Increment(ref clientNum);//增加客户数目

workerSocketList.Add(workerSocket);//将workersocket socket加入到ArrayList中

string msg1 = \客户\ + clientNum + \连接上服务器\\n\; AppendToRichEditControl(msg1);//客户登陆信息 //*********************

string msg = clientNum.ToString();

12

游戏开发论文

SendWelcomeToClient(msg, clientNum);//发送客户编号信息给该客户 UpdateClientListControl();

WaitForData(workerSocket, clientNum);//连接上的客户接收数据

mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);//主Socket返回,继续接收其他的连接请求 }

catch (ObjectDisposedException) {

System.Diagnostics.Debugger.Log(0, \, \已经关闭!\\n\); }

catch (SocketException se) {

MessageBox.Show(se.Message, \提示\); } }

private void SendWelcomeToClient(string msg, int clientNumber) {

Byte[] byData = System.Text.Encoding.UTF8.GetBytes(msg);

Socket workerSocket = (Socket)workerSocketList[clientNumber - 1]; //将数据发给客户 workerSocket.Send(byData);

// MessageBox.Show(\返回客户参数:\ /*

Socket workerSocket = (Socket)workerSocketList[clientNumber - 1]; NetworkStream networkstream = new NetworkStream(workerSocket);

System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkstream); streamWriter.WriteLine(msg); streamWriter.Flush(); */ }

private void SendToClient(string msg, int clientNumber) {

Byte[] byData = System.Text.Encoding.UTF8.GetBytes(msg); Socket workerSocket = (Socket)workerSocketList[clientNumber - 1]; NetworkStream networkstream = new NetworkStream(workerSocket);

System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkstream); streamWriter.WriteLine(msg); streamWriter.Flush(); }

public class SocketPacket {

public System.Net.Sockets.Socket currentSocket;

13

游戏开发论文

public int clientNumber;

public byte[] dataBuffer = new byte[1024];//发给服务器的数据

public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber) {

currentSocket = socket;

this.clientNumber = clientNumber; } }

public void WaitForData(System.Net.Sockets.Socket socket, int clientNumber) { try {

if (pfnWorkerCallback == null) {

pfnWorkerCallback = new AsyncCallback(OnDataReceived); }

SocketPacket socketpacket = new SocketPacket(socket, clientNumber); socket.BeginReceive(socketpacket.dataBuffer, 0,

socketpacket.dataBuffer.Length, SocketFlags.None, pfnWorkerCallback, socketpacket);

}

catch (SocketException se) {

MessageBox.Show(se.Message, \提示\); } }

public void OnDataReceived(IAsyncResult asyn) {

SocketPacket socketData = (SocketPacket)asyn.AsyncState; try {

int iRx = socketData.currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1];

System.Text.Decoder decoder = System.Text.Encoding.UTF8.GetDecoder(); int charLen = decoder.GetChars(socketData.dataBuffer, 0, iRx, chars, 0); System.String receivemsg = new System.String(chars); String substr; substr = \;

if (receivemsg.Length > 4) {

substr = receivemsg.Substring(0, 4); }

14

游戏开发论文

if (substr == \)//聊天信息 {

MessageBox.Show(\); String tmp1 = \;

tmp1 = receivemsg.Substring(4);

string[] s = tmp1.Split(new Char[] { ',' });

string clientmsg = \客户\ + socketData.clientNumber + \ + s[0] + \说:\ + s[1];

AppendToRichEditControl(clientmsg); }

if (substr == \)//退出信息 {

String tmp1 = \;

tmp1 = receivemsg.Substring(4); SqlConnection conn = new

SqlConnection(\); conn.Open(); string ke_name =

tmp1.ToString().Substring(0,tmp1.ToString().Length-3) ;//tmp1.ToString()含回车换行\\r\\n\\0符需去掉

string updata11 = %username='\ + ke_name + \;

SqlCommand comm11 = new SqlCommand(updata11, conn); comm11.ExecuteNonQuery(); conn.Close();

string outmsg = \客户\ + socketData.clientNumber + \已经断开连接!\\n\; AppendToRichEditControl(outmsg);

workerSocketList[socketData.clientNumber - 1] = null; UpdateClientListControl(); // disconnect();

}

if (substr == \)//房间信息 {

String tmp1 = \;

tmp1 = receivemsg.Substring(4);

string[] s = tmp1.Split(new Char[] { ',' });

all_table = all_table + \ + s[0] + \ + s[1] + \ + s[2] + \ + Convert.ToInt16(s[3]).ToString();

//********************向所有用户的客户端大厅发送座位信息 for (int i = 1; i <= clientNum; i++) {

SendToClient(\ + all_table, i);

15

游戏开发论文

} SqlConnection conn = new

SqlConnection(\); conn.Open();

string house_id = Convert.ToInt16(s[1]).ToString();//用户选择的房间号 string updatehouseid = \ + house_id + \where username='\ + s[0].ToString() + \;

SqlCommand comm11 = new SqlCommand(updatehouseid, conn); comm11.ExecuteNonQuery();

{

online = {

a[n,0] = myread.GetValue(4).ToString(); a[n,1] = myread.GetValue(2).ToString(); n++; } }

{

SendToClient(用户发对方IP

SendToClient(的用户发对方IP }

conn.Close();

}

{

tmp1 = receivemsg.Substring(4);

//*******************判断一个房间同桌是否已经两人

string selectstr = \ + house_id; SqlCommand da = new SqlCommand(selectstr, conn); SqlDataReader myread = da.ExecuteReader(); int n = 0;

String [ ,]a=new String[2,2] ; int online=0;

while (myread.Read()) Convert.ToInt32(myread.GetValue(5).ToString());//在线 if (online == 1) //IP //客户号 if (n == 2) \ + a[0,0], Convert.ToInt16(a[1,1]));//向一个房间的\ + a[1, 0], Convert.ToInt16(a[0, 1]));//向一个房间//******************** if (substr == \)//注册信息 String tmp1 = \;

16

游戏开发论文

string[] s = tmp1.Split(new Char[] { ',' }); String strsql;

strsql = \values ('\ + s[0].ToString() + \ + s[1].ToString() + \ + s[2].ToString() + \ + s[3].ToString() + \;

string us = null; us = s[0];

string selectstr = \* from userinfo where username='\ + us.ToString() + \;

SqlConnection conn = new

SqlConnection(\); conn.Open();

SqlCommand da = new SqlCommand(selectstr, conn); SqlDataReader myread = da.ExecuteReader(); if (myread.Read()) {

MessageBox.Show(s[0] + \帐号已经被注册\); } else { try {

myread.Close();

SqlCommand updatauser = new SqlCommand(strsql, conn); updatauser.ExecuteNonQuery();

// MessageBox.Show(\成功\。\ string clientmsg3 = \ + us.ToString(); SendToClient(clientmsg3, clientNum);

} catch {

// MessageBox.Show(\帐号创建失败\ string clientmsg0 = \;

SendToClient(clientmsg0, clientNum); } }

conn.Close();

}

if (substr == \)//验证信息 //****用户名,密码,本机IP,客户编号 {

String tmp1 = \;

17

游戏开发论文

tmp1 = receivemsg.Substring(4);

string[] s = tmp1.Split(new Char[] { ',' });

String strsql;

strsql = \ + s[0].ToString() + \and userpwd= '\ + s[1].ToString() + \; SqlConnection conn = new

SqlConnection(\); conn.Open();

SqlCommand da = new SqlCommand(strsql, conn); SqlDataReader myread = da.ExecuteReader(); if(myread.Read()) {

// MessageBox.Show(s[0] + \帐号通过\ username = myread.GetString(0);

userpicture = Convert.ToInt32(myread.GetValue(3).ToString()); myread.Close();

string updata11 = \ + s[2].ToString() + \ + s[3].ToString() + \ + s[0].ToString() + \; SqlCommand comm11 = new SqlCommand(updata11, conn); comm11.ExecuteNonQuery();

clientmsg = \ + username + \ + userpicture;

} else {

clientmsg = \; }

SendToClient(clientmsg, clientNum);

//*********向该用户的客户端大厅发送座位信息 SendToClient(\ + all_table, clientNum); //****** clientmsg = \; conn.Close(); }

//System.String szData = new System.String(chars);

//string msg = \客户\发的信息\ //AppendToRichEditControl(msg);

WaitForData(socketData.currentSocket, socketData.clientNumber); }

catch (ObjectDisposedException) {

System.Diagnostics.Debugger.Log(0, \, \已经关闭

18

游戏开发论文

\\n\);

}

catch (SocketException se) {

if (se.ErrorCode == 10054) {

string msg = \客户\ + socketData.clientNumber + \已经断开连接!\\n\; AppendToRichEditControl(msg);

workerSocketList[socketData.clientNumber - 1] = null; UpdateClientListControl(); } else {

MessageBox.Show(se.Message, \提示\); } } } } }

3.1.2 客户端

(1) 会员登陆

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;

using System.Windows.Forms; using System.IO; using System.Net;

using System.Net.Sockets; namespace Fiveclient {

public partial class FiveStart : Form {

static public bool isgoon=false;//没进行验证 static public string passmsg;//验证内容 public FiveStart() {

InitializeComponent(); }

19

游戏开发论文

private void button1_Click(object sender, EventArgs e) { passmsg = \;

passmsg = \ + textBox1.Text + \ + textBox2.Text; isgoon = true; this.Close(); }

private void button3_Click(object sender, EventArgs e) { }

private void button2_Click(object sender, EventArgs e) {

this.Dispose(); isgoon = false; }

private void FiveStart_Load(object sender, EventArgs e) {

isgoon = false; } } }

(2) 设置连接服务器

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;

using System.Windows.Forms;

namespace Fiveclient {

public partial class FiveSetconnect : Form {

public FiveSetconnect()

20

游戏开发论文

{

InitializeComponent(); }

private void button1_Click(object sender, EventArgs e) {

Fivehouse.portNum = System.Convert.ToInt32(textBox2.Text, 10); Fivehouse.serverip = textBox1.Text; try {

Fivehouse.myclient = new System.Net.Sockets.TcpClient(Fivehouse.serverip, Fivehouse.portNum); } catch {

MessageBox.Show(\服务器拒绝连接请求\,\信息\); return; }

Fivehouse.networkClient = Fivehouse.myclient.GetStream();//获取网络流 byte[] read = new byte[2];

int bytes = Fivehouse.networkClient.Read(read, 0, read.Length);//读取的字节数 if (bytes >0) {

Fivehouse.isConnecting = true; Fivehouse.startthreads(); Fivehouse.in_id =

Convert.ToInt16( System.Text.Encoding.Unicode.GetString(read)); MessageBox.Show(\建立连接成功\, System.Text.Encoding.Unicode.GetString(read)); this.Close(); } }

private void button2_Click(object sender, EventArgs e) {

this.Dispose(); } } }

(3) 用户注册

using System;

21

游戏开发论文

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;

using System.Windows.Forms;

namespace Fiveclient {

public partial class FiveLogin : Form {

static public string regmsg;//注册内容 public FiveLogin() {

InitializeComponent(); }

private void button1_Click(object sender, EventArgs e) {

if (username.Text == \) {

MessageBox.Show(\用户不能为空\); username.Text = \; return; }

if (userpwd1.Text == \ || userpwd2.Text == \) {

MessageBox.Show(\密码不能为空\); userpwd1.Text = \; userpwd1.Text = \; return; }

if (userpwd1.Text != userpwd2.Text) {

MessageBox.Show(\前后密码不对\); return; }

if (useremail.Text == \) {

MessageBox.Show(\不能为空\); useremail.Text = \; return; }

if (comboBox1.Text == \)

22

游戏开发论文

{

MessageBox.Show(\请选择头像\); comboBox1.Text = \; return; }

regmsg=\;

regmsg = \ + username.Text + \ + userpwd1.Text + \ + useremail.Text + \ + comboBox1.Text;

this.Close(); }

private void button2_Click(object sender, EventArgs e) {

this.Dispose(); }

private void pictureBox1_Click(object sender, EventArgs e) {

}

private void label5_Click(object sender, EventArgs e) {

}

private void FiveLogin_Load(object sender, EventArgs e) {

}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {

string filename = @\ + (comboBox1.SelectedIndex + 1) + \; pictureBox1.Image = Image.FromFile(filename); } } }

(4) 游戏大厅

using System;

using System.Collections.Generic; using System.ComponentModel;

23

游戏开发论文

using System.Data; using System.Drawing; using System.Text;

using System.Windows.Forms; using System.Configuration; using System.Net.Sockets; using System.IO; using System.Net; using System.Threading; namespace Fiveclient {

public partial class Fivehouse : Form {

private FiveSetconnect setcon;

static public bool isreguser=false; //判断是否注册用户 static public bool isConnecting = false; static public int portNum; static public string serverip; static public string message=\; public string speakmessage = \;

static public string inreguser=\用户名\;//登陆用户名 static public string inregpicture =\;//登陆用户照片信息 static public bool inregposition = false;//登陆用户是否坐上桌子 static public int in_id ;//登陆用户编号 static public string other_ip;//对方IP static public int table;//用户座位号

static string all_table;//服务器转发的登陆用户座位信息

static public string myserveraddress;

static public int[]islable ={ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //lable设置

//网络数据

private const string infDisconnect = \;//断开标志 static public NetworkStream networkClient; static public Thread recvThread; static public TcpClient myclient; static public StreamWriter streamWriter;

static public StreamReader streamReader; public Fivehouse() {

InitializeComponent(); }

24

游戏开发论文

static public void startthreads() {

if (recvThread == null) {

recvThread = new Thread(new ThreadStart(ReceiveMsg)); recvThread.Start(); } }

static public void ReceiveMsg() {

while (isConnecting) {

ReceiveMsg(myclient, networkClient); }

// MessageBox.Show(\与服务器断开了连接\

}

public void getmessage(string message) {

listBox1.Items.Add(message); }

static public void ReceiveMsg(TcpClient tcpc, NetworkStream ns) { try {

String strout;//接收数据 String substr = \; String tmp1 = \; ns = tcpc.GetStream();

streamReader = new StreamReader(ns); strout = streamReader.ReadLine(); if (strout.Length >= 4) {

substr = strout.Substring(0, 4); tmp1 = strout.Substring(4); }

if (string.Compare(strout, infDisconnect) == 0) {

string strdcnt = \连接被中断.\\n\; MessageBox.Show(strdcnt); ns.Close(); tcpc.Close();

25

游戏开发论文

isConnecting = false; }

if (substr == \)//获取聊天信息 {

// MessageBox.Show(\受到服务器信息\

string[] s = tmp1.Split(new Char[] { ',' }); message = \服务器说:\ + s[0].ToString() +\。\;

}

if (substr == \)//获取同桌对方IP {

//MessageBox.Show(\获取对方IP\ other_ip = tmp1; }

if (substr == \)//获取服务器发送的房间座位信息 {

all_table = tmp1;

string message2=\获取服务器发送的房间座位信息\+ tmp1; }

if (substr == \) {

//MessageBox.Show(strout);

string[] s = tmp1.Split(new Char[] { ',' });

message = \登陆成功...欢迎\ + s[0].ToString() + \登陆本系统\; inreguser = s[0].ToString();

inregpicture = s[1].ToString(); isreguser = true; }

if (strout == \) {

message=\验证失败!\; }

if (substr == \) {

message=\恭喜您,帐号注册成功\ ; }

if (strout == \) {

message=\抱歉,注册失败...\; }

if (strout == \)//获取在线信息

26

游戏开发论文

{ } //else //{

// MessageBox.Show(strout); //} } catch {

MessageBox.Show(\安全退出\,\提示\); }

}

public void disconnect(TcpClient tcpc, NetworkStream ns) {

byte[] write = new byte[64];

write = Encoding.Unicode.GetBytes(infDisconnect.ToCharArray()); ns.Write(write, 0, write.Length); ns.Close(); tcpc.Close(); disconnect();

}

public void disconnect() { if (isConnecting) {

recvThread.Abort(); }

isConnecting = false;//断开标志 }

private void Fivehouse_Load(object sender, EventArgs e) {

if (message != \) {

getmessage(message); message = \; }

if (isConnecting) //判断是否连接 {

if (isreguser)//判断是否登陆

27

游戏开发论文

{

speakout.Enabled = true;

show_inuser.Text = Convert.ToString(inreguser);

if (all_table != null&&all_table!=\) {

string[] s = all_table.Split(new Char[] { ',' }); string new_picture, new_table;

for (int i = 1; i < s.Length; i = i + 4) {

new_picture = s[i + 3].ToString();//头像 new_table = s[i + 2].ToString();//座位信息 if (new_table == \)

{ islable[1] = 1; label1.Image = Image.FromFile(@\ + new_picture + \); }

if (new_table == \)

{ islable[2] = 1; label2.Image = Image.FromFile(@\ + new_picture + \);} if (new_table == \)

{ islable[3] = 1; label3.Image = Image.FromFile(@\ + new_picture + \);} if (new_table == \)

{ islable[4] = 1; label4.Image = Image.FromFile(@\ + new_picture + \); } } }

this.Text = other_ip;

} else {

this.Text = \游戏大厅\ + \当前时间\ + DateTime.Now.ToString() + \ + DateTime.Now.DayOfWeek.ToString();

show_ip.Text = Convert.ToString(NetWork.getmyIP()); button10.Enabled = true; button11.Enabled = true; stop_return.Enabled = true; con_server.Enabled = false; } } else {

button10.Enabled = false;

28

游戏开发论文

button11.Enabled = false; speakout.Enabled = false; stop_return.Enabled = false; } }

private void button11_Click(object sender, EventArgs e) {

FiveLogin reg = new FiveLogin(); reg.ShowDialog();

listBox1.Items.Add(\连接注册服务器...\); SendMsg(networkClient, FiveLogin.regmsg);//发送注册信息 FiveLogin.regmsg = \; }

static public void SendMsg(NetworkStream ns, string tmp) {

streamWriter = new StreamWriter(ns); streamWriter.WriteLine(tmp); streamWriter.Flush(); }

private void button10_Click(object sender, EventArgs e) {

FiveStart go = new FiveStart(); go.ShowDialog(); if (FiveStart.isgoon) {

if (isConnecting) {

string msg11 = FiveStart.passmsg + ',' + Convert.ToString(NetWork.getmyIP())+','+in_id.ToString() ; listBox1.Items.Add(\用户验证中...\);

SendMsg(networkClient, msg11);//发送验证请求 FiveStart.passmsg = \; } } }

private void con_server_Click(object sender, EventArgs e) {

29

游戏开发论文

listBox1.Items.Add(\准备连接服务器\); setcon = new FiveSetconnect(); setcon.ShowDialog(); if (isConnecting) {

listBox1.Items.Add(\连接成功!\ + DateTime.Now.ToString()); // Fivehouse.startthreads(); } else {

listBox1.Items.Add(\连接失败!\); } }

public void stop_return_Click(object sender, EventArgs e) {

isreguser = false; for (int i = 0; i <18; i++) {

islable[i] = 0; }

label12=new Label(); label13.Invalidate(); label14.Invalidate();

this.pictureBox1.Invalidate();

this.listBox1.Items.Add(\用户\+inreguser+\已经退出!\); inreguser = \; show_inuser.Text = \; this.Invalidate(); }

private void button1_Click(object sender, EventArgs e) {

string tmp = \ + Convert.ToString(inreguser) + \ + \ + table.ToString() +\+ inregpicture;

SendMsg(networkClient, tmp); FiveGame five = new FiveGame(); five.ShowDialog(); }

private void button2_Click(object sender, EventArgs e) {

30

游戏开发论文

string tmp = \ + Convert.ToString(inreguser) + \ + \ + table.ToString() + \ + inregpicture;

SendMsg(networkClient, tmp); FiveGame five = new FiveGame(); five.ShowDialog();

}

private void button3_Click(object sender, EventArgs e) {

string tmp = \ + Convert.ToString(inreguser) + \ + \ + table.ToString() + \ + inregpicture;

SendMsg(networkClient, tmp); FiveGame five = new FiveGame(); five.ShowDialog();

}

//button4---button9略

private void label1_Click(object sender, EventArgs e) {

if (islable[1] == 0) {

if (inregposition) {

MessageBox.Show(\你已经坐进了其他位子\); } else {

label1.Image = Image.FromFile(@\ + inregpicture + \); inregposition = true; islable[1] = 1; table = 1;

button1.Enabled = true; } } else {

MessageBox.Show(\已经有人坐在这里了!请换位\); }

}

private void label2_Click(object sender, EventArgs e)

31

游戏开发论文

{

if (islable[2] == 0) {

if (inregposition) {

MessageBox.Show(\你已经坐进了其他位子\); } else {

label2.Image = Image.FromFile(@\ + inregpicture + \); inregposition = true; islable[2] = 1; table = 2;

this.button1.Enabled = true; } } else {

MessageBox.Show(\已经有人坐在这里了!请换位\); } }

private void label3_Click(object sender, EventArgs e) {

if (islable[3]== 0) {

if (inregposition) {

MessageBox.Show(\你已经坐进了其他位子\); } else {

label3.Image = Image.FromFile(@\ + inregpicture + \); inregposition = true; islable[3] = 1; table = 3;

this.button2.Enabled = true; } } else {

MessageBox.Show(\已经有人坐在这里了!请换位\); }

32

游戏开发论文

}

private void label4_Click(object sender, EventArgs e) {

if (islable[4] == 0) {

if (inregposition) {

MessageBox.Show(\你已经坐进了其他位子\); } else {

label5.Image = Image.FromFile(@\ + inregpicture + \); inregposition = true; islable[4] = 1; table = 4;

this.button2.Enabled = true; } } else {

MessageBox.Show(\已经有人坐在这里了!请换位\); } }

private void label5_Click(object sender, EventArgs e) {

if (islable[5] == 0) {

if (inregposition) {

MessageBox.Show(\你已经坐进了其他位子\); } else {

label4.Image = Image.FromFile(@\ + inregpicture + \); inregposition = true; islable[5] = 1; table = 5;

this.button3.Enabled = true; } } else {

33

游戏开发论文

MessageBox.Show(\已经有人坐在这里了!请换位\); } }

private void label6_Click(object sender, EventArgs e) {

if (islable[6] == 0) {

if (inregposition) {

MessageBox.Show(\你已经坐进了其他位子\); } else {

label8.Image = Image.FromFile(@\ + inregpicture + \); inregposition = true; islable[6] = 1; table = 6;

this.button3.Enabled = true; } } else {

MessageBox.Show(\已经有人坐在这里了!请换位\); } }

//label7---label18略

private void speakout_Click(object sender, EventArgs e) {

if (textBox1.Text != \) {

speakmessage = \ + inreguser +\+ textBox1.Text; listBox1.Items.Add(inreguser + \说:\ + textBox1.Text); SendMsg(networkClient, speakmessage); speakmessage=\; } }

private void Fivehouse_FormClosed(object sender, FormClosedEventArgs e) {

if (isConnecting) {

34

游戏开发论文

//listBox1.Items.Add(\退出服务器...\

string msgoutserver = \ + Convert.ToString(inreguser); SendMsg(networkClient, msgoutserver); myclient.Close(); networkClient.Close(); }

isConnecting = false; } } }

(5) 五子棋对战

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;

using System.Windows.Forms;

namespace Fiveclient {

public partial class FiveGame : Form {

///

/// 是否轮到我 /// private bool Myturn;

Bitmap oldbmp, usingbmp; IsWin iswin; gobang five; private bool onebodyin = false; static public bool isplaying = false; static public string speakmessage = \; static public string returnid = \; static public string reip = \; static public string relevel = \; NetWork network = new NetWork(); string infor, oldinfor; public FiveGame() {

InitializeComponent(); }

35

游戏开发论文

private void FiveGame_Load(object sender, EventArgs e) {

//if(speakmessage != \ //{

// getmessage(speakmessage); // speakmessage = \ //}

listBox1.Items.Add(Fivehouse.inreguser+\进入了游戏!\); usingbmp = oldbmp = new Bitmap(this.pictureBox1.Image); listView1.Items.Add(Fivehouse.inreguser, 0); listView1.Items[0].SubItems.Add(\);

listView1.Items[0].SubItems.Add(Convert.ToString(NetWork.getmyIP()));

}

private void UpdateControls(bool onServer) {

buildGamebutton.Enabled = !onServer; Joinbutton.Enabled = !onServer; Rebuildbutton.Enabled = onServer; overgame.Enabled = onServer; StopNetbutton.Enabled = onServer; if (onServer) {

status.Text = \连接中...\; } else {

status.Text = \断开连接\; } }

private void sendmsg_Click(object sender, EventArgs e) {

listBox1.Items.Add(Fivehouse.inreguser+\说:\+ userspeak.Text); string speakout=userspeak.Text.ToString(); string userid=Fivehouse.inreguser.ToString(); network.Send(speakout, userid); // getmessage(speakmessage); }

public void getmessage(string msg,string id) {

36

游戏开发论文

listBox1.Items.Add(id + \说:\+msg); }

private void Rebuildbutton_Click(object sender, EventArgs e) {

usingbmp = oldbmp = new Bitmap(this.pictureBox1.Image); pictureBox1.Enabled = true;

this.pictureBox1.Invalidate(); this.pictureBox1.Refresh(); //this.panel1.Invalidate(); }

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) {

if (onebodyin) try {

five.pointx = e.X - 21; five.pointy = e.Y - 24;

five.cheesemove(this.pictureBox1, this.Myturn); } catch { } }

private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {

if(this.Myturn)

this.label1.Text=t1;

{

if(five.CanDown()) {

try {

string

network.Send(sendinfor); string t1,t2;

this.pictureBox1.Image=five.DownthePoint(out t1,out t2);

sendinfor=five.cellx.ToString()+\+five.celly.ToString()+\+(five.myturn);

37

游戏开发论文

}

}

this.label2.Text=t2;

Myturn=false;

catch(Exception ex) { }

MessageBox.Show(ex.Message);

private void NewGamebutton_Click(object sender, EventArgs e) {

IPtextBox.Text = Convert.ToString(NetWork.getmyIP());

listBox1.Items.Add(Fivehouse.inreguser + \建立游戏,等待玩家进入\);

}

} try { } catch { }

this.st.Text=\游戏还没有开始,无法下棋\; if(iswin.Win(five.cellx,five.celly)==5) { }

if(iswin.Win(five.cellx,five.celly)==-5) { }

MessageBox.Show(\游戏结束,黑方胜利\); //this.pictureBox1.Enabled=false; //this.timer1.Stop(); //this.network.StopListen();

MessageBox.Show(\游戏结束,白方胜利\); //this.pictureBox1.Enabled=false; this.st.Text=\游戏结束,白方胜利\; //this.timer1.Stop(); //this.network.StopListen();

this.pictureBox1.Invalidate();

this.pictureBox1.Invalidate();

38

游戏开发论文

UpdateControls(true); five=new gobang();

five.AddBmp(usingbmp,new Bitmap(this.pictureBox4.Image),new iswin=new IsWin(five.down); this.pictureBox1.Enabled=true; this.pictureBox1.Image=oldbmp; this.pictureBox1.Refresh(); network.Listen(); this.timer1.Start(); this.Myturn=true; this.onebodyin=false;

Bitmap(this.pictureBox5.Image));

}

private void startchess() {

IPtextBox.Text = Convert.ToString(NetWork.getmyIP());

//listBox1.Items.Add(Fivehouse.inreguser + \建立游戏,等待玩家进入\ UpdateControls(true); five = new gobang();

five.AddBmp(usingbmp, new Bitmap(this.pictureBox4.Image), new Bitmap(this.pictureBox5.Image));

iswin = new IsWin(five.down); this.pictureBox1.Enabled = true; this.pictureBox1.Image = oldbmp; this.pictureBox1.Refresh(); network.Listen(); this.timer1.Start(); this.Myturn = true; this.onebodyin = false;

}

private void Joinbutton_Click(object sender, EventArgs e) {

if(this.IPtextBox.Text==\)

{ }

network.IP=IPtextBox.Text; string sta=\;

network.Send(ref sta,NetWork.getmyIP()+\加入游戏!\); if(sta==\) {

MessageBox.Show(\对方IP还没有配置,请点击配置\); return;

39

游戏开发论文

startchess();

listBox1.Items.Add(\加入对方主机成功!游戏建立\);

string userid = Fivehouse.inreguser.ToString(); string userip=Convert.ToString(NetWork.getmyIP()); network.Send(userid,userip,\);

} else { }

this.Myturn=false;

this.st.Text=sta;

this.onebodyin=true;

this.Joinbutton.Enabled=false; this.buildGamebutton.Enabled=false;

isplaying = true;

}

private void timer1_Tick(object sender, EventArgs e) {

this.st.Text = this.network.sta; string nowinfor;

infor = this.network.infor; if (oldinfor != infor)//有新消息 {

// this.netinforlable.Text = infor; try {

int dot = infor.IndexOf(\);

five.cellx = Convert.ToInt32(infor.Substring(0, dot)); nowinfor = infor.Substring(dot + 1); dot = nowinfor.IndexOf(\);

five.celly = Convert.ToInt32(nowinfor.Substring(0, dot)); nowinfor = nowinfor.Substring(dot + 1); five.myturn = Convert.ToBoolean(nowinfor); string t1, t2;

this.pictureBox1.Image = five.DownthePoint(out t1, out t2); //对方下棋

this.label1.Text = t1; this.label2.Text = t2;

if (iswin.Win(five.cellx, five.celly) == 5) {

40

游戏开发论文

this.st.Text = \游戏结束,白方胜利\; this.timer1.Stop();

//this.network.StopListen(); this.pictureBox1.Enabled = false; }

if (iswin.Win(five.cellx, five.celly) == -5) {

this.st.Text = \游戏结束,黑方胜利\; this.timer1.Stop();

// this.network.StopListen(); this.pictureBox1.Enabled = false; }

this.Myturn = true; } catch {

this.st.Text = infor; try {

if (infor.IndexOf(\加\) > 0) onebodyin = true;

string joinedip = infor.Substring(0, infor.IndexOf(\加\)); IPtextBox.Text = network.IP = joinedip; } catch {

} } }

oldinfor = infor; }

private void IPtextBox_TextChanged(object sender, EventArgs e) {

}

private void userspeak_TextChanged(object sender, EventArgs e) {

}

private void pictureBox1_Click(object sender, EventArgs e)

41

游戏开发论文

{

}

private void StopNetbutton_Click(object sender, EventArgs e) {

network.StopListen(); UpdateControls(false); }

private void overgame_Click(object sender, EventArgs e) {

}

private void timer2_Tick(object sender, EventArgs e) {

IPtextBox.Text = Fivehouse.other_ip; //对方IP ********* if (speakmessage != \ && returnid!=\) {

getmessage(speakmessage,returnid); speakmessage = \; returnid = \; }

if (returnid != \ && reip != \ & relevel != \) {

setuser(returnid, reip, relevel); reip = \; returnid = \; relevel =\; } }

private void setuser(string uid,string uip,string ulevel) {

//string ll=Convert.

listView1.Items.Add(uid, 0);

listView1.Items[0].SubItems.Add(ulevel); listView1.Items[0].SubItems.Add(uip); }

private void FiveGame_FormClosed(object sender, FormClosedEventArgs e) {

timer2.Enabled = false;

42

游戏开发论文

}

} }

(6) 类

using System;

using System.Collections.Generic; using System.Text; using System.Drawing; namespace Fiveclient {

public class gobang {

public gobang() { //

// TODO: 在此处添加构造函数逻辑 // }

~gobang() { }

public int[,] down = new int[25, 25]; public int cellx, celly, oldcellx, oldcelly; public bool myturn = true; private int r = 35;

public int whitenum = 0, blacknum = 0, pointx, pointy; public Bitmap bmp, bmpb, bmpw;

public void AddBmp(Bitmap map, Bitmap white, Bitmap black) {

this.bmp = map; this.bmpw = white; this.bmpb = black; }

///

/// 返回是否可以在此处下子 ///

/// public bool CanDown() {

if (down[cellx, celly] == 0) return true;

43

游戏开发论文

else return false; }

private Bitmap Down() {

int x = cellx * r + 5; int y = celly * r + 8; if (myturn)

for (int w = 0; w < bmpw.Width; w++) {

for (int h = 0; h < bmpw.Height; h++) {

Color color = bmpw.GetPixel(w, h);

if (color.R == 0 && color.G == 0 && color.B == 255) continue;

bmp.SetPixel(w + x, h + y, color); } } else

for (int w = 0; w < bmpw.Width; w++) {

for (int h = 0; h < bmpw.Height; h++) {

Color color = bmpb.GetPixel(w, h);

if (color.R == 0 && color.G == 0 && color.B == 255) continue;

bmp.SetPixel(w + x, h + y, color); } } return bmp; // }

///

/// 图片棋子 ///

private void BmpPiece() { // //

if(CanDown()) {

this.pictureBox1.Cursor=this.pictureBox3.Cursor; this.pictureBox1.Refresh(); if(myturn) {

this.pictureBox4.Location=new

this.pictureBox1.Image=bmp;

//// //// // // //

44

游戏开发论文

Point(cellx*r-r/2+21,celly*r+24-r/2); // // // // // // // // // // // // // // // // }

///

/// 在棋盘上下一个棋子 ///

public Bitmap DownthePoint(out string txt1, out string txt2) {

if (myturn) {

whitenum++; down[cellx, celly] = 1; } else {

blacknum++; down[cellx, celly] = -1; }

txt1 = whitenum.ToString(); txt2 = blacknum.ToString();

Bitmap newmap = Down(); myturn = (!myturn); return newmap; }

private void DrawPiece(System.Windows.Forms.PictureBox p1) {

p1.Refresh();

} else { }

this.pictureBox1.Cursor=this.pictureBox2.Cursor; } else { }

oldcellx=cellx; oldcelly=celly;

this.pictureBox5.Location=new this.pictureBox4.Visible=false; this.pictureBox5.Visible=true; this.pictureBox4.Visible=true; this.pictureBox5.Visible=false;

Point(cellx*r-r/2+21,celly*r+24-r/2);

45

游戏开发论文

if (CanDown()) {

Graphics g = p1.CreateGraphics();

if (myturn) {

Brush br = new SolidBrush(Color.White);

g.FillEllipse(br, cellx * r - r / 2 + 21, celly * r + 24 - r / 2, r, r); br.Dispose(); } else {

Brush br = new SolidBrush(Color.Black);

g.FillEllipse(br, cellx * r - r / 2 + 21, celly * r + 24 - r / 2, r, r); br.Dispose(); }

oldcellx = cellx; oldcelly = celly;

p1.Cursor = System.Windows.Forms.Cursors.Hand; } else {

p1.Cursor = System.Windows.Forms.Cursors.No; }

}

///

/// 画出的棋子移动 ///

public void cheesemove(System.Windows.Forms.PictureBox p1, bool myturn) {

if (!myturn) return; cellx = pointx / r; celly = pointy / r; int x = pointx % r; int y = pointy % r; if (x > r / 2) cellx++; if (y > r / 2) celly++;

if (oldcellx == cellx && oldcelly == celly || cellx > 14 || celly > 14) {

return; }

// DrawPiece(p1);

46

游戏开发论文

} } }

using System;

using System.Collections.Generic; using System.Text;

namespace Fiveclient {

public class IsWin {

int[,] down;

public IsWin(int[,] p) {

down = p; }

public int Win(int cellx, int celly) {

for (int i = 0; i < 5; i++) {

int xall = Wfive(cellx - i, celly); if (Math.Abs(xall) == 5) return xall; int yall = Hfive(cellx, celly - i); if (Math.Abs(yall) == 5) return yall; int xyall = Piefive(cellx + i, celly - i); if (Math.Abs(xyall) == 5) return xyall; xyall = Lafive(cellx - i, celly - i); if (Math.Abs(xyall) == 5) return xyall; }

return 0; }

private int Wfive(int xbegin, int y) {

int all = 0;

for (int i = 0; i < 5; i++) { try {

all = all + down[xbegin + i, y]; } catch

47

本文来源:https://www.bwwdw.com/article/cmc8.html

Top