Exemple #1
0
class MainForm(tk.Canvas):
    size = 8
    cell_size = 60
    margin = 7

    def __init__(self, master):
        width = self.size * self.cell_size + 1
        tk.Canvas.__init__(self,
                           master,
                           relief=tk.RAISED,
                           bd=4,
                           bg="green",
                           width=width,
                           height=width)

        self.grid(column=0, row=0)

        self.controller = GameController(self, self.size, BasicAI(), BasicAI())
        self.controller.play()

    def refresh(self, board):
        for i in range(self.size):
            for j in range(self.size):
                x0 = i * self.cell_size + self.margin
                y0 = j * self.cell_size + self.margin
                self.create_rectangle(x0,
                                      y0,
                                      x0 + self.cell_size,
                                      y0 + self.cell_size,
                                      fill="green")
                if not board.isBlank(j, i) and board.isBlack(j, i):
                    self.create_oval(x0 + 2,
                                     y0 + 2,
                                     x0 + self.cell_size - 2,
                                     y0 + self.cell_size - 2,
                                     fill="black")
                elif not board.isBlank(j, i) and not board.isBlack(j, i):
                    self.create_oval(x0 + 2,
                                     y0 + 2,
                                     x0 + self.cell_size - 2,
                                     y0 + self.cell_size - 2,
                                     fill="white")

    def refresh_color(self, board, isBlack):
        self.refresh(board)
        for i in range(self.size):
            for j in range(self.size):
                if board.canPlace(j, i, isBlack):
                    x = i * self.cell_size + self.margin + self.cell_size / 2
                    y = j * self.cell_size + self.margin + self.cell_size / 2
                    self.create_text(x,
                                     y,
                                     text=str(board.getEValue(j, i, isBlack)),
                                     justify="center")
Exemple #2
0
def main():
    pygame.init()
    pygame.display.set_caption("game_of_blocks")
    clock = pygame.time.Clock()
    #pygame.mixer.init()
    #pygame.mixer.music.load('theme.mp3')
    #pygame.mixer.music.play(0)
    controller = GameController(Config)
    controller.startGame()
    gameover = False
    gameLoop(clock, controller, gameover)
    pygame.quit()
Exemple #3
0
    def main(self):
        pygame.display.set_caption('Tamagotchi')
        controller = GameController(self.screen)

        while self.running:
            controller.update_game()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                else:
                    controller.handle_event(event)
Exemple #4
0
    def __init__(self, master):
        width = self.size * self.cell_size + 1
        tk.Canvas.__init__(self,
                           master,
                           relief=tk.RAISED,
                           bd=4,
                           bg="green",
                           width=width,
                           height=width)

        self.grid(column=0, row=0)

        self.controller = GameController(self, self.size, BasicAI(), BasicAI())
        self.controller.play()
Exemple #5
0
def run():
    ## create transport
    tcp = TCPClient("localhost", 33345)
    ## create game communication
    client = CommClient(tcp)
    ## create UI
    ui = GameController(client,tcp)  
    client.set_ui(ui)
    ## main loop
    tcp.start()
    tcp.join(0.5)
    if tcp.isAlive():
        ui.new_game_ind()
    else:
        print("Connection couldn't be established")
Exemple #6
0
def main():


    image_process()
    ctrl = GameController(width=1920, height=1080, caption='My own cute Pyglet v%s' % VERSION,
                          resizable=True, vsync=False, fullscreen=True)
    # ctrl.log_events()
    # Hide the mouse cursor and prevent the mouse from leaving the window.
    ctrl.set_exclusive_mouse(True)
    ctrl.renderer.setup()
    print("App started.")
    GameLoader(ctrl).load_game()
    pyglet.app.run()
    print("App stopped.")
    GameSaver(ctrl).save_game()
Exemple #7
0
 def load_assets(self):
     self.ctrl = GameController(self)
     self.all_sprites = pg.sprite.LayeredUpdates()
     self.enemies = pg.sprite.Group()
     self.snowflakes = pg.sprite.Group()
     self.Player = Player(self)
     self.Background = Background(self)
     self.Enemy = Enemy(self)
     self.Playerstats = PlayerStats(self)
Exemple #8
0
def play():
    """
    Run this function to start the Knight's Tour Puzzle.
    It can be solved either by user or CPU.
    """
    # board setup
    ctrl = GameController()
    board = ctrl.input_board_dimensions()
    # initial move
    board.current = ctrl.input_coordinates()
    # solution option (user or cpu)
    solve = ctrl.select_solution_option()
    # check if solvable
    if board.is_solvable():
        board.update_adj_possib()
        solve(ctrl)
    else:
        print('No solution exists!')
