changeset 245:a344c54f15c7

merge work
author hychen@mluna
date Thu, 23 Oct 2008 00:47:56 +0800
parents c20912354d1d (current diff) 2af91e80353e (diff)
children 44099896397c
files inference.pl
diffstat 12 files changed, 210 insertions(+), 245 deletions(-) [+]
line wrap: on
line diff
--- a/.hgignore	Thu Oct 23 00:33:22 2008 +0800
+++ b/.hgignore	Thu Oct 23 00:47:56 2008 +0800
@@ -7,3 +7,4 @@
 *.html
 *.sh
 *.txt
+ecmanaut-read-only
--- a/README	Thu Oct 23 00:33:22 2008 +0800
+++ b/README	Thu Oct 23 00:47:56 2008 +0800
@@ -8,20 +8,24 @@
 enemy.pl - list all the islands and scores the enemy have.
 freeland.pl - find the available place we can build the city.
 inactive-map.pl - finding the sheep and list them in a map.
-inference.pl - a simple proof-of-concept of decision making robot.
+agent.pl - a simple proof-of-concept of decision making robot.
 scan.pl - scan the islands and cities by coordinate or default world view.
 scores.pl - scan and update the scores of accounts.
 sheep.pl - find the sheep to kill, takes coordinate or default world view.
 
 = HOWTO =
  * Install *many* perl modules. 
-libclass-dbi-autoloader-perl - Class::DBI::AutoLoader
-libclass-dbi-perl - Class::DBI
-libclass-dbi-sqlite-perl - Class::DBI::SQLite
-libhtml-tagparser-perl - HTML::TagParser;
-libio-compress-zlib-perl - IO::Uncompress::Gunzip
-libwww-perl - LWP
-libwww-mechanize-perl - WWW::Mechanize
+Carp::Assert - libcarp-assert-perl
+Carp::Assert::More - libcarp-assert-more-perl
+Class::DBI::AutoLoader - libclass-dbi-autoloader-perl
+Class::DBI - libclass-dbi-perl
+Class::DBI::SQLite - libclass-dbi-sqlite-perl
+Decision::ParseTree - libdecision-parsetree-perl
+HTML::TagParser; - libhtml-tagparser-perl
+IO::Uncompress::Gunzip - libio-compress-zlib-perl
+LWP - libwww-perl
+WWW::Mechanize - libwww-mechanize-perl
+YAML - libyaml-perl
 
   You can download missed debian packages from http://www.assembla.com/spaces/eagle-eye/documents
   
@@ -30,13 +34,13 @@
  * Create the config file, at ${HOME}/.eagleeye.pm. The file content are
 package main;
 
-$::server = 's2.ikariam.tw';
+$::server = 's4.ikariam.tw'; # Delta server.
 $::user = "chihchun";
 $::pass = "YOUKNOW";
 
 1;
 
- * Run the bot, 'perl inference.pl'
- * Update the islands by runing 'perl scan.pl'
- * List sheeps, 'perl sheep.pl'
+ * Run the bot, 'perl agent.pl'
+ * Update the islands information by runing 'perl scan.pl'
+ * List sheeps, 'perl sheep.pl' (run scan.pl first)
 
--- a/agent.pl	Thu Oct 23 00:33:22 2008 +0800
+++ b/agent.pl	Thu Oct 23 00:47:56 2008 +0800
@@ -16,7 +16,7 @@
     return bless $self, $class;
 }
 
