农场游戏开发记录十九

    科技2022-07-14  123

    国庆第四天假期了。把买种子、种植、施肥、收获、贩卖、升级、展示的功能都和MongoDB挂接了。下面说下感受: 1,需要的类变少了很多。但也可能是我的设计架构没有弄好,有一些功能集中实现了。 2,目前对MongoDB理解还是很基础,调用方法感觉很笨拙生硬。 3,一开始写方法里,一个方法实现了太多功能。搞到自己也很疲劳,还容易出错,也不符合面对对象编程的思想。还是应该把一个个单独的小功能实现好了,再写复合功能方法的时候直接调用。这样省脑子,还不容易出错。哈哈 4,数据库里直接写入数字是double类型,用java插入和更新就可以控制是int或者double。这一点是自己摸索出来了,被坑了很长时间。 5,总算是把MongoDB基础搞定了,下一步web编程。

    仅就第3点展示一些代码吧,正反面例子都有。

    public void seed(Seed sd, int i, MongoCollection<Document> collectionSeed, MongoCollection<Document> collectionSoil, MongoCollection<Document> collectionPlants) {// 返回一个Plants对象,满足模拟种子到作物的转换而且方便下一步操作。 // 减持种子 FindIterable<Document> findIterable = collectionSeed.find(Filters.eq("seedName", sd.getProductName())); MongoCursor<Document> mongoCursor = findIterable.iterator(); if (mongoCursor.hasNext()) { int num = (int) mongoCursor.next().get("seedNum") - 1; collectionSeed.updateOne(Filters.eq("seedName", sd.getProductName()), new Document("$set", new Document("seedNum", num))); } else { System.out.println("您没有这个种子"); return; } // 改变土地状态 collectionSoil.updateOne(Filters.eq("id", i), new Document("$set", new Document("plantName", sd.getProductName().substring(0, 2)))); collectionSoil.updateOne(Filters.eq("id", i), new Document("$set", new Document("soilStatus", 1))); collectionSoil.updateOne(Filters.eq("id", i), new Document("$set", new Document("plantStatus", 1))); // 插入植物 int fruitNum = 0; double price = 0; switch (sd.getProductName()) { case "番茄种子": fruitNum = 4; price = 2.5; break; case "土豆种子": fruitNum = 8; price = 2.0; break; case "玉米种子": fruitNum = 3; price = 5.0; break; case "南瓜种子": fruitNum = 2; price = 8.0; break; default: break; } Document document = new Document("id", i).append("plantName", sd.getProductName().substring(0, 2)) .append("plantStatus", 1).append("fruitNum", fruitNum).append("price", price); collectionPlants.insertOne(document); } public void farmUpdate(MongoCollection<Document> collectionFarm,MongoCollection<Document> collectionFarmer, MongoCollection<Document> collectionSoil) { Farmer farmer = new Farmer(); Farm farm = new Farm(); double cash = farmer.getCash(collectionFarmer); int farmLevel = farm.getFarmLevel(collectionFarm); double temp = Math.pow(2,farmLevel-1)*100; if(cash < temp){ System.out.println("金钱不足"); return; } cash = -temp; farmer.setCash(cash,collectionFarmer); for(int i = 1;i<5;i++) { Document dcu = new Document("id",4*farmLevel+i).append("soilStatus", 0).append("plantName", "").append("plantStatus", 0); collectionSoil.insertOne(dcu); } farm.setFarmLevel(collectionFarm); }

    感觉好累,好辛苦。到底能不能走下去?

    Processed: 0.011, SQL: 8