예제 #1
0
def test():
    game.new_game()
    player = 1
    print(game.board)
    while abs(player) != 10 and not game.full_board():
        index = epsilon_greedy(0.0, player)
        player, _ = game.step(index, player)
        print(game.board)
예제 #2
0
def start(event):
    global root1, txt, name, color
    name = txt.get()
    root1.destroy()
    game.main(n, color)
    button = tk.Button(text='Вернуться в меню',
                       width=15,
                       height=2,
                       font='arial 14')
    button.place(x=820, y=10)
    button.bind('<Button-1>', clickedmenu)
    game.new_game()
예제 #3
0
def main(playmode):
    view = GameView()
    board, score = new_game(4)
    view.draw(board, score)
    clock = pygame.time.Clock()

    while True:
        clock.tick(20)  # limit fps

        redraw = False

        # get move from player
        for event in pygame.event.get():
            if event.type == QUIT:
                print("Exiting...")
                return

            if event.type == KEYDOWN and playmode:
                if event.key == K_LEFT:
                    score += make_move(board, 'left')
                    redraw = True
                if event.key == K_RIGHT:
                    score += make_move(board, 'right')
                    redraw = True
                if event.key == K_UP:
                    score += make_move(board, 'up')
                    redraw = True
                if event.key == K_DOWN:
                    score += make_move(board, 'down')
                    redraw = True

        if redraw:
            view.draw(board, score)

        # get move from ai
        if not playmode:
            best_move = game_ai.expectimax_move((board, score), 'gradient')
            # make the move and redraw
            score += make_move(board, best_move)
            view.draw(board, score)
            pygame.time.wait(0)

        # check if it is game over
        if len(possible_moves(board)) == 0:
            print("Game over! Score: " + str(score) + " Max square: " +
                  str(max_square(board)))
            print("Starting new game...\n")

            pygame.time.wait(3000)
            pygame.event.clear()

            board, score = new_game(4)
            view.draw(board, score)
