数据库
登录时验证用户名和密码,使用MySQL数据库管理数据,类中的主要方法也都是使用SQL语句完成。类中还提供两个接口, 一个通过username获取UserInfo ,一个是直接获取到排行榜。 数据库连接类
using System;
using MySql.Data.MySqlClient;
using UnityEngine;
public class MySqlAccess
{
//连接类对象
public MySqlConnection mySqlConnection;
//IP地址
private static string host;
//端口号
private static string port;
//用户名
private static string username;
//密码
private static string password;
//数据库名称
private static string databaseName;
public MySqlAccess(string _host,string _port, string _username, string _password, string _databaseName)
{
host = _host;
port = _port;
username = _username;
password = _password;
databaseName = _databaseName;
OpenSql();
}
private void OpenSql()
{
try {
string mySqlString = string.Format("datasource={0};port={1};database={2};user={3};pwd={4};"
, host, port, databaseName, username, password);
//Debug.Log(mySqlString);
mySqlConnection = new MySqlConnection(mySqlString);
mySqlConnection.Open();
} catch (Exception e) {
throw new Exception("服务器连接失败,请重新检查MySql服务是否打开。" + e.Message);
}
}
}
数据库管理类
using System;
using System.Collections.Generic;
using Frame.Utility;
using Game.bean;
using Game.Interface;
using MySql.Data.MySqlClient;
using UnityEngine;
using EventType = Frame.Utility.EventType;
namespace Game
{
public class DataBaseManager : SingleTonMonoAuto<DataBaseManager>, IDataBaseManager
{
private MySqlAccess mySqlAccess;
private string _connectionStr;
private MySqlConnection _connection;
private MySqlCommand _command;
Dictionary<string, UserInfo> _dictionary = new Dictionary<string, UserInfo>();
private UserInfo _userCache;
//宿舍的ip
//private string host = "172.20.177.212";
//课室的
private string host = "10.9.72.192";
private void OnEnable()
{
EventCenter.Instance.AddListener(EventType.ResetLogin,ResetLogin);
}
public void AddMoneyAndHonor(string name,int money,int honor)
{
if (_dictionary.ContainsKey(name))
{
UserInfo userInfo = _dictionary[name];
userInfo.money += money;
userInfo.honor += honor;
SaveInfo(userInfo);
}
}
/// <summary>
/// 保存UserInfo数据
/// </summary>
/// <param name="userinfo"></param>
public void SaveInfo(UserInfo userinfo)
{
int userId = userinfo.id;
int money = userinfo.money;
int honor = userinfo.honor;
string heroList = userinfo.ownedHero;
if ( !_dictionary.ContainsKey(userinfo.username))
{
//把用户数据存入字典
_dictionary.Add(userinfo.username, userinfo);
}
UpdateUserInfo(userId, money, honor, heroList);
}
/// <summary>
/// 修改用户信息
/// </summary>
/// <param name="userId"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="money"></param>
/// <param name="honor"></param>
/// <param name="ownedHero"></param>
private void UpdateUserInfo(int @ID,int @money,int @honor,string @ownedHero)
{
_command.CommandText = "Update CustomerInfo Set money=\'"
+money+"\', honor=\'"+honor+"\', ownedHero=\'"
+ownedHero+"\' where ID="+ID;
int i = _command.ExecuteNonQuery();
Debug.Log("产生影响"+ i);
}
private DataBaseManager()
{
//Debug.Log("DataBaseManager实例化");
InitDataBase();
}
//初始化数据库
private void InitDataBase()
{
mySqlAccess = new MySqlAccess(host,"3306","root","123456","dbcustomerinfo");
_connection = mySqlAccess.mySqlConnection;
_command = _connection.CreateCommand();
SaveInDic();
}
private void SaveInDic()
{
_command.CommandText = "Select * From CustomerInfo";
MySqlDataReader _reader = _command.ExecuteReader();
//将数据传入字典
while (_reader.Read())
{
object id = _reader.GetValue(0);
object username = _reader.GetValue(1);
object password = _reader.GetValue(2);
object money = _reader.GetValue(3);
object honor = _reader.GetValue(4);
object ownedHero = _reader.GetValue(5);
object isLogined = _reader.GetValue(6);
if (!_dictionary.ContainsKey((string) username))
{
_dictionary.Add((string) username,
new UserInfo(Convert.ToInt32(id), (string) username, (string) password, Convert.ToInt32(money),
Convert.ToInt32(honor), (string) ownedHero ,Convert.ToInt32(isLogined)));
}
}
_reader.Close();
}
/// <summary>
/// 通过用户名获取UserInfo
/// </summary>
/// <param name="name"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public UserInfo GetUserInfo(string name, string pwd)
{
_command.CommandText = "Select * From CustomerInfo where username = " + "'" + name + "'";
if (_command.ExecuteScalar() == null)
{
Debug.Log("用户名不存在");
//用户名不存在
return null;
}
else //用户名存在
{
//判断是否与密码匹配
UserInfo _user;
_dictionary.TryGetValue(name, out _user);
if (_user != null && !CheckIsLogined(name))
{
bool pwdIsSame = _user.password == pwd ? true : false;
if (pwdIsSame)
{
Debug.Log("登陆成功");
_user.isLogined = 1;
_command.CommandText = "UPDATE customerinfo SET islogined = 1 WHERE username = " +"'" + name + "'";
_command.ExecuteNonQuery();
_userCache = _user;
return _user;
}
else
{
Debug.Log("账户名或密码错误");
return null;
}
}
}
return null;
}
private bool CheckIsLogined(string username)
{
_command.CommandText = "SELECT islogined from customerinfo WHERE username =" + "'" + username + "'";
object obj = _command.ExecuteScalar();
bool isLogined = Convert.ToInt32(obj) == 1 ? true : false;
return isLogined;
}
/// <summary>
/// 获取排行榜
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public List<UserInfo> GetRankList(int num)
{
if (num > _dictionary.Count)
{
Debug.LogError("查询范围超出!");
return null;
}
List<UserInfo> rankList = new List<UserInfo>();
//排序的SQL语句
_command.CommandText = "Select * from CustomerInfo ORDER BY honor DESC , money DESC limit " + num;
MySqlDataReader _reader = _command.ExecuteReader();
while (_reader.Read())
{
UserInfo _userInfo;
_dictionary.TryGetValue((string) _reader.GetValue(1), out _userInfo);
rankList.Add(_userInfo);
}
_reader.Close();
return rankList;
}
private void OnApplicationQuit()
{
//Debug.Log("关闭数据库连接");
if (mySqlAccess.mySqlConnection!=null)
{
EventCenter.Instance.RemoveListener(EventType.ResetLogin,ResetLogin);
if(_userCache!=null){
_userCache.isLogined = 0;
_command.CommandText = "UPDATE customerinfo SET islogined = 0 WHERE username = " +"'" + _userCache.username + "'";
_command.ExecuteNonQuery();
}
mySqlAccess.mySqlConnection.Close();
}
}
/// <summary>
/// 一键还原所有登录
/// </summary>
public void ResetLogin()
{
_command.CommandText = "Update customerInfo Set islogined = 0";
_command.ExecuteNonQuery();
print("已还原所有登录");
}
}
}
登录页面
using System;
using DG.Tweening;
using Frame.UI;
using Frame.Utility;
using Game;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using EventType = Frame.Utility.EventType;
public class LoginModule : UIModuleBase
{
private InputField inputName;
private InputField inputPsw;
private EventSystem _system;
private bool isSelectUsername; //选框用户名
private Image FocusLigthUsername;
private Image FocusLigthPassword;
private Text txtMention; //密码错误提示
//可选对象
Selectable cur = null;
private void Start()
{
_system = EventSystem.current;
txtMention = FW("txtMention#").Text;
inputName = FW("Field-UserName#").InputField;
inputPsw = FW("Field-UserPassword#").InputField;
FW("LoginButton#").Button.onClick.AddListener(() =>
{
Debug.Log("点击了登录按钮 name=" + inputName.text + " psw=" + inputPsw.text);
//调用UIEvent的事件
UIEvent.LoginClick(inputName.text, inputPsw.text);
});
}
public void PlayMentionAnime()
{
Debug.Log("PlayMentionAnime");
Tweener _tweener = txtMention.DOFade(1, 0.6f);
_tweener.SetDelay(0);
_tweener.SetEase(Ease.Linear);
_tweener.SetAutoKill(true);
_tweener.SetLoops(0);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
Selectable next = null;
cur = _system.currentSelectedGameObject.GetComponent<Selectable>();
print("name=" + cur.name);
if (cur.name == "Field-UserName#")
{
isSelectUsername = true;
next = cur.FindSelectableOnDown();
}
else
{
isSelectUsername = false;
next = cur.FindSelectableOnUp();
}
_system.SetSelectedGameObject(next.gameObject, new BaseEventData(_system));
}
if (Input.GetKeyDown(KeyCode.Return))
{
UIEvent.LoginClick(inputName.text, inputPsw.text);
}
if (Input.GetKeyDown(KeyCode.B))
{
//一键清空登录状态
EventCenter.Instance.Call(EventType.ResetLogin);
}
}
}
登录成功界面
using System;
using System.ComponentModel.Design;
using Frame.UI;
using Game;
using Game.bean;
using Photon.Pun;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEngine.UI;
using Object = System.Object;
public class LoginSucPanel : UIModuleBase
{
private Button BtnCheck;
private Text LoginMsg;
protected override void Awake()
{
base.Awake();
BtnCheck = FW("BtnCheck#").Button;
LoginMsg = FW("txtLoginMsg#").Text;
BtnCheck.onClick.AddListener(() =>
{
UIEvent.ToMain();
});
}
public void Init()
{
LoginMsg.text = "亲爱的"+"\n" + PhotonNetwork.NickName +"\n"+ "欢迎进入游戏!";
}
public override void OnSpawn(Object obj)
{
base.OnSpawn(obj);
//设置photon昵称
PhotonNetwork.NickName = (string)obj;
Init();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
UIEvent.ToMain();
}
}
}
游戏控制类
using Game;
using Game.bean;
using Game.Interface;
using Photon.Pun;
//游戏控制类。负责所有游戏逻辑总控制
//单例,待实现
public class GameController: SingleTonObj<GameController>
{
private MainPageInfo _mainPageInfoCache;
private GameController(){}
//具体的游戏逻辑控制,按功能分
//UI控制
private IUIController _uiController;
//登录管理
private ILoginManager _loginManager;
//玩家数据
private PlayerInfo _playerInfo;
//地图
private IMapManager _mapManager;
//网络框架
private IPhotonWrapper _photonWrapper;
private bool init = false;
/// <summary>
/// 初始化
/// </summary>
public void Init()
{
if (init)
{
return;
}
init = true;
InitObj();
BindUIEvent();
}
/// <summary>
/// 初始化各个逻辑对象的具体类
/// </summary>
private void InitObj()
{
_uiController=new UIController();
//_loginManager=new LoginManager();
_loginManager = new FakeLoginManager();
_mapManager= new TestMapManager();
_photonWrapper=new TestPhotonWrapper();
_playerInfo=new PlayerInfo();
}
private void BindUIEvent()
{
UIEvent.LoginClick += Login;
UIEvent.ToMain += ToMain;
UIEvent.StoreClick += Store;
UIEvent.SettingClick += Setting;
UIEvent.MapClick += MapDetail;
UIEvent.LobbyClick += Lobby;
UIEvent.QuickStartClick += QuickStart;
UIEvent.HeroChange += HeroChange;
UIEvent.GameStart += GameStart;
}
private void ToMain()
{
_uiController.ShowMain(_mainPageInfoCache);
}
private void GameStart(MapInfo mapInfo)
{
//游戏开始,根据地图配置,跳到各自的场景
}
private void QuickStart()
{
_photonWrapper.RandomJoin((result) =>
{
if (result)
{
_uiController.ShowRoomInfo();
}
else
{
_photonWrapper.CreateRoom();
}
});
}
private void Lobby()
{
_uiController.ShowLobby();
}
private void MapDetail(MapInfo obj)
{
_uiController.ShowMapDetail();
}
private void Setting()
{
_uiController.ShowSetting();
}
private void Store()
{
_uiController.ShowStore();
}
private void HeroChange(HeroInfo heroInfo)
{
_playerInfo.chooseHero = heroInfo;
}
private void Login(string name, string pwd)
{
_loginManager.Login(name,pwd, (loginResult) =>
{
if (loginResult.suc)
{
_mainPageInfoCache = new MainPageInfo();
_mainPageInfoCache.userInfo = loginResult.userInfo;
PlayerInfo.Instance.Init();
PlayerInfo.Instance._userInfo = loginResult.userInfo;
_mainPageInfoCache.maps = _mapManager.GetAllMap();
_uiController.ShowLoginSuc(_mainPageInfoCache.userInfo.username);
}
else
{
_uiController.ShowLoginError();
}
});
}
/// <summary>
/// 游戏入口,游戏启动的时候调用
/// </summary>
public void Entrance()
{
if (PlayerInfo.Instance._userInfo != null)
{
_mainPageInfoCache = new MainPageInfo();
_mainPageInfoCache.userInfo = PlayerInfo.Instance._userInfo;
_mainPageInfoCache.maps = _mapManager.GetAllMap();
_uiController.ShowMain(_mainPageInfoCache);
}else{
_uiController.ShowLogin();
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.AutomaticallySyncScene = true;
}
}
}
登录类实例
using System;
using Game.bean;
using Game.Interface;
using Mono.Data.Sqlite;
using UnityEngine;
namespace Game
{
/// <summary>
/// 登录实现实例
/// </summary>
public class LoginManager:ILoginManager
{
private IDataBaseManager _dataBaseManager;
public LoginManager()
{
_dataBaseManager = DataBaseManager.Instance;
}
public void Login(string name, string pwd, Action<LoginResult> callBack)
{
LoginResult result =new LoginResult();
//查数据库
UserInfo userInfo = _dataBaseManager.GetUserInfo(name, pwd);
//查到了
bool check = userInfo!=null;
//且状态为未登录
if(check){
result.suc = true;
result.userInfo = userInfo;
callBack(result);
}else{
//没查到 或者账号已登录
result.suc = false;
callBack(result);
}
}
}
}
登录结果类
namespace Game.bean
{
/// <summary>
/// 登录的结果
/// </summary>
public class LoginResult
{
public bool suc;
public UserInfo userInfo;
}
}
|