Exemple #9
0
    def on_join_regular(self):
        global game_controller
        game_controller = GameController()
        main_scene = Scene(game_controller.map, game_controller)
        director.push(main_scene)

        #adding a background layer that lies below all layers
        background_layer = ImageLayer(
            os.path.join("images", "backgrounds", "notebook-paper.png"))
        main_scene.add(background_layer, z=-1)
Exemple #10
0
def play_game():
    game = GameController()
    tracker = PlayTracker()
    bot = BotPlayer(MODEL_FILE, PLAYS_CATEGORIES_FILE, RESULT_CATEGORIES_FILE)

    while game.is_playing():
        ui.draw_board(game)

        x, y = -1, -1
        if game.current_player_A():
            x, y = ui.read_user_play(game)
        else:
            x, y = bot.play(game)
            ui.print_bot_play(x, y)

        tracker.track(game, x, y)
        game.play(x, y)

    ui.draw_winner(game)
    tracker.store(game, PLAYS_FILE)
    train_model(PLAYS_FILE, MODEL_FILE, PLAYS_CATEGORIES_FILE,
                RESULT_CATEGORIES_FILE)
Exemple #11
0
from controller import GameController
from flask import Flask, jsonify

app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy   dog'
app.config['CORS_HEADERS'] = 'Content-Type'

game = GameController.GamerController()


@app.route('/play')
def play():
    response = jsonify(game.play())
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response


@app.route('/players')
def players():
    list = []
    for i in game.get_players():
        list.append({'name': i.get_name(), 'money': i.get_money()})
    response = jsonify(list)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response


if __name__ == '__main__':
    app.run('0.0.0.0', 5000, debug=True)
Exemple #12
0
def main() -> None:
    model = GameModel()
    controller = GameController(model)
    view = GameView(controller, board_size=300, grid_size=3)
Exemple #13
0
# https://stackoverflow.com/questions/287871/print-in-terminal-with-colors
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


while True:
    # Get preliminary screenshot.
    print("Taking preliminary screenshot...")
    prelim_screenshot = GameController.get_screen_image()
    prelim_td = TableDetector()
    prelim_td.load_image(prelim_screenshot)
    prelim_td.detect_all()

    # Determine where to place the cue for real screenshot.
    prelim_controller = GameController(prelim_td.tableSize,
                                       prelim_td.tableCropTopLeft,
                                       prelim_td.balls, prelim_td.ballRadius)
    stick_target = prelim_controller.find_stick_position()
    prelim_controller.move_mouse(stick_target)

    # Get real screenshot.
    print("Taking real screenshot...")
    screenshot = GameController.get_screen_image()
    td = TableDetector()
Exemple #14
0
def left_action(*args):
    print("LEFT")
    app.controller.action(Direction.LEFT)

def right_action(*args):
    app.controller.action(Direction.RIGHT)
    print("RIGHT")

def up_action(*args):
    app.controller.action(Direction.UP)
    print("UP")

def down_action(*args):
    app.controller.action(Direction.DOWN)
    print("Down")

root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.title("2048")
app = AppUI(root)
app.controller = GameController(app.visualizer)
app.visualizer.set_model(app.controller.model)
app.visualizer.start()
#root.bind('<Return>', solve)
root.bind('<Left>', left_action)
root.bind('<Right>', right_action)
root.bind('<Up>', up_action)
root.bind('<Down>', down_action)
root.mainloop() 
Exemple #15
0
def main():
    # get players
    player1, player2 = initialisePlayer()
    # build board
    boardConfig = {
        "size": initialiseBoard()
        # "size": 5
    }
    board = Board(**boardConfig)
    gameController = GameController(board)

    # reset
    gameController.resetBoard()
    gameController.printBoard()

    # build battleship and place
    ships = initialiseShip()
    for ship in ships:
        gameController.place(Battleship(**ship))
        gameController.printBoard()
    
    # player attacks
    print(gameController.attack(**playerAttack()))
    gameController.printBoard()
Exemple #16
0
def main():
    controller = GameController(constants.SCREEN)
    while True:
        for event in pygame.event.get():
            controller.handle(event)
Exemple #17
0
from controller import GameController
from domain.model import Card, Suit, Rank, Hand
from domain.service import Simulator, GameRecorder
from view import GameViewer, SimulationViewer
from configuration import ConfigLoader

config_loader = ConfigLoader()
config_loader.config_logger()

simulator = Simulator(config_loader)
game_viewer = GameViewer()
sim_viewer = SimulationViewer()
game_recorder = GameRecorder(config_loader, game_viewer)

