示例#1
0
 def __init__(self, players, rounds):
     self.info_dic = {"bankrupt_turn": {}}
     self.players = players
     self.board = Board()
     self.chancePile = ChancePile()
     self.communityPile = CommunityPile()
     self.rounds = rounds
     self.bankrupt_count = 0
     self.cur_round = 0
示例#2
0
文件: main.py 项目: BUS410/checkers
    def __init__(self):
        pygame.init()

        self.window = pygame.display.set_mode(RESOLUTION)
        pygame.display.set_caption('ТНН шашки')
        self.clock = pygame.time.Clock()
        self.board = Board()
        self.checkers = GroupChecker()
        self.checkers.reset_pos_checkers()
        self.step = (255, 255, 255)
        self.widgets = [
            Widget(x=512,
                   y=0,
                   width=128,
                   height=96,
                   text='Reset',
                   font_size=30,
                   background_color=(255, 175, 88),
                   background_color_cover=(255, 195, 131),
                   background_color_click=(255, 132, 0),
                   font_color=(168, 88, 2),
                   onclick=self.reset),
            Widget(x=512,
                   y=512 - 96,
                   width=128,
                   height=96,
                   text='Exit',
                   font_size=30,
                   background_color=(255, 175, 88),
                   background_color_cover=(255, 195, 131),
                   background_color_click=(255, 132, 0),
                   font_color=(168, 88, 2),
                   onclick=self.exit),
        ]

        self.scores = [
            Widget(x=512,
                   width=128,
                   height=160,
                   y=96,
                   text='0',
                   font_size=50,
                   background_color=(238, 191, 140),
                   font_color=(168, 88, 2)),
            Widget(x=512,
                   width=128,
                   height=160,
                   y=256,
                   text='0',
                   font_size=50,
                   background_color=(238, 191, 140),
                   font_color=(168, 88, 2)),
        ]

        self.score_black = 0
        self.score_white = 0