예제 #4
0
def win_menu():
    """
    Win menu after using chest

    Deletes save file if there is data
    """
    if os.path.isfile(SAVE_PATH) and os.stat(SAVE_PATH).st_size > 0:
        open(SAVE_PATH, 'w').close()

    str = "Congratulations you found the treasure"

    new_button = TextButton("New Game", (BUTTON_WIDTH, BUTTON_HEIGHT),
                            (CAMERA_WIDTH // 2, CAMERA_HEIGHT // 4 + 250), RED)

    exit_button = TextButton(
        "Exit", (BUTTON_WIDTH, BUTTON_HEIGHT),
        (CAMERA_WIDTH // 2, new_button.rect.midbottom[1] + 100), GREY)

    while True:
        config.SURFACE_MAIN.blit(config.SPRITE.unfocused_window, (0, 0))

        mouse_x, mouse_y = pygame.mouse.get_pos()

        new_button.mouse_over()
        exit_button.mouse_over()

        game_text.draw_text(config.SURFACE_MAIN,
                            (CAMERA_WIDTH // 2, CAMERA_HEIGHT // 4 + 100),
                            WHITE,
                            str,
                            center=True)

        new_button.draw()

        exit_button.draw()

        g = game.Game()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if new_button.rect.collidepoint((mouse_x, mouse_y)):
                        game.new_game()
                        game.populate_map()
                        g.run()
                    elif exit_button.rect.collidepoint((mouse_x, mouse_y)):
                        pygame.quit()
                        sys.exit()

        pygame.display.update()
예제 #5
0
def main(playmode):
    view = GameView()    
    board, score = new_game(4)
    view.draw(board,score)
    clock = pygame.time.Clock()

    while True:
        clock.tick(20)  # limit fps

        redraw = False

        # get move from player
        for event in pygame.event.get():
            if event.type == QUIT:
                print("Exiting...")
                return

            if event.type == KEYDOWN and playmode:
                if event.key == K_LEFT:
                    score += make_move(board, 'left')
                    redraw = True
                if event.key == K_RIGHT:
                    score += make_move(board, 'right')
                    redraw = True
                if event.key == K_UP:
                    score += make_move(board, 'up')
                    redraw = True
                if event.key == K_DOWN:
                    score += make_move(board, 'down')
                    redraw = True
    
        if redraw:            
            view.draw(board, score)

        # get move from ai
        if not playmode:
            best_move = game_ai.expectimax_move((board, score), 'gradient')
            # make the move and redraw
            score += make_move(board, best_move)
            view.draw(board, score)
            pygame.time.wait(0)

        # check if it is game over
        if len(possible_moves(board)) == 0:
            print("Game over! Score: " + str(score) + " Max square: " + str(max_square(board)))
            print("Starting new game...\n")

            pygame.time.wait(3000)
            pygame.event.clear()

            board, score = new_game(4)
            view.draw(board, score)
예제 #6
0
def play_with():
    game.new_game()
    player = 1
    print(game.board)
    while abs(player) != 10 and not game.full_board():
        index = epsilon_greedy(0.0, player)
        player, _ = game.step(index, player)
        print(game.board)
        if not (abs(player) != 10 and not game.full_board()):
            continue
        my_index = -1 + int(input("index: "))
        player, _ = game.step(my_index, player)
        print(game.board)
예제 #7
0
def one_episode(epsilon, player):
    game.new_game()
    global loss_for_one_episode, loss_for_sever_episodes
    loss_for_one_episode = 0
    if player == 1:
        while abs(player) != 10 and not game.full_board():
            player = deep_q_learning_step(epsilon, player)
    else:
        index = epsilon_greedy(0.0, 1)
        player, _ = game.step(index, player)
        while abs(player) != 10 and not game.full_board():
            player = deep_q_learning_step(epsilon, player)
    print(loss_for_one_episode)
    loss_for_sever_episodes += loss_for_one_episode
예제 #8
0
def main():
    logging.basicConfig(filename='log.txt',level=logging.DEBUG,filemode='w')

    logging.debug('start of main')

    #initialize main console
    font_file = 'data/fonts/terminal10x10_gs_tc.png'
    libtcod.console_set_custom_font(font_file, libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
    libtcod.console_init_root(SCREEN_W,SCREEN_H,'GolemRL')
    libtcod.sys_set_fps(LIMIT_FPS)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_ANY,key,mouse)
        choice = main_menu()
        if choice == 0:
            seed = random.randrange(10000)
            print 'Seed %i'%seed
            logging.info('Starting new game with seed %i' % seed)
            game = new_game()#seed)
            game.play()
        elif choice == 1:
            game = load_game()
            game.play()
        elif choice == 2:
            break

    logging.debug('end of main')
    return 0
예제 #9
0
파일: server.py 프로젝트: evhub/spyfall-irc
 def play(self):
   game = new_game(self.locations, len(self.players))
   for p, m in zip(players, game.messages()):
     self.irc.psend(p, m)
   self.irc.send("Roles have been private messaged to each player!")
   self.irc.send(show_locations(self.locations))
   self.endtime = time() + self.timelimit
예제 #10
0
def handle_main_menu():
    img = tcod.image_load(b"menu_background.png")

    while not tcod.console_is_window_closed():
        # show the background image, at twice the regular console resolution
        tcod.image_blit_2x(img, 0, 0, 0)

        # show the game's title, and some credits!
        tcod.console_set_default_foreground(0, tcod.white)
        tcod.console_print_ex(
            0, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 4, tcod.BKGND_NONE, tcod.CENTER, bytes(GAME_NAME, "utf-8")
        )
        tcod.console_print_ex(
            0,
            SCREEN_WIDTH // 2,
            SCREEN_HEIGHT - 2,
            tcod.BKGND_NONE,
            tcod.CENTER,
            b"By Matthew Pfeiffer ([email protected])",
        )

        # show options and wait for the player's choice
        choice = menu("", ["Play a new game", "Continue last game", "Quit"], 24)

        if choice == 0:  # new game
            game.new_game()
            game.run()
        elif choice == 1:  # load last game
            try:
                save.load_game()
            except:
                msgbox("\n No saved game to load.\n", 24)
                continue
            game.run()
        elif choice == 2 or choice == "escape":  # quit
            break
예제 #11
0
파일: wsgi.py 프로젝트: subeans/FINAL
def application(environ, start_response):

	error = False
	
	if environ['REQUEST_METHOD'] != 'POST':
		response = {'code': 'error', 'msg': 'wrong HTTP method'}
		error = True

	if not error:
		try:
			path = environ['PATH_INFO'].split('/')
			if len(path) == 2:
				method = path[1]
			else:
				response = {'code': 'error', 'msg': 'wrong API path'}
				error = True
		except:
			response = {'code': 'error', 'msg': 'wrong API path'}
			error = True

	try:
		request_body_size = int(environ.get('CONTENT_LENGTH', '0'))
	except ValueError:
		request_body_size = 0

	request_body = environ['wsgi.input'].read(request_body_size)
	d = parse_qs(request_body)

	if not error:
		if method == 'new':
			response = new_game(d)
		elif method == 'guess':
			response = updown(d)
		else:
			response = {'code': 'error', 'msg': 'non-existent API method'}

	status = '200 OK'
	response_body = json.dumps(response)

	response_headers = [
		('Content-Type', 'application/json'),
		('Content-Length', str(len(response_body)))
	]

	start_response(status, response_headers)

	return [response_body]
예제 #12
0
def application(environ, start_response):
    error = False

    if environ['REQUEST_METHOD'] != 'POST':         #만약 포스트 요청이 아닐경우
        response = {'code': 'error', 'msg': 'wrong HTTP method'}    #에러메세지를 담은 dictionary
        error = True

    if not error:
        try:            #environ['PATH_INFO']로부터 요청된 기능(API) 파악
            path = environ['PATH_INFO'].split('/')
            if len(path) == 2:
                method = path[1]
            else:
                response = {'code': 'error', 'msg': 'wrong API path'}
                error = True
        except:
            response = {'code': 'error', 'msg': 'wrong API path'}
            error = True

    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', '0'))
    except ValueError:
        request_body_size = 0

    request_body = environ['wsgi.input'].read(request_body_size)
    d = parse_qs(request_body)

    if not error:       #요청된 API에 따라 적절한 게임 드라이버 함수를 호출한다.
        if method == 'new':
            response = new_game(d)
        elif method == 'guess':
            response = guess(d)
        else:
            response = {'code': 'error', 'msg': 'non-existent API method'}

    status = '200 OK'
    response_body = json.dumps(response)        #json 형태를 가지는 HTTP response를 출력한다.

    response_headers = [
        ('Content-Type', 'application/json'),
        ('Content-Length', str(len(response_body)))
    ]

    start_response(status, response_headers)

    return [response_body]
예제 #13
0
def ai_mode(number_of_games=1):
    """ Just let the AI play a number of times
        without showing the UI.
    """

    scores = []

    for i in range(number_of_games):
        board, score = new_game(4)
        possible = possible_moves(board)

        while possible:
            move = game_ai.expectimax_move((board, score), 'gradient')
            score += make_move(board, move)
            possible = possible_moves(board)

        scores.append(score)
        print("Game {0}: Score = {1}".format(i + 1, score))

    print()
    print("Mean score = " + str(sum(scores) / float(len(scores))))
예제 #14
0
def ai_mode(number_of_games=1):
    """ Just let the AI play a number of times
        without showing the UI.
    """

    scores = []

    for i in range(number_of_games):
        board, score = new_game(4)
        possible = possible_moves(board)

        while possible:
            move = game_ai.expectimax_move((board, score), 'gradient')
            score += make_move(board, move)
            possible = possible_moves(board)

        scores.append(score)
        print("Game {0}: Score = {1}".format(i+1, score))

    print()
    print("Mean score = " + str(sum(scores)/float(len(scores))))
예제 #15
0
def main():
    game = new_game()
    game.play()
예제 #16
0
 def new_game(self, *args):
     cards = game.new_game()
     self.clear_canvas()
     self.display_cards(cards, 0, True, False)
예제 #17
0
def main_menu(mygame, level, graphics):
    f = data.load("menu.png")
    graph.load_spriteset(f, graphics)
    
    i=0
    menu_quit = 2
    ticks = pygame.time.get_ticks()
    t = 0
    menu_selection = 0
    key_pressed = 1
    next = "play"
    while menu_quit != 1:
        pygame.event.pump()
        keys = pygame.key.get_pressed()
        if(keys[pygame.K_ESCAPE] == 1 and key_pressed == 0):
            menu_quit = 1
            next = "play"
        if((keys[pygame.K_LEFT] or keys[pygame.K_UP]) and key_pressed == 0):
            menu_selection = (menu_selection+2)%3
            key_pressed = 1
            mygame.sound_11.play()
        if((keys[pygame.K_RIGHT] or keys[pygame.K_DOWN]) and key_pressed == 0):
            menu_selection = (menu_selection+1)%3
            key_pressed = 1
            mygame.sound_11.play()
        if( keys[pygame.K_LEFT] == 0 and keys[pygame.K_RIGHT] == 0 and keys[pygame.K_UP] == 0 and keys[pygame.K_DOWN] == 0 and keys[pygame.K_ESCAPE] == 0 and keys[pygame.K_RETURN] == 0 and keys[pygame.K_1] == 0 and keys[pygame.K_2] == 0 and keys[pygame.K_3] == 0 and keys[pygame.K_LCTRL] == 0):
            key_pressed = 0
        if((keys[pygame.K_RETURN] == 1 or keys[pygame.K_LCTRL] == 1 ) and key_pressed == 0):
            menu_quit = 1
            if menu_selection == 0:
                next = "play"
                mygame.sound_12.play()
            if menu_selection == 1:
                next = "edit"
            if menu_selection == 2:
                next = "quit"
        graph.draw_sprite_static_multi(256+0 + 5*(menu_selection==0), 120, 60, 5, 1, graphics)
        graph.draw_sprite_static_multi(256+16 + 5*(menu_selection==1), 120, 60+32, 5, 1, graphics)
        graph.draw_sprite_static_multi(256+32 + 5*(menu_selection==2), 120, 60+64, 5, 1, graphics)
        graph.draw_screen(graphics)
        pygame.time.wait(1)
        t = pygame.time.get_ticks() - ticks
        ticks = pygame.time.get_ticks()
        i += 1
        
    if next == "play" and mygame.ingame == 0:
        i = 0
        menu_quit = 2
        ticks = pygame.time.get_ticks()
        t = 0
        menu_selection = 0
        key_pressed = 1
        next = "menu"
        while menu_quit != 1:
            pygame.event.pump()
            keys = pygame.key.get_pressed()
            if(keys[pygame.K_ESCAPE] == 1 and key_pressed == 0):
                menu_quit = 1
                next = "menu"
            if((keys[pygame.K_LEFT] or keys[pygame.K_UP]) and key_pressed == 0):
                menu_selection = (menu_selection+1)%2
                key_pressed = 1
                mygame.sound_11.play()
            if((keys[pygame.K_RIGHT] or keys[pygame.K_DOWN]) and key_pressed == 0):
                menu_selection = (menu_selection+1)%2
                key_pressed = 1
                mygame.sound_11.play()
            if( keys[pygame.K_LEFT] == 0 and keys[pygame.K_RIGHT] == 0 and keys[pygame.K_UP] == 0 and keys[pygame.K_DOWN] == 0 and keys[pygame.K_ESCAPE] == 0 and keys[pygame.K_RETURN] == 0 and keys[pygame.K_1] == 0 and keys[pygame.K_2] == 0 and keys[pygame.K_3] == 0 and keys[pygame.K_LCTRL] == 0):
                key_pressed = 0
            if((keys[pygame.K_RETURN] == 1 or keys[pygame.K_LCTRL] == 1 ) and key_pressed == 0):
                menu_quit = 1
                if menu_selection == 0:
                    next = "play"
                    mygame.ingame = 1
                    # SQ - this game crashed if this option was selected with no existing save data..
                    #    So, I made continue_game return immediately if it checked and found no data
                    #    and if we get to the next line that is indeed the case. Instead of crashing,
                    #    we'll now just start a new game by copying the three lines for menu selection
                    #    1 below and pasting them here:
                    #game.continue_game(mygame, level)
                    if not game.continue_game(mygame, level):
                        next = "intro"
                        mygame.ingame = 1
                        game.new_game(mygame, level)
                if menu_selection == 1:
                    next = "intro"
                    mygame.ingame = 1
                    game.new_game(mygame, level)
            graph.draw_sprite_static_multi(256+48 + 3*(menu_selection==0), 136, 60+16, 3, 1, graphics)
            graph.draw_sprite_static_multi(256+64 + 3*(menu_selection==1), 136, 60+48, 3, 1, graphics)
            graph.draw_screen(graphics)
            pygame.time.wait(1)
            t = pygame.time.get_ticks() - ticks
            ticks = pygame.time.get_ticks()
            i += 1
    return next
예제 #18
0
    parser.add_argument("--comand", help="Что бы узнать правила игры введите --comand helpme")
    args = parser.parse_args()
    if args.comand == 'helpme':
        open_helper()
    elif args.comand == None:
        pass
    else:
        print('Неизвестная команда\n\n\n')


console_reader()


# ___ЗАПУСК ИГРЫ___

print('Добро пожаловать в игру \"Крести-нолики\"\n')
if check_saving() == 0:
    """
    Нет сохраненной игры
    """
    n, k, player, progress_field = new_game()
    current_field = build_field(n, k)
    print_field(current_field)
    play(player, progress_field, current_field)

else:
    """
    Есть сохраненная игра
    """
    loading()
예제 #19
0
파일: menu.py 프로젝트: r452031538/csci321
def main_menu(mygame, level, graphics):
    f = data.load("menu.png")
    graph.load_spriteset(f, graphics)

    i = 0
    menu_quit = 2
    ticks = pygame.time.get_ticks()
    t = 0
    menu_selection = 0
    key_pressed = 1
    next = "play"
    while menu_quit != 1:
        pygame.event.pump()
        keys = pygame.key.get_pressed()
        if (keys[pygame.K_ESCAPE] == 1 and key_pressed == 0):
            menu_quit = 1
            next = "play"
        if ((keys[pygame.K_LEFT] or keys[pygame.K_UP]) and key_pressed == 0):
            menu_selection = (menu_selection + 2) % 3
            key_pressed = 1
            mygame.sound_11.play()
        if ((keys[pygame.K_RIGHT] or keys[pygame.K_DOWN])
                and key_pressed == 0):
            menu_selection = (menu_selection + 1) % 3
            key_pressed = 1
            mygame.sound_11.play()
        if (keys[pygame.K_LEFT] == 0 and keys[pygame.K_RIGHT] == 0
                and keys[pygame.K_UP] == 0 and keys[pygame.K_DOWN] == 0
                and keys[pygame.K_ESCAPE] == 0 and keys[pygame.K_RETURN] == 0
                and keys[pygame.K_1] == 0 and keys[pygame.K_2] == 0
                and keys[pygame.K_3] == 0 and keys[pygame.K_SPACE] == 0):
            key_pressed = 0
        if ((keys[pygame.K_RETURN] == 1 or keys[pygame.K_SPACE] == 1)
                and key_pressed == 0):
            menu_quit = 1
            if menu_selection == 0:
                next = "play"
                mygame.sound_12.play()
            if menu_selection == 1:
                next = "edit"
            if menu_selection == 2:
                next = "quit"
        graph.draw_sprite_static_multi(256 + 0 + 5 * (menu_selection == 0),
                                       120, 60, 5, 1, graphics)
        graph.draw_sprite_static_multi(256 + 16 + 5 * (menu_selection == 1),
                                       120, 60 + 32, 5, 1, graphics)
        graph.draw_sprite_static_multi(256 + 32 + 5 * (menu_selection == 2),
                                       120, 60 + 64, 5, 1, graphics)
        graph.draw_screen(graphics)
        pygame.time.wait(1)
        t = pygame.time.get_ticks() - ticks
        ticks = pygame.time.get_ticks()
        i += 1

    if next == "play" and mygame.ingame == 0:
        i = 0
        menu_quit = 2
        ticks = pygame.time.get_ticks()
        t = 0
        menu_selection = 0
        key_pressed = 1
        next = "menu"
        while menu_quit != 1:
            pygame.event.pump()
            keys = pygame.key.get_pressed()
            if (keys[pygame.K_ESCAPE] == 1 and key_pressed == 0):
                menu_quit = 1
                next = "menu"
            if ((keys[pygame.K_LEFT] or keys[pygame.K_UP])
                    and key_pressed == 0):
                menu_selection = (menu_selection + 1) % 2
                key_pressed = 1
                mygame.sound_11.play()
            if ((keys[pygame.K_RIGHT] or keys[pygame.K_DOWN])
                    and key_pressed == 0):
                menu_selection = (menu_selection + 1) % 2
                key_pressed = 1
                mygame.sound_11.play()
            if (keys[pygame.K_LEFT] == 0 and keys[pygame.K_RIGHT] == 0
                    and keys[pygame.K_UP] == 0 and keys[pygame.K_DOWN] == 0
                    and keys[pygame.K_ESCAPE] == 0
                    and keys[pygame.K_RETURN] == 0 and keys[pygame.K_1] == 0
                    and keys[pygame.K_2] == 0 and keys[pygame.K_3] == 0
                    and keys[pygame.K_SPACE] == 0):
                key_pressed = 0
            if ((keys[pygame.K_RETURN] == 1 or keys[pygame.K_SPACE] == 1)
                    and key_pressed == 0):
                menu_quit = 1
                if menu_selection == 0:
                    next = "play"
                    mygame.ingame = 1
                    game.continue_game(mygame, level)
                if menu_selection == 1:
                    next = "intro"
                    mygame.ingame = 1
                    game.new_game(mygame, level)
            graph.draw_sprite_static_multi(
                256 + 48 + 3 * (menu_selection == 0), 136, 60 + 16, 3, 1,
                graphics)
            graph.draw_sprite_static_multi(
                256 + 64 + 3 * (menu_selection == 1), 136, 60 + 48, 3, 1,
                graphics)
            graph.draw_screen(graphics)
            pygame.time.wait(1)
            t = pygame.time.get_ticks() - ticks
            ticks = pygame.time.get_ticks()
            i += 1
    return next
예제 #20
0
import game


game = game.Game()
game.new_game()
예제 #21
0
 def __init__(self, deck=None):
     self.history = [new_game(deck=deck)]
     self.count = 0
     self.long_game = False
     self.run()
예제 #22
0
파일: jpm.py 프로젝트: esimonson/6.177
#!/usr/bin/env python-32

from constants import *
from imports import *
import game

if __name__ == "__main__":
	game.new_game()