Browse Source

python3 porting

master
Dmitry Vyal 3 years ago
parent
commit
ab7673c4a0
3 changed files with 41 additions and 38 deletions
  1. +18
    -15
      client.py
  2. +3
    -3
      game.py
  3. +20
    -20
      ui.py

+ 18
- 15
client.py View File

@ -8,7 +8,7 @@ import sys
import select
import time
import os
import ConfigParser
import configparser
import ast
TIMEOUT = 15
@ -16,7 +16,7 @@ TIMEOUT = 15
class Config:
def __init__(self, game_mode="training", server_url="http://vindinium.org",
number_of_games=1, number_of_turns=300, map_name="m3", key=None):
number_of_games=1, number_of_turns=300, map_name="m3", key=None):
self.game_mode = game_mode
self.number_of_games = number_of_games
self.number_of_turns = number_of_turns
@ -37,7 +37,7 @@ class Client:
self.bot = Curses_ui_bot() # Our bot
self.states = []
self.delay = 0.5 # Delay in s between turns in replay mode
self.victory = 0
self.victory = 0
self.time_out = 0
def pprint(self, *args, **kwargs):
@ -52,7 +52,7 @@ class Client:
a = 1
coma = ""
printable = printable + "["
for k, v in kwargs.iteritems():
for k, v in kwargs.items():
if 1 < a < len(kwargs):
coma = ", "
else:
@ -69,7 +69,7 @@ class Client:
def load_config(self):
"""Load saved config from file ~/.vindinium/config"""
config_parser = ConfigParser.ConfigParser()
config_parser = configparser.ConfigParser()
user_home_dir = os.path.expanduser("~")
config_file_name = os.path.join(user_home_dir, ".vindinium", "config")
try:
@ -81,14 +81,14 @@ class Client:
self.config.key = config_parser.get("game", "key")
self.config.number_of_games = config_parser.getint("game", "number_of_games")
self.config.number_of_turns = config_parser.getint("game", "number_of_turns")
except (IOError, ConfigParser.Error) as e:
except (IOError, configparser.Error) as e:
self.gui.quit_ui()
print ("Error while loading config file", config_file_name, ":", e)
quit(1)
def save_config(self):
"""Save config to file in ~/.vindinium/config"""
config_parser = ConfigParser.ConfigParser()
config_parser = configparser.ConfigParser()
user_home_dir = os.path.expanduser("~")
config_file_name = os.path.join(user_home_dir, ".vindinium", "config")
try:
@ -99,7 +99,7 @@ class Client:
for key, value in self.config.__dict__.items():
config_parser.set("game", key, value)
config_parser.write(config_file)
except (IOError, ConfigParser.Error) as e:
except (IOError, configparser.Error) as e:
self.gui.quit_ui()
print ("Error while saving config file", config_file_name, ":", e)
quit(1)
@ -132,6 +132,7 @@ class Client:
game_id = self.states[0]['game']["id"]
except IndexError:
self.pprint("No states available for this game, unable to save game.")
return
game_file_name = os.path.join(user_home_dir, ".vindinium", "save", game_id)
try:
if not os.path.isdir(os.path.join(user_home_dir, ".vindinium", "save")):
@ -146,9 +147,9 @@ class Client:
def download_game_file(self, game_file_url):
# I will treat no other forbidden char than space char.
game_file_url = game_file_url.replace(" ", "%20")
#
#
# FIXME :
#
#
# Game file available online at http://vindinium.org/events/<gameId>
# are not parsable by ast.literal_eval() ????
#
@ -162,7 +163,7 @@ class Client:
#
# MUST TRY:
# games=[json.loads(line[6:]) for line in requests.get(game_file_url).content.splitlines() if line.startswith("data: ")]
#
#
self.gui.quit_ui()
os.system('cls' if os.name == 'nt' else 'clear')
print ("********************************************************")
@ -372,7 +373,7 @@ class Client:
if self.bot.running:
self.bot.process_game(state)
self.display_game()
except (Exception, e):
except Exception as e:
if self.gui.log_win:
self.pprint("Error at client.restart_game:", str(e))
self.pprint("If your code or your settings are not responsible of this error, please report this error to:")
@ -397,6 +398,8 @@ class Client:
elif self.config.game_mode == 'arena':
params = {'key': self.config.key}
api_endpoint = '/api/arena'
else:
raise Exception('Unknown game mode')
# Wait for 10 minutes
try:
r = self.session.post(self.config.server_url + api_endpoint, params, timeout=10*60)
@ -474,7 +477,7 @@ class Client:
# in the display
self.gui.display_path(self.bot.path_to_goal)
# Move cursor along the time line (cost cpu time)
cursor_pos = int(float(self.gui.TIME_W) / self.bot.game.max_turns * self.bot.game.turn)
cursor_pos = int(float(self.gui.TIME_W) // self.bot.game.max_turns * self.bot.game.turn)
self.gui.move_time_cursor(cursor_pos)
# Finally display selected move
self.gui.display_move(self.bot.hero_move)
@ -513,6 +516,6 @@ if __name__ == "__main__":
client.gui.draw_game_windows()
client.play()
except Exception as e:
if hasattr(client, 'gui'):
if hasattr(client, 'gui') and client.gui is not None:
client.gui.quit_ui()
raise e
raise e

+ 3
- 3
game.py View File

@ -23,7 +23,7 @@ class Hero:
self.crashed = hero['crashed']
self.mine_count = hero['mineCount']
self.mines = []
self.name = hero['name'].encode("utf-8")
self.name = hero['name']
class Game:
@ -69,7 +69,7 @@ class Game:
self.turn = game['turn']
self.max_turns = game['maxTurns']
self.finished = game['finished']
for key in game:
for key in sorted(game.keys()): # TODO: board must go before heroes
if key in process:
process[key](game[key])
@ -85,7 +85,7 @@ class Game:
line = tiles[y:y+self.board_size*2]
for x in range(0, len(line), 2):
tile = line[x:x+2]
tile_coords = (y/self.board_size/2, x/2)
tile_coords = (y//self.board_size//2, x//2)
if tile[0] == " ":
# It's passable
char = " "


+ 20
- 20
ui.py View File

@ -5,7 +5,7 @@ import curses
import curses.panel
import curses.textpad
import re
import urlparse
from urllib.parse import urlparse
import os
# Minimal terminal size
@ -641,7 +641,7 @@ class tui:
"""Return True if num is int and if num > 0
Print error message and return false otherwise"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
if num is not None:
try:
num = int(str(num).strip(chr(0)))
@ -671,11 +671,11 @@ class tui:
def check_url(self, url):
"""Return True if url is a valid url"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
url = url.strip(chr(0)).strip()
if len(url) > 0:
# text_box.edit return a null char at start:(
check = urlparse.urlparse(url)
check = urlparse(url)
if len(check.scheme) > 0 and len(check.netloc) > 0:
return True
self.menu_win.addstr(15, offset + 12, "Please, input a valid URL.", curses.color_pair(3))
@ -685,11 +685,11 @@ class tui:
def check_file_url(self, url):
"""Return True if url is a valid url with 'file path'"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
url = url.strip(chr(0)).strip()
if len(url) > 0:
# text_box.edit return a null char at start:(
check = urlparse.urlparse(url)
check = urlparse(url)
if len(check.scheme) > 0 and \
len(check.netloc) > 0 and \
len(check.path) > 0:
@ -701,7 +701,7 @@ class tui:
def check_file_path(self, path):
"""Return True if path is an existant file name"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
path = path.strip(chr(0)).strip()
if len(path) > 0:
# text_box.edit return a null char at start
@ -714,7 +714,7 @@ class tui:
def check_key(self, player_key):
"""Check the player key format"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x / 2 - 25
offset = screen_x // 2 - 25
player_key = player_key.strip(chr(0)).strip()
if len(player_key) > 0:
pattern = "^([0-9]|[a-z]){8}"
@ -731,7 +731,7 @@ class tui:
def draw_banner(self):
"""Draw the Vindinium banner on self.menu_win"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
self.menu_win.clear()
self.menu_win.box()
self.menu_pan = curses.panel.new_panel(self.menu_win)
@ -750,7 +750,7 @@ class tui:
def ask_main_menu(self):
"""Display main menu window and ask for choice"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
choice = "0"
options = ["1", "2", "3", "4", "5"]
self.menu_win = curses.newwin(self.MENU_H, self.MENU_W, self.MENU_Y, self.MENU_X)
@ -773,7 +773,7 @@ class tui:
def ask_game_mode(self):
"""Display game mode menu and ask for choice"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
choice = "0"
options = ["1", "2"]
self.draw_banner()
@ -793,7 +793,7 @@ class tui:
def ask_number_games(self):
"""Ask for number_of_games"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
num_game = None
self.draw_banner()
self.menu_win.addstr(10, offset + 19, "ARENA MODE", curses.A_BOLD)
@ -815,7 +815,7 @@ class tui:
def ask_number_turns(self):
"""Ask for number_of_turns"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
num_turns = None
self.draw_banner()
self.menu_win.addstr(10, offset + 17, "TRAINING MODE", curses.A_BOLD)
@ -838,7 +838,7 @@ class tui:
"""Ask for server url"""
server_url = ""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
offset_2 = 19
self.draw_banner()
if game_mode == "training":
@ -865,7 +865,7 @@ class tui:
"""Ask for player key"""
player_key = ""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
offset_2 = 19
self.draw_banner()
if game_mode == "training":
@ -891,7 +891,7 @@ class tui:
"""Ask for game file url"""
file_url = ""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x / 2 - 25
offset = screen_x // 2 - 25
self.draw_banner()
self.menu_win.addstr(13, offset - 6, "File URL:", curses.A_BOLD)
curses.textpad.rectangle(self.menu_win, 12, offset + 5, 14, offset + 55)
@ -913,7 +913,7 @@ class tui:
"""Ask for game file path"""
file_path = ""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x / 2 - 25
offset = screen_x // 2 - 25
self.draw_banner()
self.menu_win.addstr(13, offset - 6, "File path:", curses.A_BOLD)
curses.textpad.rectangle(self.menu_win, 12, offset + 5, 14, offset + 55)
@ -934,7 +934,7 @@ class tui:
def ask_save_config(self):
"""Ask for config save"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
choice = "0"
options = ["1", "2"]
self.menu_win = curses.newwin(self.MENU_H, self.MENU_W, self.MENU_Y, self.MENU_X)
@ -953,7 +953,7 @@ class tui:
def ask_play_game(self):
"""Ask for playing game"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
choice = "0"
options = ["1", "2"]
self.menu_win = curses.newwin(self.MENU_H, self.MENU_W, self.MENU_Y, self.MENU_X)
@ -972,7 +972,7 @@ class tui:
def ask_map(self):
"""Display main menu window and ask for choice"""
screen_y, screen_x = self.stdscr.getmaxyx()
offset = screen_x/2 - 25
offset = screen_x // 2 - 25
choice = "0"
options = ["1", "2", "3", "4", "5", "6"]
self.menu_win = curses.newwin(self.MENU_H, self.MENU_W, self.MENU_Y, self.MENU_X)


Loading…
Cancel
Save