-sub is_Attacked {
+sub is_attacked {
     my ($self, $city) = @_;
     return ($city->{force}->{attacks} > 0 ) ? 1 : 0;
 }
@@ -35,7 +35,7 @@
 sub is_space_enough {
     my ($self, $city) = @_;
     # TODO 應該以消耗率/時間計算
-    return ($city->{space}->{total} <= ($city->{space}->{occupied}+6) ?  1 : 0)
+    return ($city->{space}->{total} <= ($city->{space}->{occupied}+6) ?  0 : 1)
 }
 
 sub is_corruption {
@@ -49,26 +49,19 @@
     return ($city->{happiness} >= 2 ?  1 : 0)
 }
 
-sub is_warehouse_enough
-{
+sub is_warehouse_enough {
     my ($self, $city) = @_;
     # TODO 以速率計算容納率
     # XXX: not implemented yet.
     return 1;
 }
 
-sub is_risk
-{
+sub is_risk {
     my ($self, $city) = @_;
     # TODO 計算可搶劫比例, 城牆防護, 軍事分數
     return 0;
 }
 
-sub is_shipyard
-{
-    return 1;
-}
-
 sub is_gold_enoughforcargo {
     my ($self, $city) = @_;
     my @cargoCost = qw/160 244 396 812 1240 1272 1832 1888 3848 3972 5204 5384 6868 7120 8864 9200 11268 11712 14108 14680 23320 24288 28664 29880 34956 36468 42348 44212 51024 53308 61236 64024 73096 76468 87020 91088 103224 116524 122072 137432 180060 202132 211964 237444 249108 278276 292076 306623 321963 338138 355198 373191 392171 412195 433320 455612 479135 503962 530166 557828 587031 617863 650420 684802 721113 759466 799981 842783 888005 935790 986286 1039654 1096062 1155689 1218724 1285369 1355837 1430353 1509159 1592508 1680670 1773932 1872597 1976989 2087448 2204338 2328045 2458976 2597567 2744276 2899594 3064040 3238163 3422550 3617820 3824635 4043693 4275738 4521561 4782000 5057946 5350345 5660202 5988585 6336630 6705540 7096598 7511164 7950683 8416694 8910828 9434823 9990523 10579889 11205006 11868090 12571498 13317734 14109462 14949514/;
@@ -123,6 +116,24 @@
     return (defined($city->{research}->{2040}) ?  1 : 0);
 }
 
+sub is_invention_researched {
+    my ($self, $city) = @_;
+    return (defined($city->{research}->{3040}) ?  1 : 0);
+}
+
+sub is_barracks_level_enough {
+    my ($self, $city) = @_;
+    return 0 if(!defined($city->{building}->{barracks}));
+    return ($city->{building}->{barracks} >= 3 ? 1 : 0);
+}
+
+sub is_shipyard_level_enough {
+    my ($self, $city) = @_;
+    return 0 if(!defined($city->{building}->{shipyard}));
+    return ($city->{building}->{shipyard} >= 2 ? 1 : 0);
+    return 0;
+}
+
 sub rule_engagement
 {
     my ($self, $city) = @_;
@@ -177,7 +188,7 @@
         }
     }
     # Debug
-    print(Dumper($cities->{$cityId}->{parse_path}));
+    # print(Dumper($cities->{$cityId}->{parse_path}));
 }
 
 $i->logout;
--- a/building.yaml	Thu Oct 23 00:33:22 2008 +0800
+++ b/building.yaml	Thu Oct 23 00:47:56 2008 +0800
@@ -1,7 +1,7 @@
 ---
 # 基本建設規則
 # 檢查是否被攻擊
-- is_Attacked:
+- is_attacked:
     # we are in Peace :D
     0:
       - is_constructing:
@@ -13,26 +13,23 @@
            # 財富
             - is_wealth_researched:
                0: research_economy
-               1: 
-                  # 擴張
-                  - is_expansion_researched:
-                     0: research_seafaring
-                     1:
-                        # 造紙
-                        - is_paper_researched:
-                           0: research_knowledge
-                           1:
-                              # 釀酒
-                              - is_winepress_researched:
-                                 0: research_economy
-                                 1:
-                                    # 正規軍
-                                    - is_professionalarmy_researched:
-                                       0: resaerch_military
+            # 擴張
+            - is_expansion_researched:
+               0: research_seafaring
+            # 造紙
+            - is_paper_researched:
+               0: research_knowledge
+            # 正規軍
+            - is_professionalarmy_researched:
+               0: resaerch_military
+            # 釀酒
+            - is_winepress_researched:
+               0: research_economy
+            # 發明
+            - is_invention_researched:
+               0: research_knowledge
          # let's find something to build up
          0:
-            # 確認是否為主城
-            # 確認是否有學院
             - is_gold_enoughforcargo:
                1: increaseTransporter
             - is_wall_enough:
@@ -53,13 +50,58 @@
                         - is_drydock_researched: 
                            0: resaerch_military
                            1: build_shipyard
+                           # build one board
             - is_happiness:
                0: 
                   - is_winepress_researched:
-                     0: research_economy
+                     # 0: research_economy
                      1: build_tavern
-                     # reduce_trvern
-            # 是主城, 可隨意建任一尚未搭建之建築
+
+            # TODO
+            # http://ikariam.wikia.com/wiki/List_of_buildings
+            # http://ikariam.wikia.com/wiki/Technology_Tree
+            # is_conservation_researched
+            #    -build_warehouse
+            # build_academy
+            # build_palace (Expansion, Capital only)
+            # build_embassy (副城, 不建)
+
+            - is_professionalarmy_researched:
+               1:
+                  - is_shipyard_level_enough:
+                     1:
+                        - build_shipyard
+            - is_professionalarmy_researched:
+               1:
+                  - is_barracks_level_enough:
+                     1: 
+                        - build_barracks
+            # is_invention_researched
+            # biuld_workshop 
+            # biuld_hideout
+            #
+            # build_museum
+
+            # 皇宮
             # 副城, 不建 ...
     # 採取防禦措施
     1: run_defense
+    # 若軍分 0, 進行焦土政策 針對特定城市 錢全部買船 拆港
+    # increaseTransporter
+    # destroy TradingPort
+    #
+    # 計算出兵數量、到達時間與調動時間
+    # 調動軍隊防護 (加入封鎖列表)
+
+    # (保留兵力) 出兵對方城鎮, 拆港, keep gold
+    # (保留兵力) 出兵任一城鎮, 拆港, keep gold
+
+# blocking
+# 計算軍方比例
+# 對方軍分 0, # 海軍一日三次, 每次八小時 # 陸軍每日三次, 八小時一次
+# 對方平等軍分, 半夜偷襲
+# 對方高軍分 # 累積分數
+#
+# balance resources
+# 從其他城移動資源到特定城市
+# 預先計算可能需要的資源
--- a/inference.pl	Thu Oct 23 00:33:22 2008 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,127 +0,0 @@
-#!/usr/bin/perl
-use strict;
-use Ikariam;
-use Data::Dumper;
-
-package main;
-
-our $cities;
-sub Warn
-{
-    my ($city, $msg) = @_;
-    printf("http://%s/index.php?view=city&id=%s (%s) %s \n", 
-        $::server, $city, $cities->{$city}->{name}, $msg);
-}
-
-sub rule_happiness
-{
-    my $id = shift;
-
-    if($cities->{$id}->{happiness} >= 3) {
-        Warn($id, sprintf("is not happy (%s)!", $cities->{$id}->{happiness_text}));
-    }
-}
-
-sub rule_resource
-{
-    my $id = shift;
-
-    # checking goods
-    foreach my $good (qw/wood wine marble crystal/) {
-        if($cities->{$id}->{resources}->{$good} <= 100) {
-            Warn($id, sprintf("Running out %s (%d)!", $good, $cities->{$id}->{resources}->{$good}));
-        }
-    }
-}
-
-sub rule_building
-{
-    my $cityId = shift;
-
-    # 城鎮跟圍牆
-    if($cities->{$cityId}->{construction} != 1) {
-        if($cities->{$cityId}->{buildings}->{wall} < $cities->{$cityId}->{buildings}->{townHall}) {
-            Warn($cityId, sprintf("Wall level (%d) is lower then town hall (%d)!",
-                    $cities->{$cityId}->{buildings}->{wall},
-                    $cities->{$cityId}->{buildings}->{townHall}
-                )) 
-        } else {
-            Warn($cityId, sprintf("is not building."));
-        }
-    }
-}
-
-sub rule_space
-{
-    my $cityId = shift;
-
-    if($cities->{$cityId}->{space}->{total} == $cities->{$cityId}->{space}->{occupied})
-    {
-        Warn($cityId, sprintf("your space is full, upgraded the hall")) 
-        if($cities->{$cityId}->{construction} != 1);
-    }
-    return 0;
-}
-
-sub rule_war
-{
-    my $cityId = shift;
-    if($cities->{$cityId}->{force}->{attacks} > 0)
-    {
-        Warn($cityId, sprintf("YOU ARE ATTACKED!!!!")) if($cities->{$cityId}->{construction} != 1)
-    }
-}
-
-sub rule_engagement
-{
-    my $cityId = shift;
-    if($cities->{$cityId}->{force}->{wars} == 0) {
-        Warn($cityId, sprintf("Let's Attack someone!"));
-    }
-}
-
-# 貪腐
-sub rule_corruption
-{
-    my $id = shift;
-
-    if($cities->{$id}->{corruption} > 0) {
-        Warn($id, sprintf("corruption is %d", $cities->{$id}->{corruption}));
-    }
-}
-
-print Dumper($cities);
-# show cities.
-foreach my $cityId (keys(%$cities)) {
-    printf("%s http://s2.ikariam.tw/index.php?view=city&id=%d\n", $cities->{$cityId}->{name}, $cityId);
-    printf("construction: %s\n", $cities->{$cityId}->{construction});
-    
-    foreach my $thing (qw/resources space force buildings citizens army fleet/) {
-        printf("%s\n", uc($thing));
-        foreach my $i (keys(%{$cities->{$cityId}->{$thing}})) {
-            printf("%s %s, ", $i, $cities->{$cityId}->{$thing}->{$i});
-        }
-        print("\n");
-    }
-    print("\n");
-}
-
-our $i = new Ikariam($::server, $::user, $::pass);
-$i->login;
-$cities = $i->check;
-$i->logout;
-
-# space
-# Checking rules
-foreach my $procedure (qw/rule_war rule_happiness rule_corruption rule_building rule_space rule_resource/) {
-    foreach my $id (keys(%$cities)) {
-        eval(sprintf("%s(%s);", $procedure, $id));
-    }
-}
-
-foreach my $procedure (qw/rule_engagement/) {
-    foreach my $id (keys(%$cities)) {
-        eval(sprintf("%s(%s);", $procedure, $id));
-        last;
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pyikb/Parser.py	Thu Oct 23 00:47:56 2008 +0800
@@ -0,0 +1,51 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+import re,string
+from sgmllib import SGMLParser  
+
+class ContentParser(SGMLParser):
+    def __init__(self):
+        SGMLParser.__init__(self)
+        self.anchor =  {'link':'', 'title':''}
+        self.anchorlist = []
+	self.liattr={}
+        self.inside_elements=['site']
+	self.pat=re.compile('\r|\t|\n')
+
+    def start_a(self, attributes):
+        """For each anchor tag, pay attention to the href and title attributes."""
+        href, title = '', ''
+        for name, value in attributes:
+            if name.lower() == 'href': href = value
+            if name.lower() == 'title': title = value
+        self.anchor['link'] = href
+        self.anchor['title'] = title
+        self.inside_elements.append('anchor')
+
+    def end_a(self):
+        self.anchorlist.append(self.anchor) # store the anchor in a list 
+        self.anchor = {'link':'', 'title':''}   # reset the dictionary,  
+        self.inside_elements.pop()
+
+    def handle_data(self, text):
+        if self.inside_elements[-1]=='anchor':
+            self.anchor['title'] = text
+	if self.inside_elements[-1]=='li':
+	    text=self.pat.sub(' ',text)
+	    text=string.split(text," ")
+	    if self.liattcl in self.liattr:
+	    	self.liattr[self.liattcl]=self.liattr[self.liattcl]+text
+	    else:
+	        self.liattr[self.liattcl]=text
+
+    def start_li(self,attributes):
+	self.liattcl=''
+        attrs = dict(attributes)
+	if attrs.has_key('class'):
+	     	self.liattcl=attrs['class']
+		self.inside_elements.append('li')
+
+    def end_li(self):
+	if self.inside_elements[-1]=='li':
+	    self.inside_elements.pop()
+	
--- a/pyikb/ikariam.py	Thu Oct 23 00:33:22 2008 +0800
+++ b/pyikb/ikariam.py	Thu Oct 23 00:47:56 2008 +0800
@@ -3,60 +3,14 @@
 import os,sys,re,string
 import cookielib,urllib2,urllib # for urlencode
 import time
-from sgmllib import SGMLParser  
-
-class ContentParser(SGMLParser):
-    def __init__(self):
-        SGMLParser.__init__(self)
-        self.anchor =  {'link':'', 'title':''}
-        self.anchorlist = []
-	self.liattr={}
-        self.inside_elements=['site']
-	self.pat=re.compile('\r|\t|\n')
-
-    def start_a(self, attributes):
-        """For each anchor tag, pay attention to the href and title attributes."""
-        href, title = '', ''
-        for name, value in attributes:
-            if name.lower() == 'href': href = value
-            if name.lower() == 'title': title = value
-        self.anchor['link'] = href
-        self.anchor['title'] = title
-        self.inside_elements.append('anchor')
-
-    def end_a(self):
-        self.anchorlist.append(self.anchor) # store the anchor in a list 
-        self.anchor = {'link':'', 'title':''}   # reset the dictionary,  
-        self.inside_elements.pop()
-
-    def handle_data(self, text):
-        if self.inside_elements[-1]=='anchor':
-            self.anchor['title'] = text
-	if self.inside_elements[-1]=='li':
-	    text=self.pat.sub(' ',text)
-	    text=string.split(text," ")
-	    if self.liattcl in self.liattr:
-	    	self.liattr[self.liattcl]=self.liattr[self.liattcl]+text
-	    else:
-	        self.liattr[self.liattcl]=text
-
-    def start_li(self,attributes):
-	self.liattcl=''
-        attrs = dict(attributes)
-	if attrs.has_key('class'):
-	     	self.liattcl=attrs['class']
-		self.inside_elements.append('li')
-
-    def end_li(self):
-	if self.inside_elements[-1]=='li':
-	    self.inside_elements.pop()
-	
+from lconf import LoadConfigfile
+from Parser import ContentParser
 
 class connection(object):
     def __init__(self):
 	self.page=''
-	self.server='s2.ikariam.tw'
-	self.baseurl='http://'+self.server
+	self.confdata=LoadConfigfile().cd
+	self.baseurl='http://'+self.confdata['server']
         self.COOKIEFILE = '/tmp/ikcookies.lwp'
 	self.cj = cookielib.LWPCookieJar()
 	if os.path.isfile(self.COOKIEFILE):
@@ -68,8 +22,10 @@
     def login(self):
         if not os.path.isfile(self.COOKIEFILE):
 	    print "create cookie file"+self.COOKIEFILE
-	    # /index.php?action=loginAvatar&function=login
-            params = {"universe":self.server, "name":'username', "password":'passwd'}
+	    params = {"universe":self.confdata['server'], \
+	    "name":self.confdata['user'], \
+	    "password":self.confdata['pass']}
+
             data = urllib.urlencode(params)
             self.page=urllib2.urlopen(self.baseurl+'/index.php?action=loginAvatar&function=login',data).read()
 	self.cj.save(self.COOKIEFILE)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pyikb/lconf.py	Thu Oct 23 00:47:56 2008 +0800
@@ -0,0 +1,15 @@
+import os,string
+class LoadConfigfile(object):
+    def __init__(self):
+	profile = os.environ["HOME"]+'/.eagleeye.pm'
+	self.cd={}
+	if os.path.isfile(profile):
+	    print "Loading Config file."
+	    cfile=open(profile,'r')
+	    for line in cfile.xreadlines():
+	    	if line[0:3]=='$::':
+		   con=string.split(line[3:-2])
+		   self.cd[con[0]]=con[2][1:-1]	   
+	else:
+	    print "File don't exist."
+
--- a/pyikriam/__init__.py	Thu Oct 23 00:33:22 2008 +0800
+++ b/pyikriam/__init__.py	Thu Oct 23 00:47:56 2008 +0800
@@ -1,4 +1,5 @@
 from lazy.www import c
+from lconf import LoadConfigfile
 import cookielib
 import os
 import urllib2
@@ -7,11 +8,10 @@
 
     cities = {}
 
-    def __init__(self, server, username, password):
+    def __init__(self):
         self.COOKIEFILE = '/tmp/ikariam.lwp'
-        self.server=server
-        self.baseurl='http://'+self.server
-
+	self.confdata=LoadConfigfile().cd
+        self.baseurl='http://'+self.confdata['server']
         self.cj = cookielib.LWPCookieJar()
         if os.path.isfile(self.COOKIEFILE):
             self.cj.load(self.COOKIEFILE)
@@ -20,16 +20,18 @@
         opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.8.1.12pre) Gecko/20071220 BonEcho/2.0.0.12pre')]
         urllib2.install_opener(opener)
 
-        self.login(username, password)
+        self.login()
 
-    def login(self,username,password):     
-	print "login to %s...." % self.server
-        params = {"universe":self.server, "name":username, "password":password}
+    def login(self):     
+	print "login to %s...." % self.confdata['server']
+        params = {"universe":self.confdata['server'], \
+        "name":self.confdata['user'], \
+        "password":self.confdata['pass']}
         ret = c(self.baseurl+'/index.php?action=loginAvatar&function=login').get(params).get_content()
         self.cj.save(self.COOKIEFILE)
         
     def logout(self):
-	print "logut from %s...." % self.server
+	print "logut from %s...." % self.confdata['server']
         c(self.baseurl+'/index.php?action=loginAvatar&function=logout')
         os.remove(self.COOKIEFILE)
         
@@ -50,8 +52,3 @@
         xpath_gold = xpath_globalinfo + "/li[2]/a/span[@id='value_gold']/text()"
         self.gold = c(self.core.baseurl).get(self.params).find(xpath_gold).get_content()[0]
         
-if __name__ == '__main__':
-    i = Ikariam('hychen','pwdyouknow')
-    city = i.city(117261)
-    city.sync()
-    print city.gold
--- a/pyikriam/example.py	Thu Oct 23 00:33:22 2008 +0800
+++ b/pyikriam/example.py	Thu Oct 23 00:47:56 2008 +0800
@@ -1,6 +1,6 @@
 from __init__ import Ikariam
 
-i = Ikariam(server='s1.ikariam.tw', username='hychen', password='')
+i = Ikariam()
 city = i.city(117261)
 city.sync()
 print 'gold is'+city.gold
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pyikriam/lconf.py	Thu Oct 23 00:47:56 2008 +0800
@@ -0,0 +1,15 @@
+import os,string
+class LoadConfigfile(object):
+    def __init__(self):
+	profile = os.environ["HOME"]+'/.eagleeye.pm'
+	self.cd={}
+	if os.path.isfile(profile):
+	    print "Loading Config file."
+	    cfile=open(profile,'r')
+	    for line in cfile.xreadlines():
+	    	if line[0:3]=='$::':
+		   con=string.split(line[3:-2])
+		   self.cd[con[0]]=con[2][1:-1]	   
+	else:
+	    print "File don't exist."
+
--- a/sheep.pl	Thu Oct 23 00:33:22 2008 +0800
+++ b/sheep.pl	Thu Oct 23 00:47:56 2008 +0800
@@ -37,7 +37,7 @@
         SELECT user.id 
           FROM user, cities 
          WHERE user.id == cities.user 
-           AND user.trader_score_secondary >= 20
+           AND user.trader_score_secondary >= 200
            AND user.army_score_main <= 100
            AND cities.island IN (SELECT island.id FROM island WHERE island.x <= ? AND island.x >= ? AND island.y <= ? AND island.y >= ? )
     }
@@ -73,18 +73,18 @@
             next if($c->status eq 'v');
 
             unless($c->status eq 'i') {
-                next if($members > 3);
+                next if($members > 5);
             }
 
             my $island = Ikariam::Island->retrieve($c->island);
 
             # 所得金錢 = 對方城鎮等級x(對方城鎮等級-1)x對方金錢/10000
-            my $robbery = $c->citylevel * ($c->citylevel - 1) * $sheep->trader_score_secondary / 10000;
+            my $capture = $c->citylevel * ($c->citylevel - 1) * $sheep->trader_score_secondary / 10000;
 
-            next if($robbery < 2000);
+            next if($capture < 100);
 
             $line = sprintf("%d %s army %d %s/%s(%d),", 
-                $robbery,
+                $capture,
                 $c->status, $sheep->army_score_main, $sheep->name, $sheep->ally, $members);
 
             $line .= sprintf("\"%s\" %d [%d,%d] %s http://s2.ikariam.tw/index.php?view=island&id=%d&selectCity=%d\n",