SSM实现RPG游戏之角色生成器

功能描述

几乎所有的RPG游戏(一种源自《龙与地下城》的游戏类型)在进入游戏时都会让用户自己来创建自己喜欢的角色

游戏角色应有的属性
  • 游戏角色应有以下属性:名字、性别、种族、职业、力量、敏捷、体力、智力、智慧、生命值、魔法值和技能。
  • 名字:不超过50个字符。
  • 性别:可以选择男性和女性。
  • 种族:一共可选五个种族,人类、精灵、兽人、矮人和元素。
  • 职业:可选六种职业,狂战士、圣骑士、刺客、猎手、祭司和巫师。
  • 其余属性均为整数。
  • 用户输入角色姓名,然后由用户选择角色性别,然后由用户选择种族,然后选择职业,然后自动分配力量、敏捷、体力、智力和智慧属性,并计算生命值和魔法值。
  • 生命值=体力*20。
  • 魔法值=(智力+智慧)*10。
职业限制

很多职业会限制某些种族选择,例如兽人不能就职圣骑士等等,种族和职业的限制
在这里插入图片描述

初始属性

力量、敏捷、体力、智力和智慧要求是随机值(利用随机数函数来取得随机数),但是五项属性的总和应该是100,并且应该和职业相关。例如狂战士的体力和力量就要比较高,而巫师需要较高的智力,而祭司则需要较高的智慧。各职业初始属性的大致比例应遵从下表:
在这里插入图片描述

显示信息

最后向用户显示该角色的所有信息,然后询问用户是否满意,如用户不满意则重新创建,若用户满意则程序结束,并将用户创建角色的相关信息保存进数据库。


编码实现

1.首先创建web工程,在这里采用的maven,先导入ssm相关的以及测试的pom依赖
pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!--log4j的依赖-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!--servlet的依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>

    <!--log4j的依赖-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!--mysql的依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
      <scope>runtime</scope>
    </dependency>


    <!--c3p0连接池-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>


    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.4</version>
    </dependency>

    <!--spring整合mybatis的依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!--Spring的jdbc模块-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>

    <!--导入spring的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>
    <!--Spring整合单元测试的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.1.15</version>
    </dependency>

  </dependencies>

2.创建相关的配置文件

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <!--Spring的注解扫描器-->
    <context:component-scan base-package="edu.xust"/>

    <!-- 配置c3p0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/role?characterEncoding=utf8"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>


    <!--mybatis整合spring-->
    <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-conf.xml"/>
    </bean>


    <!--mapper扫描器    bean的id为mapper类名首字母小写-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="edu.xust.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

Springmvc.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--配置前端控制器(在web.xml中配置)-->
    <!--配置处理器映射器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <!--处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
    <!--配置处理器(注解开发无需配置)-->
    <context:component-scan base-package="edu.xust.controller"/>
</beans>

mybatis-conf.xml
该配置文件将在后面的起别名的时候使用

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
    </typeAliases>
</configuration>

log4j.properties
用来打印日志

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug, stdout

3.实体类的实现
为了节省篇幅,在这里没有写出get和set方法

public  class RoleBean {
    String username;//姓名
    String sex;//性别
    String race;//种族
    String occupation;//职业
    int strength;//力量
    int agility;//敏捷
    int physicial;//体力
    int intellige;//智力
    int intelligence;//智慧
    int life;//生命值
    int magic;//魔法值
    String skill;//技能
 }

3.mapper代理
RoleMapper.class

package edu.xust.mapper;

import edu.xust.pojo.RoleBean;
import org.springframework.stereotype.Repository;

@Repository
public interface RoleMapper {
    //使用mybatis自动代理实现持久层
    void insertRole(RoleBean role);
}

RoleMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.xust.mapper.RoleMapper">

    <insert id="insertRole" parameterType="edu.xust.pojo.RoleBean">
      insert into role values(#{username},#{sex},#{race},#{occupation},#{strength},#{agility},#{physicial},#{intellige},#{intelligence},#{life},#{magic},#{skill});
    </insert>
</mapper>

4.生成属性

package edu.xust.utils;

import java.util.Random;

public class RoleUtil {
    /**
     * 采用随机数生成力量属性,其他属性在此基础上按比例进行计算
     * @param occupation
     * @return
     */
    public static Object[] getProperty(String occupation) {
        Object [] pro=new Object[8];
        int strength = 0;//力量
        int physical = 0;//体力
        int inttellige = 0;//智慧
        int inttelligence = 0;//智力
        int life = 0;//生命值
        int magic = 0;//魔法值
        String skill = "";//技能
        int agility = 0;//敏捷
        Random random = new Random();
        switch (occupation) {
            case "狂战士":
                strength = random.nextInt(3) + 39;//力量
                agility = strength/2;//敏捷
                physical = strength-10;//体力
                inttelligence = strength/8;//智力
                skill="狂战之崩山裂地斩";
                break;
            case "圣骑士":
                strength = random.nextInt(3) + 23;//力量
                agility = strength-10;//敏捷
                physical = agility*2;//体力
                inttelligence = agility+5;//智力
                skill="圣骑之圣骑之光";//技能
                break;
            case "刺客":
                strength = random.nextInt(3) + 20;//力量
                agility = strength*2-5;//敏捷
                physical = strength;//体力
                inttelligence = physical-5;//智力
                skill="幻舞";
                break;
            case "猎手":
                strength = random.nextInt(3) + 13;//力量
                agility = strength*3-5;//敏捷
                physical = strength;//体力
                inttelligence = physical-5;//智力
                skill="猎手之猎刃";
                break;
            case "祭司":
                strength = random.nextInt(3) + 13;//力量
                agility = strength+5;//敏捷
                physical = strength;//体力
                inttelligence = physical+agility;//智力
                skill = "祭司之四魂";
                break;
            case "巫师":
                strength = random.nextInt(3) + 8;//力量
                agility = strength*2;//敏捷
                physical = strength;//体力
                inttelligence = physical*2;//智力
                skill = "巫师之怨灵";
                break;
        }
        inttellige = 100-strength-agility-physical-inttelligence;//智慧
        magic = (inttelligence+inttellige)*10;//魔法
        life = physical*20;//生命值
        pro[0]=strength;
        pro[1] = agility;
        pro[2] = physical;
        pro[3] = inttelligence;
        pro[4] = inttellige;
        pro[5] = magic;
        pro[6] = life;
        pro[7] = skill;
        return pro;
    }

}


5.service层

package edu.xust.service;

import edu.xust.mapper.RoleMapper;
import edu.xust.pojo.RoleBean;
import edu.xust.utils.RoleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RoleService {
    @Autowired//按类型注入属性
    RoleMapper roleMapper;

    public void addRole(RoleBean role) {
        roleMapper.insertRole(role);
    }

    public RoleBean SelectRole(String username, String sex, String race, String occupation) {
       //获取属性
        Object[] property = RoleUtil.getProperty(occupation);
        RoleBean role = new RoleBean();
        role.setUsername(username);//名字
        role.setSex(sex);//性别
        role.setStrength((int)property[0]);//力量
        role.setAgility((int)property[1]);//敏捷
        role.setPhysicial((int)property[2]);//体力
        role.setIntelligence((int)property[3]);//智力
        role.setIntellige((int)property[4]);//智慧
        role.setMagic((int)property[5]);//魔法
        role.setLife((int)property[6]);//生命值
        role.setRace(race);//种族
        role.setOccupation(occupation);//职业
        role.setSkill(property[7].toString());//初始技能
        return role;
    }
}


6.controller控制层的实现

package edu.xust.controller;

import com.alibaba.fastjson.JSON;
import edu.xust.pojo.RoleBean;
import edu.xust.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RoleController {
    RoleBean roleBean;
    @Autowired
    private RoleService roleService;//按类型注入
    @RequestMapping(value = "/create",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String createRole(){
        roleService.addRole(roleBean);//调用service层添加角色
        return null;
    }
    @RequestMapping(value = "/get",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getRole(String username,String sex,String occupation,String race){
        roleBean = roleService.SelectRole(username, sex, race, occupation);
        String s = JSON.toJSONString(roleBean);//把对象转换为JSON字符串格式
        return s;
    }

}


7.页面的实现
数据传输格式为JSON,使用ajax实现异步请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>创建角色</title>

    <style type="text/css">
        #con {
            background: url("image/background1.jpg") no-repeat;
            background-size: cover;
            position: absolute;
            top: 0;
            bottom: 0px;
            right: 0px;
            left: 0px;
        }
        #div{
            width: 600px;
            height: 600px;
            margin-top: 200px;
            margin-left: 600px;
        }
    </style>
</head>
<body>
<div id="con">
    <div id="div">
        <div>
            <span>角色名</span>
            <input type="text" id="username">
        </div>
        <br>
        <div>
            <span>性别</span>
            <select id="sex">
                <option >男</option>
                <option >女</option>
            </select>
        </div>
        <br>
        <div>
            <span>种族</span>
            <select id="race">
            </select>
            <span>职业</span>
            <select id="occupation">
            </select>
        </div>
        <br>
        <div>
            <button id="ok" style="margin-left: 60px">确定</button>
            <button id="cal" style="margin-left: 40px">取消</button>
        </div>
    </div>
</div>
</body>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript">
    var race = document.getElementById("race");
    var occupation = document.getElementById("occupation");
    var data=[];
    data["人类"]=["狂战士","圣骑士","刺客","猎手","祭司","巫师"];
    data["精灵"]=["刺客","猎手","祭司","巫师"];
    data["兽人"]=["狂战士","猎手","祭司","巫师"];
    data["矮人"]=["狂战士","圣骑士","祭司"];
    data["元素"]=["祭司","巫师"];
    //动态生成下拉框的选择项
    for (key in data) {
        var option = document.createElement("option");
        option.appendChild(document.createTextNode(key));
        option.setAttribute("value", key);
        race.appendChild(option);
    }
    getdata();
    //当下拉框数据改变就触发getdata()去更改联动框的数据
    race.onchange = getdata;
    function getdata() {
        occupation.length = 0;
        var ss = data[race.value];
        for (index in ss) {
            var option = document.createElement("option");
            option.appendChild(document.createTextNode(ss[index]));
            occupation.appendChild(option);
        }
    }
</script>
<script type="text/javascript">
    $ok = $("#ok");
    //添加时间
    $ok.click(function () {
        //获取数据
        var  username = $("#username").val();
        var sex = $("#sex").val();
        var race = $("#race").val();
        var occupation = $("#occupation").val();
        //ajax异步请求
        $.ajax({
            "url": "/get.action",
            "type": "get",
            "data": {"username":username,"sex":sex,"race":race,"occupation":occupation},
            "success": function (data, msg, xhr) {
               if( confirm("用户名: "+data.username+"\n"+
                       "性别: "+data.sex+"\n"+
                       "种族: "+data.race+"\n"+
                       "职业: "+data.occupation+"\n"+
                       "力量: "+data.strength+"\n"+
                       "体力: "+data.physicial+"\n"+
                       "智慧: "+data.intellige+"\n"+
                       "敏捷: "+data.agility+"\n"+
                       "智力: "+data.intelligence+"\n"+
                       "生命值: "+data.life+"\n"+
                       "魔法: "+data.magic+"\n"+
                       "初始技能: "+data.skill+"\n")==true){
                   f1();//点击确定以后正式添加角色
               }
            },
            "error": function () {
                console.log("失败...");
            }
        });
    })

</script>
<script type="text/javascript">
    function f1() {
        $.ajax({
            "url": "/create.action",
            "type": "get",
            "success": function (data, msg, xhr) {
                alert("创建成功")
            },
            "error": function () {
                console.log("失败...");
            }
        });
    }
    
</script>
</html>
结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值