Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: cp1252 -*-
- #### kivy imports
- import kivy
- from kivy.app import App
- from kivy.uix.floatlayout import FloatLayout
- from kivy.uix.dropdown import DropDown
- from kivy.uix.button import Button
- from kivy.uix.gridlayout import GridLayout
- from kivy.uix.modalview import ModalView
- from kivy.uix.scatter import Scatter
- from kivy.uix.scatter import ScatterPlane
- from kivy.uix.image import *
- from kivy.graphics import Color, Ellipse
- from kivy.uix.widget import Widget
- from kivy.uix.label import Label
- from kivy.uix.image import Image
- from kivy.base import EventLoop
- from kivy.utils import *
- from kivy.clock import Clock
- from time import sleep
- ### conquest imports
- from DbHelper import *
- from Utilities import *
- TURM_X = 7
- TURM_Y = 7
- KREIS_X = 5.
- KREIS_Y = 5.
- # Tower
- class Building(Image):
- def __init__(self, _type, land, besitzer, pos1, pos2, status=0, var1='', var2=''):
- self.land = land
- self.pos1 = pos1
- self.pos2 = pos2
- self._type = _type
- self.status = status
- self.var1 = var1
- self.var2 = var2
- self.besitzer = besitzer
- if _type == 'Kampfturm':
- bild = 'turm.png'
- if _type == 'Kaserne':
- bild = 'kaserne.png'
- pos2 = pos2 - 2
- if _type == 'Festung':
- bild = 'festung.png'
- pos2 = pos2 - 2
- if _type == 'Universitaet':
- bild = 'uni.png'
- return Image.__init__(self, source='media/'+bild, pos=(pos1,pos2), size=(TURM_X, TURM_Y))
- class Landkreis(Image):
- def __init__(self, _color, land, besitzer, pos1, pos2):
- self.land = land
- self.pos1 = int(pos1)
- self.pos2 = int(pos2)
- self._color = _color
- self.besitzer = besitzer
- bild = 'media/kreis_' + _color + '.jpg'
- return Image.__init__(self, source=bild, pos=( int(pos1),int(pos2) ), size=(KREIS_X, KREIS_Y))
- class GebaeudeButton(Button):
- def __init__(self, conquest, land, _id, _status, var1, var2, desc):
- self._id = _id
- self.land = land
- self._status = _status
- self.var1 = var1
- self.var2 = var2
- self.conquest = conquest
- return Button.__init__(self, text=desc, font_size=11, size_hint_y=None, height=44, background_normal='media/kachel.png')
- def on_press(self):
- self.db = DbHelper("game")
- table = self.db.fetchTables(["game_buildings"])
- fail = False
- for building in table:
- if building[1] == self.land:
- fail = True
- print "there is already a building in ", self.land
- if fail == False:
- self.db.insertTo("game_buildings", [self._id, self.land, self._status, self.var1, self.var2])
- self.conquest.modal.dismiss()
- self.conquest.update_map()
- # Main App Class
- class Conquest(App):
- # called at app start
- def build(self):
- # prepare database
- self.db = DbHelper("game") # standard database
- self.root = GridLayout(cols=1)
- new_game_btn = Button(text='New Game')
- self.root.add_widget(new_game_btn)
- new_game_btn.bind(on_press=self.new_game)
- continue_btn = Button(text='Continue')
- self.root.add_widget(continue_btn)
- continue_btn.bind(on_press=self.init_ingame)
- return self.root
- def new_game(self, instance):
- # delete old game data
- # create new game data
- self.playername = self.db.prepareNewGame(**{'bots':2})
- self.init_ingame(self)
- # prepares ingame widgets
- def init_ingame(self, instance):
- self.tables = self.db.fetchTables(["both_land", "game", "game_buildings", "buildings"])
- self.playername = 'player_self'
- ### basic layout preperation ###
- self.root.clear_widgets()
- layout = ScatterPlane(do_rotation=False)
- self.floating = FloatLayout()
- map_image = Image(source='map.png', size=(480,411))
- self.floating.add_widget(map_image)
- self.root.bind(on_touch_down=self.on_touch_down)
- ### GET GAME DICTS ###
- # money dict
- # player : money
- self.money_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][5].split("|||")))
- self.voelker_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][6].split("|||")))
- # create capital dict
- #print tables["game_buildings"]
- self.capital_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][3].split("|||")))
- self.turn = self.tables["game"][2] # current player
- # create color dict
- self.color_dict = dict(zip(self.tables["game"][1].split("|||"), self.tables["game"][4].split("|||")))
- ### SHOW MONEY ###
- m_text = 'Gold: ' + str(self.money_dict[self.playername])
- self.money_anzeige = Label(text=m_text)
- self.root.add_widget(self.money_anzeige)
- ### BUILDING ID + NAME ###
- self.buildings_names = {}
- for _id, _volk, _name, _var1, _var2, _description, _cost, _runden in self.tables["buildings"]:
- self.buildings_names[_id] = _name
- self.update_map()
- layout.add_widget(self.floating)
- self.root.add_widget(layout)
- def update_map(self, delay=0):
- self.tables = self.db.fetchTables(["both_land", "game", "game_buildings", "buildings"])
- #print self.tables["game_buildings"]
- #print self.tables["buildings"]
- if delay > 0:
- sleep(delay)
- self.floating.clear_widgets()
- map_image = Image(source='map.png', size=(480,411))
- self.floating.add_widget(map_image)
- self.laender = {} # name : koordinaten
- self.besitzer = {} # name : besitzer
- self.buildings = []
- current_x = {}
- current_y = {}
- for _id, name, positionX, positionY, nachbarn, besitzer, kontinent, effect in self.tables["both_land"]:
- current_x[name] = 6
- current_y[name] = 0
- position = Utilities.getRealCoordinates(positionX, positionY)
- self.laender[name] = position
- self.besitzer[name] = besitzer
- if besitzer == '':
- color = 'neutral'
- else:
- color = self.color_dict[besitzer]
- # create circle
- element = Landkreis(color, name, besitzer, position[0], position[1])
- self.buildings.append(element)
- self.floating.add_widget(self.buildings[-1])
- for _type, land, status, var1, var2 in self.tables["game_buildings"]:
- type_real = ''
- if self.buildings_names[_type] == u'Kampfturm':
- type_real = 'Kampfturm'
- if var1 == 'recruit':
- type_real = 'Kaserne'
- if var2 == 'festung':
- type_real = 'Festung'
- if var1 == 'university':
- type_real = 'Universitaet'
- if type_real:
- element = Building(type_real, land, besitzer, self.laender[land][0] + current_x[land],
- self.laender[land][1] + current_y[land], status, var1, var2)
- current_x[land] += 10 if not var2 == "Festung" else 22
- if element:
- self.buildings.append(element)
- # add this element to GUI
- self.floating.add_widget(self.buildings[-1])
- def on_touch_down(self, obj, touch):
- #binded to on_touch_down event of the root Grid layout
- obj = obj.children[0]
- #print obj
- #print touch.x, touch.y
- (x,y) = obj.to_local(touch.x, touch.y)
- # check if building
- for building in self.buildings:
- if building.collide_point(x, y) == True:
- self.modal = ModalView(size_hint=(None,None), size=(420, 240))
- mod_layout = GridLayout(cols=1,padding=5)
- # building or kreis?
- if building.__class__.__name__ == 'Landkreis':
- if building.besitzer == 'player_self':
- # display building form
- existing = [self.buildings_names[x[0]] for x in self.tables["game_buildings"] if x[1] == building.land]
- if not existing:
- self.gebaeude_buttons = []
- for buildingx in self.tables["buildings"]:
- #print buildingx
- if buildingx[1] == 0 or int(buildingx[1]) == int(self.voelker_dict[self.playername]):
- desc = buildingx[2] + ": "+ buildingx[5] + " Gold: " + str(buildingx[6]) + " (" + str(buildingx[7]) + ")"
- self.gebaeude_buttons.append(GebaeudeButton(self, building.land, buildingx[0],
- buildingx[7], buildingx[3], buildingx[4], desc))
- mod_layout.add_widget(self.gebaeude_buttons[-1])
- else:
- mod_layout.add_widget(Label(text='Es steht schon ein Gebaeude in ' + building.land))
- self.modal.add_widget(mod_layout)
- self.modal.bind(on_dismiss=self.update_map())
- else:
- self.modal.add_widget(Label(text='Touch auf ' + building._type + ' in Land '+building.land))
- self.modal.open()
- if __name__ in ('__android__','__main__'):
- Conquest().run()
- # seperate file
- import sqlite3
- import random
- class DbHelper():
- def __init__(self,database):
- string = database + ".db"
- self.conn = sqlite3.connect(string)
- self.cursor = self.conn.cursor()
- self.tables = ["both_land", "buildings", "game", "game_buildings", "helden"]
- def prepareNewGame(self, **kwargs):
- # delete old tables first
- query = ''
- for name in self.tables:
- query += "DROP TABLE IF EXISTS " + name + ";"
- self.cursor.executescript(query)
- # create new tables and content
- self.cursor.executescript("""
- CREATE TABLE [both_land] (
- [id] INTEGER DEFAULT '0' NOT NULL PRIMARY KEY,
- [name] VARCHAR NULL,
- [positionX] INTEGER NOT NULL,
- [positionY] INTEGER NOT NULL,
- [nachbarn] varchar NULL,
- [besitzer] varchar NULL,
- [kontinent] varchar NULL,
- [effect] varchar
- );
- CREATE TABLE [buildings] (
- [id] INTEGER DEFAULT '0' NOT NULL PRIMARY KEY,
- [volk] INTEGER NOT NULL,
- [name] VARCHAR(50) NULL,
- [var1] VARCHAR(50) NULL,
- [var2] VARCHAR(50) NULL,
- [description] VARCHAR(250) NULL,
- [cost] INTEGER NOT NULL,
- [runden] INTEGER NULL
- );
- CREATE TABLE [game] (
- [runde] INTEGER DEFAULT '0' NOT NULL,
- [players] VARCHAR(150) NULL,
- [turn] VARCHAR(150) NOT NULL,
- [capitals] VARCHAR(200) NOT NULL,
- [colors] VARCHAR(150) NOT NULL,
- [money] VARCHAR(150) NOT NULL,
- [voelker] VARCHAR(150) NOT NULL
- );
- CREATE TABLE [game_buildings] (
- [type] INTEGER NOT NULL,
- [land] INTEGER NOT NULL,
- [status] INTEGER NULL,
- [var1] VARCHAR(50) NULL,
- [var2] VARCHAR(50) NULL
- );
- CREATE TABLE [helden] (
- [id] INTEGER NOT NULL PRIMARY KEY,
- [name] VARCHAR(30) NOT NULL,
- [volk] INTEGER NOT NULL,
- [kp] INTEGER NOT NULL,
- [effectivity] INTEGER NOT NULL,
- [class] INTEGER NOT NULL,
- [effect] VARCHAR(40) NOT NULL,
- [land] VARCHAR(40),
- [alive] INTEGER NOT NULL,
- [moved] INTEGER NOT NULL,
- [fortress] INTEGER NOT NULL
- );
- """)
- ### insert into game table ###
- playerstr = 'player_self'
- playerslist = [playerstr]
- if not kwargs["bots"]:
- bots = 2
- else:
- bots = kwargs["bots"]
- for x in range(0,bots):
- playerslist.append('Bot['+str(x)+']')
- playerstring = '|||'.join(playerslist)
- # determine capitals
- # capital list
- capitals = {2 : ["Brandyberge", "Arnor"],
- 3 : ["Brandyberge", "Arnor", "Dam Enroh"],
- 4 : ["Einsame Lande", "Sued-Gondor", "Arnor", "Annunor"]
- }
- # now randomly assign capitals
- random.shuffle(capitals[bots+1])
- capitals = capitals[bots+1]
- capitalstring = '|||'.join(capitals)
- player_capitals = dict(zip(capitals, playerslist))
- r_player_capitals = dict(zip(playerslist, capitals))
- colors = ['black', 'green', 'maroon', 'navy']
- random.shuffle(colors)
- colors = colors[:bots]
- colors = ['orange'] + colors
- colorstr = '|||'.join(colors)
- moneystr = ''
- for i in range(0,bots+1):
- moneystr += '20|||'
- voelker_strr = ['Menschen', 'Orks', 'Elben', 'Isengard', 'Haradrim', 'Angmar', 'Zwerge']
- voelker = ['1','2','3','4','5','6','7']
- random.shuffle(voelker)
- voelker = voelker[:bots+1]
- voelkerstr = '|||'.join(voelker)
- player_voelker = dict(zip(voelker, playerslist))
- self.cursor.execute("""
- INSERT INTO game VALUES (
- 0, ?, ?, ?, ?, ?, ?
- )
- """, [playerstring, playerstr[:-2], capitalstring, colorstr, moneystr, voelkerstr])
- # you are the first player
- ### insert country data by csv ###
- fp = open("land_csv.csv", "r")
- content = fp.read()
- fp.close()
- query = ''
- for row in content.split("\n"):
- values = row.split("|||")
- values = [x[1:-1] for x in values]
- #print values
- # only if name not empty
- if values[0] != '':
- besitzer = ''
- if values[0] in player_capitals.keys():
- besitzer = player_capitals[values[0]]
- query += "INSERT INTO both_land VALUES (NULL, '%s', %d, %d, '%s', '%s', '%s', '%s'); " % \
- (values[0], int(values[1]), int(values[2]), values[3], besitzer, values[5], values[6])
- self.cursor.executescript(query)
- query = ''
- fp = open("gebaeude_csv.csv")
- content = fp.read()
- fp.close()
- for row in content.split("\n"):
- values = row.split("|||")
- values = [x[1:-1] for x in values]
- if values[0] != '':
- query += "INSERT INTO buildings VALUES (NULL, %d, '%s', '%s', '%s', '%s', %d, %d); " % \
- (int(values[0]), values[1], values[2], values[3], values[4], int(values[5]), int(values[6]))
- self.cursor.executescript(query)
- query = ''
- fp = open("helden_csv.csv")
- content = fp.read()
- fp.close()
- for row in content.split("\n"):
- values = row.split(",")
- values = [x[1:-1] for x in values]
- # volk = values[2]
- # determine startland
- volk = values[2]
- if volk in voelker:
- player = player_voelker[values[2]]
- startland = r_player_capitals[player]
- else:
- # volk nicht besetzt
- startland = ''
- query += "INSERT INTO helden VALUES (%d, '%s', %d, %d, %d, %d, '%s', '%s', %d, %d, %d)" % \
- (int(values[0]), values[1], int(values[2]), int(values[3]), int(values[4]),
- int(values[5]), values[6], startland, 1, 0, int(values[10]))
- self.conn.commit()
- return voelker[0]
- def fetchTables(self,tables):
- self.cursor = self.conn.cursor()
- data = {}
- for name in tables:
- self.cursor.execute("SELECT * FROM " + name)
- if not name == 'game':
- data[name] = self.cursor.fetchall()
- else:
- data[name] = self.cursor.fetchall()[0]
- return data
- def insertTo(self, table, values):
- self.cursor = self.conn.cursor()
- query = 'INSERT INTO ' + table + ' VALUES ('
- for value in values:
- query += '?,'
- query = query[:-1]
- query += ');'
- print query, values
- self.cursor.execute(query, values)
- self.conn.commit()
- return True
Advertisement
Add Comment
Please, Sign In to add comment