froechrissi

Conquest - erster code

Jan 28th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.13 KB | None | 0 0
  1. # -*- coding: cp1252 -*-
  2. #### kivy imports
  3.  
  4. import kivy
  5.  
  6. from kivy.app import App
  7. from kivy.uix.floatlayout import FloatLayout
  8. from kivy.uix.dropdown import DropDown
  9. from kivy.uix.button import Button
  10. from kivy.uix.gridlayout import GridLayout
  11.  
  12. from kivy.uix.modalview import ModalView
  13.  
  14. from kivy.uix.scatter import Scatter
  15. from kivy.uix.scatter import ScatterPlane
  16. from kivy.uix.image import *
  17. from kivy.graphics import Color, Ellipse
  18. from kivy.uix.widget import Widget
  19. from kivy.uix.label import Label
  20. from kivy.uix.image import Image
  21.  
  22. from kivy.base import EventLoop
  23.  
  24. from kivy.utils import *
  25.  
  26.  
  27. from kivy.clock import Clock
  28.  
  29. from time import sleep
  30.  
  31.  
  32. ### conquest imports
  33. from DbHelper import *
  34. from Utilities import *
  35.  
  36. TURM_X = 7
  37. TURM_Y = 7
  38.  
  39. KREIS_X = 5.
  40. KREIS_Y = 5.
  41.  
  42.  
  43. # Tower
  44. class Building(Image):
  45.   def __init__(self, _type, land, besitzer, pos1, pos2, status=0, var1='', var2=''):
  46.     self.land = land
  47.     self.pos1 = pos1
  48.     self.pos2 = pos2
  49.     self._type = _type
  50.     self.status = status
  51.     self.var1 = var1
  52.     self.var2 = var2
  53.     self.besitzer = besitzer
  54.  
  55.     if _type == 'Kampfturm':
  56.       bild = 'turm.png'
  57.  
  58.     if _type == 'Kaserne':
  59.       bild = 'kaserne.png'
  60.       pos2 = pos2 - 2
  61.  
  62.     if _type == 'Festung':
  63.       bild  = 'festung.png'
  64.       pos2 = pos2 - 2
  65.  
  66.     if _type == 'Universitaet':
  67.       bild = 'uni.png'
  68.    
  69.     return Image.__init__(self, source='media/'+bild, pos=(pos1,pos2), size=(TURM_X, TURM_Y))
  70.  
  71.  
  72.      
  73. class Landkreis(Image):
  74.   def __init__(self, _color, land, besitzer, pos1, pos2):
  75.     self.land = land
  76.     self.pos1 = int(pos1)
  77.     self.pos2 = int(pos2)
  78.     self._color = _color
  79.     self.besitzer = besitzer
  80.  
  81.     bild = 'media/kreis_' + _color + '.jpg'
  82.    
  83.     return Image.__init__(self, source=bild, pos=( int(pos1),int(pos2) ), size=(KREIS_X, KREIS_Y))
  84.  
  85. class GebaeudeButton(Button):
  86.   def __init__(self, conquest, land, _id, _status, var1, var2, desc):
  87.     self._id = _id
  88.     self.land = land
  89.     self._status = _status
  90.     self.var1 = var1
  91.     self.var2 = var2
  92.     self.conquest = conquest
  93.     return Button.__init__(self, text=desc, font_size=11, size_hint_y=None, height=44, background_normal='media/kachel.png')
  94.  
  95.   def on_press(self):
  96.     self.db = DbHelper("game")
  97.     table = self.db.fetchTables(["game_buildings"])
  98.  
  99.     fail = False
  100.     for building in table:
  101.       if building[1] == self.land:
  102.         fail = True
  103.         print  "there is already a building in ", self.land
  104.  
  105.     if fail == False:
  106.       self.db.insertTo("game_buildings", [self._id, self.land, self._status, self.var1, self.var2])
  107.  
  108.     self.conquest.modal.dismiss()
  109.  
  110.     self.conquest.update_map()
  111.    
  112.  
  113.    
  114.  
  115.  
  116.  
  117. # Main App Class
  118. class Conquest(App):
  119.  
  120.   # called at app start
  121.   def build(self):
  122.  
  123.       # prepare database
  124.       self.db = DbHelper("game") # standard database
  125.  
  126.      
  127.    
  128.       self.root = GridLayout(cols=1)
  129.      
  130.       new_game_btn = Button(text='New Game')
  131.       self.root.add_widget(new_game_btn)
  132.       new_game_btn.bind(on_press=self.new_game)
  133.  
  134.       continue_btn = Button(text='Continue')
  135.       self.root.add_widget(continue_btn)
  136.       continue_btn.bind(on_press=self.init_ingame)
  137.  
  138.      
  139.  
  140.  
  141.  
  142.      
  143.       return self.root
  144.  
  145.   def new_game(self, instance):
  146.  
  147.    
  148.     # delete old game data
  149.    
  150.     # create new game data
  151.  
  152.     self.playername = self.db.prepareNewGame(**{'bots':2})
  153.  
  154.     self.init_ingame(self)  
  155.  
  156.    
  157.  
  158.  
  159.  
  160.   # prepares ingame widgets
  161.   def init_ingame(self, instance):
  162.  
  163.     self.tables = self.db.fetchTables(["both_land", "game", "game_buildings", "buildings"])
  164.  
  165.     self.playername = 'player_self'
  166.  
  167.  
  168.  
  169.  
  170.     ### basic layout preperation ###
  171.  
  172.     self.root.clear_widgets()
  173.  
  174.    
  175.     layout = ScatterPlane(do_rotation=False)
  176.     self.floating = FloatLayout()
  177.     map_image = Image(source='map.png', size=(480,411))
  178.     self.floating.add_widget(map_image)
  179.     self.root.bind(on_touch_down=self.on_touch_down)
  180.    
  181.  
  182.    
  183.  
  184.  
  185.  
  186.  
  187.     ### GET GAME DICTS ###
  188.  
  189.     # money dict
  190.     # player : money
  191.     self.money_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][5].split("|||")))
  192.    
  193.     self.voelker_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][6].split("|||")))
  194.  
  195.    
  196.     # create capital dict
  197.     #print tables["game_buildings"]
  198.     self.capital_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][3].split("|||")))
  199.     self.turn = self.tables["game"][2] # current player
  200.  
  201.     # create color dict
  202.     self.color_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][4].split("|||")))
  203.    
  204.  
  205.     ### SHOW MONEY ###
  206.     m_text = 'Gold: ' + str(self.money_dict[self.playername])
  207.     self.money_anzeige = Label(text=m_text)
  208.     self.root.add_widget(self.money_anzeige)
  209.  
  210.     ### BUILDING ID + NAME ###
  211.     self.buildings_names = {}
  212.     for _id, _volk, _name, _var1, _var2, _description, _cost, _runden in self.tables["buildings"]:
  213.       self.buildings_names[_id] = _name
  214.  
  215.    
  216.  
  217.  
  218.  
  219.     self.update_map()
  220.  
  221.     layout.add_widget(self.floating)
  222.    
  223.     self.root.add_widget(layout)
  224.  
  225.  
  226.  
  227.  
  228.  
  229.  
  230.   def update_map(self, delay=0):
  231.  
  232.  
  233.     self.tables = self.db.fetchTables(["both_land", "game", "game_buildings", "buildings"])
  234.  
  235.     #print self.tables["game_buildings"]
  236.  
  237.     #print self.tables["buildings"]
  238.  
  239.     if delay > 0:
  240.       sleep(delay)
  241.  
  242.     self.floating.clear_widgets()
  243.  
  244.     map_image = Image(source='map.png', size=(480,411))
  245.     self.floating.add_widget(map_image)
  246.    
  247.     self.laender = {} # name : koordinaten
  248.    
  249.     self.besitzer = {} # name : besitzer
  250.    
  251.     self.buildings = []
  252.    
  253.     current_x = {}
  254.     current_y = {}
  255.    
  256.     for _id, name, positionX, positionY, nachbarn, besitzer, kontinent, effect in self.tables["both_land"]:
  257.       current_x[name] = 6
  258.       current_y[name] = 0
  259.       position = Utilities.getRealCoordinates(positionX, positionY)
  260.       self.laender[name] = position
  261.       self.besitzer[name] = besitzer
  262.  
  263.       if besitzer == '':
  264.         color = 'neutral'
  265.       else:
  266.         color = self.color_dict[besitzer]
  267.        
  268.       # create circle
  269.       element = Landkreis(color, name, besitzer, position[0], position[1])
  270.       self.buildings.append(element)
  271.       self.floating.add_widget(self.buildings[-1])
  272.  
  273.  
  274.  
  275.    
  276.  
  277.  
  278.    
  279.  
  280.  
  281.     for _type, land, status, var1, var2 in self.tables["game_buildings"]:
  282.  
  283.  
  284.  
  285.       type_real = ''
  286.      
  287.       if self.buildings_names[_type] == u'Kampfturm':
  288.         type_real = 'Kampfturm'
  289.  
  290.       if var1 == 'recruit':
  291.         type_real = 'Kaserne'
  292.  
  293.       if var2 == 'festung':
  294.         type_real = 'Festung'
  295.  
  296.       if var1 == 'university':
  297.         type_real = 'Universitaet'
  298.  
  299.  
  300.       if type_real:
  301.         element = Building(type_real, land, besitzer, self.laender[land][0] + current_x[land],
  302.                            self.laender[land][1] + current_y[land], status, var1, var2)
  303.         current_x[land] += 10 if not var2 == "Festung" else 22
  304.  
  305.       if element:
  306.         self.buildings.append(element)
  307.         # add this element to GUI
  308.         self.floating.add_widget(self.buildings[-1])
  309.  
  310.  
  311.  
  312.  
  313.  
  314.  
  315.  
  316.   def on_touch_down(self, obj, touch):
  317.     #binded to on_touch_down event of the root Grid layout
  318.    
  319.     obj = obj.children[0]
  320.     #print obj
  321.     #print touch.x, touch.y
  322.     (x,y) = obj.to_local(touch.x, touch.y)
  323.  
  324.  
  325.     # check if building
  326.     for building in self.buildings:
  327.       if building.collide_point(x, y) == True:
  328.         self.modal = ModalView(size_hint=(None,None), size=(420, 240))
  329.         mod_layout = GridLayout(cols=1,padding=5)
  330.        
  331.         # building or kreis?
  332.         if building.__class__.__name__ == 'Landkreis':
  333.  
  334.           if building.besitzer == 'player_self':
  335.  
  336.             # display building form
  337.  
  338.             existing = [self.buildings_names[x[0]] for x in self.tables["game_buildings"] if x[1] == building.land]
  339.  
  340.             if not existing:
  341.               self.gebaeude_buttons = []
  342.               for buildingx in self.tables["buildings"]:
  343.                 #print buildingx
  344.    
  345.                 if buildingx[1] == 0 or int(buildingx[1]) == int(self.voelker_dict[self.playername]):
  346.                   desc = buildingx[2] + ": "+ buildingx[5] + " Gold: " + str(buildingx[6]) + " (" + str(buildingx[7]) + ")"
  347.                   self.gebaeude_buttons.append(GebaeudeButton(self, building.land, buildingx[0],
  348.                                                               buildingx[7], buildingx[3], buildingx[4], desc))
  349.  
  350.                   mod_layout.add_widget(self.gebaeude_buttons[-1])
  351.             else:
  352.               mod_layout.add_widget(Label(text='Es steht schon ein Gebaeude in ' + building.land))
  353.              
  354.  
  355.         self.modal.add_widget(mod_layout)
  356.         self.modal.bind(on_dismiss=self.update_map())
  357.  
  358.  
  359.          
  360.         else:
  361.           self.modal.add_widget(Label(text='Touch auf ' + building._type + ' in Land '+building.land))
  362.        
  363.         self.modal.open()
  364.  
  365.    
  366.  
  367. if __name__ in ('__android__','__main__'):
  368.   Conquest().run()
  369.  
  370.  
  371.  
  372.  
  373.  
  374. # seperate file
  375. import sqlite3
  376. import random
  377.  
  378. class DbHelper():
  379.  
  380.     def __init__(self,database):
  381.         string = database + ".db"
  382.         self.conn = sqlite3.connect(string)
  383.         self.cursor = self.conn.cursor()
  384.         self.tables = ["both_land", "buildings", "game", "game_buildings", "helden"]
  385.  
  386.     def prepareNewGame(self, **kwargs):
  387.  
  388.         # delete old tables first
  389.         query = ''
  390.         for name in self.tables:
  391.             query += "DROP TABLE IF EXISTS " + name + ";"
  392.            
  393.         self.cursor.executescript(query)
  394.  
  395.  
  396.      
  397.  
  398.         # create new tables and content
  399.        
  400.         self.cursor.executescript("""
  401.        CREATE TABLE [both_land] (
  402.        [id] INTEGER DEFAULT '0' NOT NULL PRIMARY KEY,
  403.        [name] VARCHAR  NULL,
  404.        [positionX] INTEGER  NOT NULL,
  405.        [positionY] INTEGER  NOT NULL,
  406.        [nachbarn] varchar  NULL,
  407.        [besitzer] varchar  NULL,
  408.        [kontinent] varchar  NULL,
  409.        [effect] varchar
  410.        );
  411.  
  412.        CREATE TABLE [buildings] (
  413.        [id] INTEGER DEFAULT '0' NOT NULL PRIMARY KEY,
  414.        [volk] INTEGER  NOT NULL,
  415.        [name] VARCHAR(50)  NULL,
  416.        [var1] VARCHAR(50)  NULL,
  417.        [var2] VARCHAR(50)  NULL,
  418.        [description] VARCHAR(250)  NULL,
  419.        [cost] INTEGER  NOT NULL,
  420.        [runden] INTEGER  NULL
  421.        );
  422.  
  423.        CREATE TABLE [game] (
  424.        [runde] INTEGER DEFAULT '0' NOT NULL,
  425.        [players] VARCHAR(150)  NULL,
  426.        [turn] VARCHAR(150) NOT NULL,
  427.        [capitals] VARCHAR(200) NOT NULL,
  428.        [colors] VARCHAR(150) NOT NULL,
  429.        [money] VARCHAR(150) NOT NULL,
  430.        [voelker]  VARCHAR(150) NOT NULL
  431.        );
  432.  
  433.        CREATE TABLE [game_buildings] (
  434.        [type] INTEGER  NOT NULL,
  435.        [land] INTEGER  NOT NULL,
  436.        [status] INTEGER  NULL,
  437.        [var1] VARCHAR(50) NULL,
  438.        [var2] VARCHAR(50) NULL
  439.        );
  440.  
  441.        CREATE TABLE [helden] (
  442.        [id] INTEGER NOT NULL PRIMARY KEY,
  443.        [name] VARCHAR(30) NOT NULL,
  444.        [volk] INTEGER NOT NULL,
  445.        [kp] INTEGER NOT NULL,
  446.        [effectivity] INTEGER NOT NULL,
  447.        [class] INTEGER NOT NULL,
  448.        [effect] VARCHAR(40) NOT NULL,
  449.        [land] VARCHAR(40),
  450.        [alive] INTEGER NOT NULL,
  451.        [moved] INTEGER NOT NULL,
  452.        [fortress]  INTEGER NOT NULL
  453.        );
  454.        """)
  455.  
  456.  
  457.  
  458.         ### insert into game table ###
  459.        
  460.         playerstr = 'player_self'
  461.         playerslist = [playerstr]
  462.         if not kwargs["bots"]:
  463.             bots = 2
  464.         else:
  465.             bots = kwargs["bots"]
  466.  
  467.         for x in range(0,bots):
  468.             playerslist.append('Bot['+str(x)+']')
  469.  
  470.         playerstring = '|||'.join(playerslist)
  471.  
  472.        
  473.  
  474.  
  475.         # determine capitals
  476.         # capital list
  477.         capitals = {2 : ["Brandyberge", "Arnor"],
  478.                     3 : ["Brandyberge", "Arnor", "Dam Enroh"],
  479.                     4 : ["Einsame Lande", "Sued-Gondor", "Arnor", "Annunor"]
  480.                     }
  481.        
  482.         # now randomly assign capitals
  483.         random.shuffle(capitals[bots+1])
  484.         capitals = capitals[bots+1]
  485.         capitalstring = '|||'.join(capitals)
  486.  
  487.         player_capitals = dict(zip(capitals, playerslist))
  488.         r_player_capitals = dict(zip(playerslist, capitals))
  489.  
  490.         colors = ['black', 'green', 'maroon', 'navy']
  491.         random.shuffle(colors)
  492.         colors = colors[:bots]
  493.         colors = ['orange'] + colors
  494.         colorstr = '|||'.join(colors)
  495.        
  496.         moneystr = ''
  497.         for i in range(0,bots+1):
  498.             moneystr += '20|||'
  499.  
  500.         voelker_strr = ['Menschen', 'Orks', 'Elben', 'Isengard', 'Haradrim', 'Angmar', 'Zwerge']
  501.         voelker = ['1','2','3','4','5','6','7']
  502.         random.shuffle(voelker)
  503.         voelker = voelker[:bots+1]
  504.         voelkerstr = '|||'.join(voelker)
  505.  
  506.         player_voelker = dict(zip(voelker, playerslist))
  507.            
  508.  
  509.  
  510.         self.cursor.execute("""
  511.        INSERT INTO game VALUES (
  512.        0, ?, ?, ?, ?, ?, ?
  513.        )
  514.  
  515.        """, [playerstring, playerstr[:-2], capitalstring, colorstr, moneystr, voelkerstr])
  516.         # you are the first player
  517.  
  518.  
  519.  
  520.        
  521.  
  522.         ### insert country data by csv ###
  523.         fp = open("land_csv.csv", "r")
  524.         content = fp.read()
  525.         fp.close()
  526.        
  527.        
  528.         query = ''
  529.         for row in content.split("\n"):
  530.             values = row.split("|||")
  531.             values = [x[1:-1] for x in values]
  532.             #print values
  533.             # only if name not empty
  534.             if values[0] != '':
  535.                 besitzer = ''
  536.                 if values[0] in player_capitals.keys():
  537.                     besitzer = player_capitals[values[0]]
  538.                 query += "INSERT INTO both_land VALUES (NULL, '%s', %d, %d, '%s', '%s', '%s', '%s'); " % \
  539.                 (values[0], int(values[1]), int(values[2]), values[3], besitzer, values[5], values[6])
  540.  
  541.        
  542.  
  543.         self.cursor.executescript(query)
  544.  
  545.         query = ''
  546.         fp = open("gebaeude_csv.csv")
  547.         content = fp.read()
  548.         fp.close()
  549.  
  550.         for row in content.split("\n"):
  551.             values = row.split("|||")
  552.             values = [x[1:-1] for x in values]
  553.             if values[0] != '':
  554.                 query += "INSERT INTO buildings VALUES (NULL, %d, '%s', '%s', '%s', '%s', %d, %d); " % \
  555.                 (int(values[0]), values[1], values[2], values[3], values[4], int(values[5]), int(values[6]))
  556.  
  557.         self.cursor.executescript(query)
  558.  
  559.  
  560.         query = ''
  561.         fp = open("helden_csv.csv")
  562.         content = fp.read()
  563.         fp.close()
  564.  
  565.         for row in content.split("\n"):
  566.             values = row.split(",")
  567.             values = [x[1:-1] for x in values]
  568.             # volk = values[2]
  569.             # determine startland
  570.             volk = values[2]
  571.             if volk in voelker:
  572.                 player = player_voelker[values[2]]
  573.                 startland = r_player_capitals[player]
  574.             else:
  575.                 # volk nicht besetzt
  576.                 startland = ''
  577.            
  578.            
  579.             query += "INSERT INTO helden VALUES (%d, '%s', %d, %d, %d, %d, '%s', '%s', %d, %d, %d)" % \
  580.                      (int(values[0]), values[1], int(values[2]), int(values[3]), int(values[4]),
  581.                       int(values[5]), values[6], startland, 1, 0, int(values[10]))
  582.  
  583.  
  584.         self.conn.commit()
  585.  
  586.         return voelker[0]
  587.  
  588.        
  589.    
  590.     def fetchTables(self,tables):
  591.         self.cursor = self.conn.cursor()
  592.         data = {}
  593.         for name in tables:
  594.             self.cursor.execute("SELECT * FROM " + name)
  595.             if not name == 'game':
  596.                 data[name] = self.cursor.fetchall()
  597.             else:
  598.                 data[name] = self.cursor.fetchall()[0]
  599.  
  600.         return data
  601.  
  602.  
  603.     def insertTo(self, table, values):
  604.         self.cursor = self.conn.cursor()
  605.         query = 'INSERT INTO ' + table + ' VALUES ('
  606.         for value in values:
  607.             query += '?,'
  608.         query = query[:-1]
  609.         query += ');'
  610.         print query, values
  611.         self.cursor.execute(query, values)
  612.         self.conn.commit()
  613.         return True
Advertisement
Add Comment
Please, Sign In to add comment