예제 #1
0
파일: main.py 프로젝트: Lonsdaleiter/Chess
def update():
    global running
    global window
    global clock

    mouseup = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouseup = True
            mouse.down = True

        if not mouseup:
            mouse.down = False

        if event.type == pygame.MOUSEMOTION:
            mouse.x = pygame.mouse.get_pos()[0]
            mouse.y = pygame.mouse.get_pos()[1]

    clock.tick(60)

    drawer.draw(assets.background_image, 0, 0)
    keyboard.update()

    board.update()

    pygame.display.flip()

    if turnmanager.won:
        os.system("say 'Closing the window in 5 seconds'")
        time.sleep(5)
        exit(0)
예제 #2
0
    def simTree(self,board,play_turn,node,l,c_p):
        #每次决策树都是在剩余的子里选
        #记录每次选择出来的节点树
        # print(len(node),l)
        #树上找到的节点
        n=[]
        #模拟出来的节点
        sn=[]

        ns=list(node.keys())
        #当前剩余可走位置
        #提出已经有信息的节点
        availables=list(filter(lambda x: x not in node or node[x][0]==0,board.availables))
        # print(availables)
        # print(len(availables))
        for _ in range(1, len(board.availables) + 1):
            #因为围棋比较特殊,所有剩余位置均为子节点,
            #所以需要所有位置均有信息才可能进行uct
            #即经过模拟后
            if len(availables)==0:
                #获取当前出手玩家
                player=board.get_player(play_turn)
                #遍历剩余节点
                #如果是当前玩家取胜率最大
                if c_p==player:
                    #ubc1公式
                    bonus,move=max(
                        (self.eval(node[key]),key) for key in board.availables)
                    # print(c_p,player,"win",move)
                else:
                    bonus,move=min(
                        (self.eval(node[key]),key) for key in board.availables)
                    # print(c_p,player,"win",move)
                #记录选出来的模拟节点
                n.append(move)
                #消除记录里的点
                ns.remove(move)
                #更新棋盘
                board.update(player,move)
                #胜利
                win,winner = board.has_a_winner(board)
                if win:
                    return win,winner,n,sn
            else:
                #需要扩展的节点
                move=choice(availables)
                player=board.get_player(play_turn)
                board.update(player,move)
                #记录选出来的模拟节点
                n.append(move)
                #该节点无数据
                win,winner,sn=self.simulation(board,play_turn)
                return win,winner,n,sn
        return False,-1,n,sn
예제 #3
0
파일: UCT.py 프로젝트: ZooDoz/Python4NN
 def simulation(self, board, play_turn):
     for _ in range(1, len(board.availables) + 1):
         move = choice(board.availables)
         player = board.get_player(play_turn)
         board.update(player, move)
         #胜利
         win, winner = board.has_a_winner(board)
         if win:
             return win, winner
     #如果没有结果也算失败
     return False, -1
 def getAnswerPlay(self, board):
     answer = []
     turn = 0
     while True:
         turn += 1
         col = self.S1.think(board)
         answer.append(col)
         if board.update(self.S1.ME, col): break
         turn += 1
         col = self.S2.think(board)
         answer.append(col)
         if board.update(self.S2.ME, col): break
     return answer, turn
예제 #5
0
파일: UCT.py 프로젝트: ZooDoz/Python4NN
 def simTree(self, board, play_turn, node, l, c_p):
     #每次决策树都是在剩余的子里选
     #记录每次选择出来的节点树
     # print(len(node),l)
     n = []
     availables = list(filter(lambda x: x not in node, board.availables))
     for _ in range(1, len(board.availables) + 1):
         #因为围棋比较特殊,所有剩余位置均为子节点,
         #所以需要所有位置均有信息才可能进行uct
         #即经过模拟后
         #获取当前出手玩家
         player = board.get_player(play_turn)
         #当前剩余没有记录位置
         if len(availables) == 0:
             #遍历剩余节点
             #对剩余节点访问次数求和然后取对数
             #即当前节点访问次数 sum(剩余节点的访问次数)=当前节点的访问次数
             #因此total(v) = sum(total(v’),for v’ in childs(v))
             log_total = log(sum(node[m][0] for m in board.availables))
             #如果是当前玩家取胜率最大
             if c_p == player:
                 #ubc1公式
                 bonus, move = max(
                     (node[m][1] + sqrt(log_total / node[m][0]), m)
                     for m in board.availables)
                 # print(c_p,player,"win",move)
             else:
                 bonus, move = min(
                     (node[m][1] - sqrt(log_total / node[m][0]), m)
                     for m in board.availables)
                 # print(c_p,player,"win",move)
             #记录选出来的模拟节点
             n.append(move)
             #更新棋盘
             board.update(player, move)
             #胜利
             win, winner = board.has_a_winner(board)
             if win:
                 return win, winner, n
         else:
             # print(len(availables),len(board.availables))
             #需要扩展的节点
             move = choice(availables)
             #更新棋盘
             board.update(player, move)
             #记录选出来的模拟节点
             n.append(move)
             #该节点无数据,需要模拟
             win, winner = self.simulation(board, play_turn)
             return win, winner, n
     return False, -1, n