示例#3
0
def drawCell(pos_x,pos_y):
    blockSize = Board.get_BlockSize(10)
    for x in range(width//blockSize):
        for y in range(height//blockSize):
            rect = pygame.Rect(x*blockSize, y*blockSize,
                               blockSize, blockSize)
            if x==pos_x-1 and y==pos_y-1:
                pygame.draw.rect(screen, kolor.convert('red'), rect, 0)
            if x*blockSize >=width or y*blockSize >=height:
                break
示例#4
0
文件: states.py 项目: hubrys/tytrys
 def _restart(self):
     """Restart game with default values"""
     self.board = Board(10, 22)
     self.next_piece = random_tetromino(0, 0)
     self.current_piece = random_tetromino(5, 20)
     self.drop_time = .5
     self.current_key = -1
     self.lines_to_next_level = 15
     self.level = 1
     self.score = 0
     self.view_modified = True
示例#5
0
文件: states.py 项目: hubrys/tytrys
    def __init__(self, window):
        super(GameState, self).__init__(window)
        # These lines are so that I don't have to stare at warnings
        # restart sets these to the right values
        self.board = Board(10, 22)
        self.next_piece = random_tetromino(0, 0)
        self.current_piece = random_tetromino(5, 20)
        self.drop_time = .5
        self.current_key = -1
        self.lines_to_next_level = 15
        self.level = 1
        self.score = 0
        self.view_modified = True

        self._restart()
        self.board_window = window.derwin(
            self.board.height, self.board.width + 2, 0, 0)
        self.info_window = window.derwin(
            self.board.height, 8, 0, self.board.width + 2)
示例#6
0
def move():
    global PREV_DATA_BY_GAME_ID
    print("\nPINGED\n  ********************")
    data = request.get_json(force=True)  # dict

    snake_dict = create_snake_dict(data['snakes'])
    board = Board(data['height'], data['width'], snake_dict, data['food']['data'])

    prev_food_list = PREV_DATA_BY_GAME_ID[data['id']]['prev_food_list']
    # insert info about which snakes ate last turn into data object
    if prev_food_list is not None:
        data['ate_last_turn'] = find_snakes_that_just_ate(data, prev_food_list, board)

    PREV_DATA_BY_GAME_ID[data['id']]['prev_food_list'] = convert_to_coords_list(data['food']['data'])

    move = pick_move(data, board, snake_dict)

    response = {
        'move': move,
        'taunt': 'Squaack'
    }
    return json.dumps(response)
示例#7
0
def move():
    global PREV_DATA_BY_GAME_ID
    print("\nPINGED\n  ********************")
    start = time()
    data = request.get_json(force=True)  # dict
    snake_dict = create_snake_dict(data['snakes'])
    board = Board(data['height'], data['width'], snake_dict, data['food']['data'], data['you']['id'])

    try:
        prev_food_list = PREV_DATA_BY_GAME_ID[data['id']]['prev_food_list']
    except KeyError:  # bit of a hack, but lets us restart the game server and resume the same game
        # without issues. Also good if we ever crash mid game
        print("Failed to retrieve prev turn data")
        prev_food_list = None

    # insert info about which snakes ate last turn into data object
    if prev_food_list is not None:
        data['ate_last_turn'] = find_snakes_that_just_ate(data, prev_food_list, board)

    try:
        PREV_DATA_BY_GAME_ID[data['id']]['prev_food_list'] = convert_to_coords_list(data['food']['data'])
    except KeyError:
        print("Failed to update prev food list for next turn")
        pass

    end = time()
    print("Took", (end - start), "to build the board and setup game data")

    move_alone = time()
    move = pick_move(data, board, snake_dict)
    print("Computing the move took", (move_alone - start), "time")
    end = time()
    print("Took", (end - start), "to compute move", move)

    response = {
        'move': move,
        'taunt': "ITS NOT A BUBBLE. WE WON'T CRASH"
    }
    return json.dumps(response)
示例#8
0
class Game:
    def __init__(self, players, rounds):
        self.info_dic = {"bankrupt_turn": {}}
        self.players = players
        self.board = Board()
        self.chancePile = ChancePile()
        self.communityPile = CommunityPile()
        self.rounds = rounds
        self.bankrupt_count = 0
        self.cur_round = 0

    def run(self):
        # Play the game for a given amount of rounds
        end = False
        for i in range(0, self.rounds):
            # dev_print("round", i)
            self.cur_round = i
            if util.verbose:
                log.write("round {0}:\n".format(i))
            end = self.round()
            if util.verbose:
                log.write("\n")
            if end:
                break
            # for player in self.players:
            # 	dev_print("player {0}: cash {1}, property {2}".format(player.num, player.cash, player.total_property()))
        if not end:
            self.info_dic["end"] = -1

        return self.info_dic

    def round(self):
        # Each round, every player should get its turn
        for player in self.players:
            if not player.is_bankrupt():
                self.turn(player)
                if player.is_bankrupt():
                    player.bankrupt()
                    self.info_dic["bankrupt_turn"][player.num] = self.cur_round
                    if util.verbose:
                        log.write(
                            "player {} has bankrupted, return all properties to the bank.\n"
                            .format(player.num))
                    self.bankrupt_count += 1
            if len(self.players) - self.bankrupt_count <= 1:
                for i in self.players:
                    if not i.is_bankrupt():
                        if util.verbose:
                            log.write("player {} wins\n".format(i.num))
                        self.info_dic["bankrupt_turn"][i.num] = -1
                        self.info_dic["winner"] = i.num
                        self.info_dic["end"] = self.cur_round
                return True
        if util.verbose:
            log.write("\n")
        for player in self.players:
            if util.verbose:
                log.write("player {} has {} cash.\n".format(
                    player.num, player.cash))
        if util.verbose:
            log.write("\n")
        return False

    def turn(self, player):
        # Get number of eyes on dice
        dice1, dice2 = diceThrow()
        if util.verbose:
            log.write("player {0} rolls two dices, {1} and {2}.\n".format(
                player.num, dice1, dice2))
        # Move the player to new position, goingToJail True is 3 doubles thrown
        player.move(self.board, dice1, dice2)

        # Get tile type
        tileType = self.board.getTileType(player.position)

        # Set to go to jail if on 'Go To Jail' tile
        if tileType == "gotojail":
            player.go_to_jail()

        # Do chance card if player has landed on a chance tile
        elif player.position in Board.TILES_CHANCE:
            player.doChanceCard(self.chancePile.pullCard(), self.board)

        # Do commmunity card if player has landed on a community chest tile
        elif player.position in Board.TILES_COMMUNITY:
            player.doCommunityCard(self.communityPile.pullCard(), self.board)

        elif Board.TILE_BUILDING[player.position] is not None:
            building = Board.TILE_BUILDING[player.position]
            if building.owner is None or building.owner.num == player.num:
                player.buy_building(Board.TILE_BUILDING[player.position])
            elif building.owner is not None and building.owner != player.num:
                fined = int(building.cur_price * 0.2)
                player.fine_money(fined, other=building.owner)

        # equivalent to trading
        for building_to_sell in player.building_to_sell_list:
            for other_player in self.players:
                if not other_player.is_bankrupt():
                    boundary = other_player.choose_boundary(
                        other_player.strategy, other_player.strategy_para)
                    if other_player != player and other_player.cash - building_to_sell.cur_price >= boundary:
                        other_player.cash -= building_to_sell.cur_price
                        building_to_sell.set_owner(other_player)
                        other_player.building.append(building_to_sell)
                        player.cash += int(building_to_sell.cur_price * 0.1)
                        if util.verbose:
                            log.write(
                                "player {0} successfully sell land {1} to player {2}, get the remaining {3}, player {0} currently has {4}, player {2} has {5}.\n"
                                .format(player.num, building_to_sell.name,
                                        other_player.num,
                                        building_to_sell.cur_price * 0.1,
                                        player.cash, other_player.cash))
                        break
        player.building_to_sell_list = []

        # Log the fact that a player has landed on a tile, after all movements
        self.board.hit(player.position)

        # Go again if not on jail and has thrown double
        if tileType != "jail" and dice1 == dice2:
            self.turn(player)

    def plot_para(self):
        return self.info_dic['end'], self.players[0].income, self.players[
            0].tax, self.players[0].start_capital
示例#9
0
"""
Basic pygame interface for minesweeper

- Written by SC 15/07/19
- edited by jmc 25/07/19
"""

import pygame
from objects import Board

# initialise board size and number of bombs
board = Board(10, 25)
bombs = board.bombs()
size = board.size()  # for now we just stick to 10

pygame.init()

# pygame text size
fontsize = 3*size
font = pygame.font.Font('freesansbold.ttf', fontsize)

# define colours
green = (0, 135, 56)
blue = (0, 0, 255)
red = (128, 13, 0)
turquoise = 12, 179, 151
black = (0, 0, 0)
white = (255, 255, 255)
grey = (140, 140, 140)
lightgrey = (207, 207, 207)
示例#10
0
文件: states.py 项目: hubrys/tytrys
class GameState(TytrysState):
    """Game Logic

    """

    def __init__(self, window):
        super(GameState, self).__init__(window)
        # These lines are so that I don't have to stare at warnings
        # restart sets these to the right values
        self.board = Board(10, 22)
        self.next_piece = random_tetromino(0, 0)
        self.current_piece = random_tetromino(5, 20)
        self.drop_time = .5
        self.current_key = -1
        self.lines_to_next_level = 15
        self.level = 1
        self.score = 0
        self.view_modified = True

        self._restart()
        self.board_window = window.derwin(
            self.board.height, self.board.width + 2, 0, 0)
        self.info_window = window.derwin(
            self.board.height, 8, 0, self.board.width + 2)

    def _restart(self):
        """Restart game with default values"""
        self.board = Board(10, 22)
        self.next_piece = random_tetromino(0, 0)
        self.current_piece = random_tetromino(5, 20)
        self.drop_time = .5
        self.current_key = -1
        self.lines_to_next_level = 15
        self.level = 1
        self.score = 0
        self.view_modified = True

    def process_messages(self):
        while not self.messages.empty():
            if self.messages.get() == "restart":
                self._restart()
                self.window.clear()

    def handle_user_input(self):
        direction = None
        key_pressed = self.window.getch()
        if key_pressed in (ord('j'), ord('J'), curses.KEY_LEFT):
            direction = Direction.Left
        elif key_pressed in (ord('l'), ord('L'), curses.KEY_RIGHT):
            direction = Direction.Right
        elif key_pressed in (ord('i'), ord('I'), curses.KEY_UP):
            direction = Direction.CCW
        elif key_pressed in (ord('k'), ord('K'), curses.KEY_DOWN):
            direction = Direction.CW
        elif key_pressed in (ord('q'), ord('Q')):
            self.view_modified = True
            game.switch_to_state("paused")
        elif key_pressed == ord(' '):
            self.drop_current_piece()

        if direction is not None:
            if direction == Direction.CCW or direction == Direction.CW:
                if self.board.are_valid_coordinates(
                        self.current_piece.rotate_result(direction)):
                    renderer.clear_tetromino(self.current_piece,
                                             self.board_window)
                    self.view_modified = True
                    self.current_piece.rotate(direction)
            else:
                if self.board.are_valid_coordinates(
                        self.current_piece.move_result(direction)):
                    renderer.clear_tetromino(self.current_piece,
                                             self.board_window)
                    self.view_modified = True
                    self.current_piece.move(direction)

    def drop_current_piece(self):
        self.view_modified = True
        renderer.clear_tetromino(self.current_piece, self.board_window)
        while self.board.are_valid_coordinates(
                self.current_piece.move_result(Direction.Down)):
            self.current_piece.move(Direction.Down)

    def draw(self):
        if self.view_modified:
            self.view_modified = False
            renderer.draw_board(self.board, self.board_window)
            renderer.draw_tetromino(self.current_piece, self.board_window)
            self.board_window.refresh()
            self._draw_info()

    def _draw_info(self):
        self.info_window.border()
        self.info_window.addstr(1, 1, "Tytrys")
        self.info_window.hline(2, 1, ord('_'), 6)
        self.info_window.addstr(4, 1, "Next:")
        self.next_piece.set_location(3, 14) # little hacky
        renderer.draw_tetromino(self.next_piece, self.info_window)
        self.info_window.addstr(10, 1, "Score:")
        self.info_window.addstr(11, 1, str(self.score))
        self.info_window.addstr(14, 1, "Level:")
        self.info_window.addstr(15, 3, str(self.level))
        self.info_window.addstr(18, 1, "Lines:")
        self.info_window.addstr(19, 1, str(self.lines_to_next_level) + "  ")
        self.info_window.refresh()

    def update(self, delta):
        self.elapsed_time += delta
        self.handle_user_input()

        if self.elapsed_time >= self.drop_time:
            if self.board.are_valid_coordinates(
                    self.current_piece.move_result(Direction.Down)):
                renderer.clear_tetromino(self.current_piece, self.board_window)
                self.current_piece.move(Direction.Down)
            else:
                renderer.clear_tetromino(self.next_piece, self.info_window)
                try:
                    self.board.lock_tetromino(self.current_piece)
                    self.current_piece = self.next_piece
                    self.current_piece.set_location(5, 20)
                    self.next_piece = random_tetromino(0, 0)

                    rows_removed = self.board.clear_full_rows()
                    if rows_removed:
                        self.lines_to_next_level -= rows_removed
                        self.score += sum(range(rows_removed + 1)) * 100
                        if self.lines_to_next_level <= 0:
                            self.score += 1000 * self.level
                            self.lines_to_next_level = 15
                            self.level += 1
                            self.drop_time *= .75
                except RuntimeError:
                    game.add_state_and_switch("game over",
                                              GameOverState(self.window,
                                                            self.score))

            self.view_modified = True
            self.elapsed_time -= self.drop_time
示例#11
0
文件: main.py 项目: konko2/snake
from random import choice
from tkinter import Tk, TclError

from constraints import Direction
from objects import Snake, Board
from welcome_window import create_preference_window

try:
    speed, length, height = create_preference_window()

    tk = Tk()
    tk.title("snake")
    tk.resizable(False, False)

    board = Board(tk, length, height, bg='white')
    board.pack()

    snake = Snake(board, board.find_center_field())
    egg = None

    def finish_step():
        tk.quit()
        snake.move()

    while True:
        tk.after(speed, finish_step)

        if egg and snake.is_eat(egg):
            snake.is_growing = True

            board.delete(egg)
def game():
    #make player instances,
    player1 = Player(Board(), Board(True), 'Player1')
    CPU = Player(Board(), Board(True), 'CPU')

    available_ships = ['sub', 'aircraft', 'patrol', 'patrol']

    print 'Welcome to Battleship!'
    print 'To place your battleship enter a phrase such as "Place sub horizontal at A2" or "Place aircraft, vert, at (C,4)"'
    print ''
    print ''

    #Player 1 places his ships here
    while available_ships:
        player1.defense_board.print_board()
        print '{}, your board is pictured above for reference.'.format(player1.name)
        print 'You have the following ships left for placement: {}'.format(available_ships)
        defense_request = raw_input('Type your placement phrase here: ')

        try:
            parsed_request = parse(defense_request)
        except ValueError as e:
            print e
            continue

        #this should probably be an exception
        if parsed_request[0] not in available_ships:
            print "You've already placed your {}, as a reminder, you have the following ships left for placement: {}".format(parsed_request[0], available_ships)
            continue
        try:
            player1.defense_board.place_boat(*parsed_request)
            available_ships.remove(parsed_request[0])
        except ValueError as e:
            print e

    #AI places his ships here, core logic executed in AI library.
    ai.boat_placement(CPU.defense_board)

    #Flip a coin to determine who goes first.
    print 'Battleships placed for {} and computer.'.format(player1.name)

    #using turn to alternate turns
    turn = True
    players = (player1, CPU)
    while not any([player1.has_win, CPU.has_win]):
        if turn:
            player = players[0]
            print 'Here\'s your current board used for tracking your attacks:'
            print ''
            player.attack_board.print_board()
            coordinate = raw_input('Player {} Enter your coordinate: '.format(player.name))
            try:
                parsed_coord = coordinate_parse(coordinate)
                if players[1].defense_board[parsed_coord][0]:
                    print 'Hit!'
                    player.attack_board[parsed_coord][0] = 'x'
                    
                else:
                    print 'Miss!'
                    player


            except ValueError as e:
                print e
                continue
        else:
            player = players[1]


        turn = not turn
示例#13
0
    def __init__(self):
        Board.__init__(self)

        for i in range(1, size):
            self.add_bee()
示例#14
0
    
def drawCell(pos_x,pos_y):
    blockSize = Board.get_BlockSize(10)
    for x in range(width//blockSize):
        for y in range(height//blockSize):
            rect = pygame.Rect(x*blockSize, y*blockSize,
                               blockSize, blockSize)
            if x==pos_x-1 and y==pos_y-1:
                pygame.draw.rect(screen, kolor.convert('red'), rect, 0)
            if x*blockSize >=width or y*blockSize >=height:
                break


board=create_board(10,10)
board=create_cell(3,4)
Board=Board(width,height)
screen.fill(kolor.convert('white'))
Board.drawGrid(10)

counter=0
while run:
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run =False
    drawCell(5,5)
    sleep(2)
    drawCell(1,1)

    text("Klaudiusz Hynek",32,kolor.full_random_color())
    pygame.display.update()