game_controller = GameController(config_loader, simulator, game_viewer,
                                 sim_viewer, game_recorder)
game_controller.control = False
game_controller.pause = False
game_controller.use_advice = True
game_controller.start_up()
Exemple #18
0
class TestBattleShips(TestCase):
    def setUp(self):
        self.shipRepository = ShipRepository()
        self.boardRepository = BoardRepository()
        self.gameController = GameController(self.boardRepository,
                                             self.shipRepository)

    def testAddShip(self):
        board = self.boardRepository.getBoard(1, 1)
        self.assertEqual(board.getMark("A1"), ".")
        self.assertEqual(board.getMark("A2"), ".")
        self.assertEqual(board.getMark("A3"), ".")

        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("test", 1)
        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("A1A2", 1)
        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("", 1)
        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("BBBBBB", 1)
        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("A1A2A9", 1)
        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("I8I9I7", 1)
        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("a1a2a3", 1)

        self.gameController.addShip("A1A2A3", 1)
        self.assertEqual(board.getMark("A1"), "+")
        self.assertEqual(board.getMark("A2"), "+")
        self.assertEqual(board.getMark("A3"), "+")
        self.assertEqual(board.getMark("B1"), ".")

        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("A1A2A3", 1)

        with self.assertRaises(CoordinateInvalid):
            self.gameController.addShip("A1B1C1", 1)

        self.assertEqual(board.getMark("A1"), "+")
        self.assertEqual(board.getMark("A2"), "+")
        self.assertEqual(board.getMark("A3"), "+")
        self.assertEqual(board.getMark("B1"), ".")

        self.gameController.addShip("B1B2B3", 1)
        self.assertEqual(board.getMark("B1"), "+")
        self.assertEqual(board.getMark("B2"), "+")
        self.assertEqual(board.getMark("B3"), "+")

        self.gameController.addShip("A2A3A4", 1)
        self.assertEqual(board.getMark("A1"), ".")
        self.assertEqual(board.getMark("A2"), "+")
        self.assertEqual(board.getMark("A3"), "+")
        self.assertEqual(board.getMark("A4"), "+")

        self.gameController.addShip("B3B4B5", 1)
        self.assertEqual(board.getMark("B1"), ".")
        self.assertEqual(board.getMark("B2"), ".")
        self.assertEqual(board.getMark("B3"), "+")
        self.assertEqual(board.getMark("B4"), "+")
        self.assertEqual(board.getMark("B5"), "+")

    def testCoordinateValidation(self):
        Validator.validateCoordinate("A1")
        Validator.validateCoordinate("B5")
        with self.assertRaises(CoordinateInvalid):
            Validator.validateCoordinate("a0")
        with self.assertRaises(CoordinateInvalid):
            Validator.validateCoordinate("f6")
        with self.assertRaises(CoordinateInvalid):
            Validator.validateCoordinate("123")
        with self.assertRaises(CoordinateInvalid):
            Validator.validateCoordinate("r4")

    def testShipValidatoin(self):
        Validator.validateShip("A1", "A2", "A3")
        Validator.validateShip("B0", "B1", "B2")
        Validator.validateShip("A1", "B1", "C1")
        Validator.validateShip("D2", "E2", "F2")

        with self.assertRaises(CoordinateInvalid):
            Validator.validateShip("D1", "E2", "F2")
        with self.assertRaises(CoordinateInvalid):
            Validator.validateShip("A1", "A5", "A3")
        with self.assertRaises(CoordinateInvalid):
            Validator.validateShip("D1", "D2", "F2")
        with self.assertRaises(CoordinateInvalid):
            Validator.validateShip("A1", "B2", "C1")
import time

square_width = 10 # pixels
grid_width = 51
pixels_wide = square_width * grid_width
ms_per_block = 2 # screen refreshes per move
score_font_size = 14

if __name__ == '__main__':
	pygame.init()
	size = (pixels_wide, int(pixels_wide*1.08) )# + score_font_size + 14)
	screen = pygame.display.set_mode(size)

	model = GameModel(grid_width)
	view = GameView(model, screen, square_width)
	controller = GameController(model)

	running = True
	count = 0
	while running:
		view.draw()
		for event in pygame.event.get():
			# if event.type == pygame.QUIT:
			# 	running = False
			running = controller.handle_event(event)
		count += 1
		if count == ms_per_block:
			model.update_snake()
			model.check_collision()
			count = 0