예제 #6
0
                if event.key == pygame.K_DOWN and snake.direction != 'u':
                    snake.direction = 'd'
                if event.key == pygame.K_RIGHT and snake.direction != 'l':
                    snake.direction = 'r'
                if event.key == pygame.K_LEFT and snake.direction != 'r':
                    snake.direction = 'l'

    # IF GAME IS WORKING
    if GAME:

        if food.check_ate(snake):
            draw_food(food)
            snake.add_case()

        last_case = snake.move()
        # try to update the board
        try:
            board.update(snake, last_case, food)
        # if we can't, he is in the wall
        except IndexError:
            print("[GAME OVER]")
            GAME = False  # he loses
            continue  # to not exec next lines

        # draw snake, refresh display
        draw_snake(snake, last_case)
        pygame.display.update()

        # CLOCK
        clock.tick(ticks)
예제 #7
0
파일: main.py 프로젝트: 74Genesis/2048
def main():
	global board, settings

	pygame.init()
	pygame.font.init()
	screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
	pygame.display.set_caption("2048 by 74Genesis")
	font = pygame.font.Font("font/ClearSans-Bold.ttf", 18)
	fontScore = pygame.font.Font("font/ClearSans-Bold.ttf", 13)

	#Основной "холст"
	mainSur = pygame.Surface((WIN_WIDTH, WIN_HEIGHT))
	mainSur.fill(pygame.Color("#faf8ef"))

	# Кнопка Новая игра
	restartBut = pygame.Surface((100, 50))
	restartBut.fill(pygame.Color("#8f7a66"))
	#текст New game
	nGame = font.render("New Game", True, (249,246,242))	

	# Счет
	score = pygame.Surface((80, 50))
	score.fill(pygame.Color("#bbada0"))
	#score
	scoreText = font.render("Score", True, (249,246,242))
	#score число
	scoreNum = None

	# Лучший счет
	bestScore = pygame.Surface((80, 50))
	bestScore.fill(pygame.Color("#bbada0"))
	bestText = font.render("Best", True, (249,246,242))

	#фон доски
	boardBg = pygame.Surface((BOARD_SIZE, BOARD_SIZE))
	boardBg.fill(pygame.Color("#bbada0"))

	board = board.Board()
	# board.board = [[2, 256, 3, 7],
 #       		  	  [2, 128, 4, 8],
	#    		  	  [1024, 64, 5, 9],
	#    		  	  [1024, 32, 6, 34]]

	#Нарисовать заполненные клетки
	cellObjects, textObjects = board.drowFullCells(cellGroup, textGroup)

	pygame.key.set_repeat(1, 400)
	clock = pygame.time.Clock()
	scoreNumX = 0
	while 1:
		clock.tick(400)
		up=down=left=right=False
		#Закрыть окно
		for e in pygame.event.get():
			#Перед выходом сохранить в файл все настройки
			if e.type == pygame.QUIT:
				settings = settings.Settings()
				settings.changeOption("Score", board.getScore())
				settings.changeOption("Best", board.getBest())
				settings.changeOption("StartGame", False)
				settings.changeOption("Board", board.getBoard())
				raise SystemExit

			#Проверять нажатие клавиши только если не осуществляется движение доски
			if not board.startMove:
				if e.type == pygame.KEYDOWN:
					if e.key == pygame.K_UP:
						up = True
					elif e.key == pygame.K_DOWN:
						down = True
					elif e.key == pygame.K_LEFT:
						left = True
					elif e.key == pygame.K_RIGHT:
						right = True
			if e.type == pygame.MOUSEBUTTONDOWN:
				mousePos = pygame.mouse.get_pos()
				if mousePos[0] > ELEM_IND and \
				   mousePos[0] < ELEM_IND+100 and \
				   mousePos[1] > ELEM_IND and \
				   mousePos[1] < ELEM_IND+50:
					board.newGame()
					#Удалить старые спрайты клеток и текста
					for key in cellObjects:
						cellGroup.remove(cellObjects[key])
					for key in textObjects:
						textGroup.remove(textObjects[key])
					cellObjects, textObjects = board.drowFullCells(cellGroup, textGroup) 


		#Если нажата кнопка управления полем
		if up or down or left or right:
			board.setStartMove(True) #начинаем передвижение
			board.setBoardMove(False) #Пересчитана ли доска
			#запоминаем нажатую кнопку
			if up: board.setKeyDown("up")
			if down: board.setKeyDown("down")
			if left: board.setKeyDown("left")
			if right: board.setKeyDown("right")

		#Пока активировано передвижение, изменяем доску
		if board.getStartMove():
			if board.getKeyDown() == "up": up = True
			if board.getKeyDown() == "down": down = True
			if board.getKeyDown() == "left": left = True
			if board.getKeyDown() == "right": right = True
			
			if not board.getBoardMove():
				nBoard, moveMap, nScore = board.move(up, down, left, right)
				board.setNewBoard(nBoard)
				board.setMoveMap(moveMap)
				board.setNewScore(nScore)

				board.setBoardMove(True)

			updateRes = board.update(cellObjects, textObjects, board.moveMap) #двигает клетки

			if updateRes: #Все клетки передвинуты
				board.setBoardMove(False)
				if len(board.getMoveMap()) > 0: # если ячейки двигались
					boardNewNum = board.totalCell(board.getNewBoard()) #добавить ещё одну цифру
					board.setBoard(boardNewNum) #сохранить новую доску
				
				#Удалить старые спрайты клеток и текста
				for key in cellObjects:
					cellGroup.remove(cellObjects[key])
				for key in textObjects:
					textGroup.remove(textObjects[key])

				cellObjects, textObjects = board.drowFullCells(cellGroup, textGroup) #Создать новые
				board.setStartMove(False) #Индикатор движения выключить

				board.setScore(board.getNewScore()) #Обновить счет

				#Если лучший счет меньше основного, обновить его
				if board.getBest() < board.getScore():
					board.setBest(board.getScore())

				#Проверяем не проиграл ли пользователь
				# if board.isMove(board.getNewBoard()):
				# 	print("Конец игры")

				#Победил ли пользователь
				# if board.winner(board.getNewBoard()):
				# 	print("Победитель !")

		#Создание числа "Счет" и "Лучший счет"
		scoreNum = fontScore.render(str(board.getScore()), True, (249,246,242))
		bestNum = fontScore.render(str(board.getBest()), True, (249,246,242))

		#Рисование всех элементов
		#Главный "Холст"
		screen.blit(mainSur, (0,0)) 
		#Новая игра
		screen.blit(restartBut, (ELEM_IND,ELEM_IND)) 
		#New game
		screen.blit(nGame, (ELEM_IND+7, ELEM_IND+11)) 
		#cчет
		screen.blit(score, (115+ELEM_IND,ELEM_IND)) 
		screen.blit(scoreText, (147, ELEM_IND)) #Текст score
		scoreNumX = numAlignCenter(str(board.getScore()), 115+ELEM_IND, 80) #позиция числа
		screen.blit(scoreNum, (scoreNumX, ELEM_IND+25)) #Число score
		#Лучший счет
		screen.blit(bestScore, (115+80+ELEM_IND*2,ELEM_IND)) 
		screen.blit(bestText, (115+80+ELEM_IND*2 + 23, ELEM_IND)) #Текст best
		bestNumX = numAlignCenter(str(board.getBest()), 115+80+ELEM_IND*2, 80) #позиция числа
		screen.blit(bestNum, (bestNumX, ELEM_IND+25)) #Число best
		#фон доски
		screen.blit(boardBg, (ELEM_IND,ELEM_IND*2 + 50)) 

		board.drowCellBack(screen, GAME_BEGIN_X, GAME_BEGIN_Y) #пустые клетки
			
		cellGroup.draw(screen)
		textGroup.draw(screen)
		pygame.display.update()
예제 #8
0
def update():
    ''' Update internal logic of the game '''

    board.update()
예제 #9
0
def update():
    gfw.world.update()
    board.update()