Exemple #20
0
class AppInterface:
    def __init__(self, max_turn: int):
        self.max_turn = max_turn
        self.status = Status.MENU
        self.game_controller = GameController(max_turn)
        self.score_controller = ScoreController()

    def handle_message(self, message: str, user_id: str):
        if self.status is Status.MENU:
            yield from self.menu_handle_message(message, user_id)
        elif self.status is Status.GAME:
            yield from self.game_handle_message(message, user_id)
        elif self.status is Status.SCORE:
            yield from self.score_handle_message(message, user_id)
        else:
            raise Exception(f"unsupported Status {self.status}")

    # --- message handler for MENU mode ---
    def menu_handle_message(self, message: str, user_id: str):
        if message in ("遊ぶ", "ハードモード"):
            if message == "ハードモード":
                self.game_controller.cpu_strength = CPUStrength.HARD
            yield from self.game_controller.start_game()
            self.status = Status.GAME
        elif message == "ルール":
            yield from self.show_rule()
        elif message == "スコア":
            yield from self.show_score(user_id)
        elif message == "スコアを消す":
            yield from self.score_controller.ask_clear_score()
            self.status = Status.SCORE
        else:
            yield from self.show_commands()

    @staticmethod
    def show_rule():
        rule_text = ("〜 ルール説明 〜\n"
                     "シングルポーカーは、あなたと CPU で一枚の手札の強さを競うトランプゲームです。"
                     "最初の山札はA,2,3,4,5,6,7,8,9,10,J,Q,Kの13枚です。"
                     "次の手順でゲームが進行します。\n\n"
                     "1) あなたと CPU は山札からそれぞれ一枚引く。\n\n"
                     "2) CPU は手札を捨てるかどうか選択し、捨てる場合は山札から一枚引く。"
                     "捨てたカードは公開される。\n\n"
                     "3) あなたは手札を捨てるかどうか選択し、捨てる場合は山札から一枚引く。"
                     "捨てたカードは公開される。\n\n"
                     "4) 2),3) をあと4回繰り返す。\n\n"
                     "5) 最終的に残った手札の強さが強いほうが勝ち。強さは次の通り:\n"
                     "2<3<4<5<6<7<8<9<10<J<Q<K\n"
                     "AはJ,Q,Kには勝ち、それ以外には負ける。")
        yield rule_text

    @staticmethod
    def show_score(user_id: str):
        yield from ScoreController.show_score(user_id)

    @staticmethod
    def show_commands():
        yield "以下のいずれかの言葉を送信してください。"
        yield "「遊ぶ」:ゲームを開始します。"
        yield "「ルール」:ルールを表示します。"
        yield "「スコア」:スコアを表示します。"
        yield "「スコアを消す」:スコアを消去します。"

    # --- message handler for GAME mode ---
    def game_handle_message(self, message: str, user_id: str):
        yield from self.game_controller.handle_message(message, user_id)
        if not self.game_controller.is_active:
            self.status = Status.MENU
            self.game_controller.__init__(self.max_turn)

    # --- message handler for SCORE mode ---
    def score_handle_message(self, message: str, user_id: str):
        yield from self.score_controller.handle_message(message, user_id)
        if not self.score_controller.is_asking_clear_score:
            self.status = Status.MENU
Exemple #21
0
 def __init__(self, max_turn: int):
     self.max_turn = max_turn
     self.status = Status.MENU
     self.game_controller = GameController(max_turn)
     self.score_controller = ScoreController()
Exemple #22
0
import pygame as pg

from controller import GameController

pg.mixer.pre_init(22100, -16, 2, 64)
pg.init()

s = pg.mixer.Sound('./sounds/forbidden-sournd.wav')
s.set_volume(0.1)

if __name__ == '__main__':
    game = GameController(sound_controller=s)
    game.main_loop()
Exemple #23
0
# Lets have some fun ;)
import pygame
from controller import GameController
from settings import GameSettings

pygame.init()
pygame.mixer.init()  # для звука
screen = GameSettings.my_screen
pygame.display.set_caption(GameSettings.GAME_CAPTION)
clock = pygame.time.Clock()

controller = GameController()

if __name__ == '__main__':
    while GameSettings.running:
        clock.tick(GameSettings.FPS)
        screen.fill(GameSettings.background_color)
        controller.run()
        pygame.display.flip()

    pygame.quit()
Exemple #24
0
 def setUp(self):
     self.shipRepository = ShipRepository()
     self.boardRepository = BoardRepository()
     self.gameController = GameController(self.boardRepository,
                                          self.shipRepository)
Exemple #25
0
 def __init__(self):
     self.create_widgets()
     self.setController(GameController())