Уведомления

Группа в Telegram: @pythonsu

#1 Янв. 27, 2015 19:17:33

Boomer111
Зарегистрирован: 2015-01-27
Сообщения: 6
Репутация: +  0  -
Профиль   Отправить e-mail  

Помогите найти отличия между 2 кодами Python

Всем привет!
Помогите найти отличия между 2 кодами
Что есть такого в первом, чего нет во втором и наоборот?
Заранее спасибо!

Код 1 :

#!/usr/bin/python
# -*- coding: utf-8 -*-
''' Help the user achieve a high score in a real game of 2048 by using a move searcher. '''
from __future__ import print_function
import ctypes
import time
import os
import random
# Enable multithreading?
MULTITHREAD = True
for suffix in ['so', 'dll', 'dylib']:
    dllfn = 'bin/2048.' + suffix
    if not os.path.isfile(dllfn):
        continue
    ailib = ctypes.CDLL(dllfn)
    break
else:
    print("Couldn't find 2048 library bin/2048.{so,dll,dylib}! Make sure to build it first.")
    exit()
ailib.init_tables()
ailib.find_best_move.argtypes = [ctypes.c_uint64]
ailib.score_toplevel_move.argtypes = [ctypes.c_uint64, ctypes.c_int]
ailib.score_toplevel_move.restype = ctypes.c_float
def to_c_board(m):
    board = 0
    i = 0
    for row in m:
        for c in row:            
            board |= c << (4*i)
            i += 1
    return board
def print_board(m):
    for row in m:
        for c in row:
            print('%8d' % c, end=' ')
        print()
def _to_val(c):
    if c == 0: return 0
    return 2**c
def to_val(m):
    return [[_to_val(c) for c in row] for row in m]
def _to_score(c):
    if c <= 1:
        return 0
    return (c-1) * (2**c)
def to_score(m):
    return [[_to_score(c) for c in row] for row in m]
if MULTITHREAD:
    from multiprocessing.pool import ThreadPool
    pool = ThreadPool(4)
    def score_toplevel_move(args):
        return ailib.score_toplevel_move(*args)
    def find_best_move(m):
        board = to_c_board(m)
        print_board(to_val(m))
        scores = pool.map(score_toplevel_move, [(board, move) for move in range(4)])
        bestmove, bestscore = max(enumerate(scores), key=lambda x:x[1])
        if bestscore == 0:
            return -1
        return bestmove
else:
    def find_best_move(m):
        board = to_c_board(m)
        return ailib.find_best_move(board)
def movename(move):
    return ['up', 'down', 'left', 'right'][move]
def rungame(args):
    from gamectrl import BrowserRemoteControl, Fast2048Control, Keyboard2048Control, Hybrid2048Control
    if len(args) == 1:
        port = int(args[0])
    else:
        port = 32000
    ctrl = BrowserRemoteControl(port)
    # Use Keyboard2048Control if Fast2048Control doesn't seem to be working.
    # gamectrl = Fast2048Control(ctrl)
    gamectrl = Hybrid2048Control(ctrl)
    if gamectrl.get_status() == 'ended':
        gamectrl.restart_game()
    moveno = 0
    start = time.time()
    while 1:
        state = gamectrl.get_status()
        if state == 'ended':
            break
        elif state == 'won':
            time.sleep(0.75)
            gamectrl.continue_game()
        moveno += 1
        board = gamectrl.get_board()
        move = find_best_move(board)
        if move < 0:
            break
        print("%010.6f: Score %d, Move %d: %s" % (time.time() - start, gamectrl.get_score(), moveno, movename(move)))
        time.sleep(random.randint(3,10)/10.0)
        gamectrl.execute_move(move)
        
    score = gamectrl.get_score()
    board = gamectrl.get_board()
    maxval = max(max(row) for row in to_val(board))
    print("Game over. Final score %d; highest tile %d." % (score, maxval))
if __name__ == '__main__':
    import sys
    rungame(sys.argv[1:])

Код 2 :
#!/usr/bin/python
# -*- coding: utf-8 -*-
''' Help the user achieve a high score in a real game of threes by using a move searcher. '''
from __future__ import print_function
import ctypes
import time
import os
# Enable multithreading?
MULTITHREAD = True
for suffix in ['so', 'dll', 'dylib']:
    dllfn = 'bin/2048.' + suffix
    if not os.path.isfile(dllfn):
        continue
    ailib = ctypes.CDLL(dllfn)
    break
else:
    print("Couldn't find 2048 library bin/2048.{so,dll,dylib}! Make sure to build it first.")
    exit()
ailib.init_tables()
ailib.find_best_move.argtypes = [ctypes.c_uint64]
ailib.score_toplevel_move.argtypes = [ctypes.c_uint64, ctypes.c_int]
ailib.score_toplevel_move.restype = ctypes.c_float
def to_c_board(m):
    board = 0
    i = 0
    for row in m:
        for c in row:            
            board |= c << (4*i)
            i += 1
    return board
def print_board(m):
    for row in m:
        for c in row:
            print('%8d' % c, end=' ')
        print()
def _to_val(c):
    if c == 0: return 0
    return 2**c
def to_val(m):
    return [[_to_val(c) for c in row] for row in m]
def _to_score(c):
    if c <= 1:
        return 0
    return (c-1) * (2**c)
def to_score(m):
    return [[_to_score(c) for c in row] for row in m]
if MULTITHREAD:
    from multiprocessing.pool import ThreadPool
    pool = ThreadPool(4)
    def score_toplevel_move(args):
        return ailib.score_toplevel_move(*args)
    def find_best_move(m):
        board = to_c_board(m)
        print_board(to_val(m))
        scores = pool.map(score_toplevel_move, [(board, move) for move in range(4)])
        bestmove, bestscore = max(enumerate(scores), key=lambda x:x[1])
        if bestscore == 0:
            return -1
        return bestmove
else:
    def find_best_move(m):
        board = to_c_board(m)
        return ailib.find_best_move(board)
def movename(move):
    return ['up', 'down', 'left', 'right'][move]
def rungame(args):
    from gamectrl import BrowserRemoteControl, Fast2048Control, Keyboard2048Control
    if len(args) == 1:
        port = int(args[0])
    else:
        port = 32000
    ctrl = BrowserRemoteControl(port)
    # Use Keyboard2048Control if Fast2048Control doesn't seem to be working.
    gamectrl = Fast2048Control(ctrl)
    # gamectrl = Keyboard2048Control(ctrl)
    if gamectrl.get_status() == 'ended':
        gamectrl.restart_game()
    moveno = 0
    start = time.time()
    while 1:
	if(gamectrl.get_score()<10000): 
	    time.sleep(0.6)
        state = gamectrl.get_status()
        if state == 'ended':
            break
        elif state == 'won':
            time.sleep(0.75)
            gamectrl.continue_game()
        moveno += 1
        board = gamectrl.get_board()
        move = find_best_move(board)
        if move < 0:
            break
        print("%010.6f: Score %d, Move %d: %s" % (time.time() - start, gamectrl.get_score(), moveno, movename(move)))
        gamectrl.execute_move(move)
    score = gamectrl.get_score()
    board = gamectrl.get_board()
    maxval = max(max(row) for row in to_val(board))
    print("Game over. Final score %d; highest tile %d." % (score, maxval))
if __name__ == '__main__':
    import sys
    rungame(sys.argv[1:])

Отредактировано Boomer111 (Янв. 27, 2015 19:17:56)

Офлайн

#2 Янв. 27, 2015 19:59:20

Rodegast
От: Пятигорск
Зарегистрирован: 2007-12-28
Сообщения: 2759
Репутация: +  185  -
Профиль   Отправить e-mail  

Помогите найти отличия между 2 кодами Python

Вот тебе скришоты с отличиями:
http://s017.radikal.ru/i427/1501/70/3e4b80c00527.png
http://s018.radikal.ru/i523/1501/3b/870e4af08838.png



С дураками и сектантами не спорю, истину не ищу.
Ели кому-то правда не нравится, то заранее извиняюсь.

Офлайн

#3 Янв. 27, 2015 19:59:44

doza_and
От:
Зарегистрирован: 2010-08-15
Сообщения: 4138
Репутация: +  252  -
Профиль   Отправить e-mail  

Помогите найти отличия между 2 кодами Python

Офлайн

#4 Янв. 27, 2015 19:59:50

Alex_HH
Зарегистрирован: 2014-03-03
Сообщения: 91
Репутация: +  13  -
Профиль   Отправить e-mail  

Помогите найти отличия между 2 кодами Python

в первом есть:

import random
...
time.sleep(random.randint(3,10)/10.0)



————–
Зимой и летом heavy metall.
Технический прогресс - это падение вверх. Alex_HH (с)
Эстетизация жестокости есть квинтэссенция смысла человеческого существования. Alex_HH (с)
После бога идет не пустота, там метаданные. Alex_HH (с)

Офлайн

#5 Янв. 28, 2015 00:10:26

py.user.next
От:
Зарегистрирован: 2010-04-29
Сообщения: 9890
Репутация: +  854  -
Профиль   Отправить e-mail  

Помогите найти отличия между 2 кодами Python

[guest@localhost py]$ .diff file1.py file2.py 
--- file1.py 2015-01-28 08:09:25.301345276 +1000
+++ file2.py 2015-01-28 08:09:41.094297827 +1000
@@ -1,11 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
-''' Help the user achieve a high score in a real game of 2048 by using a move searcher. '''
+''' Help the user achieve a high score in a real game of threes by using a move searcher. '''
from __future__ import print_function
import ctypes
import time
import os
-import random
# Enable multithreading?
MULTITHREAD = True
for suffix in ['so', 'dll', 'dylib']:
@@ -65,20 +64,22 @@
def movename(move):
return ['up', 'down', 'left', 'right'][move]
def rungame(args):
- from gamectrl import BrowserRemoteControl, Fast2048Control, Keyboard2048Control, Hybrid2048Control
+ from gamectrl import BrowserRemoteControl, Fast2048Control, Keyboard2048Control
if len(args) == 1:
port = int(args[0])
else:
port = 32000
ctrl = BrowserRemoteControl(port)
# Use Keyboard2048Control if Fast2048Control doesn't seem to be working.
- # gamectrl = Fast2048Control(ctrl)
- gamectrl = Hybrid2048Control(ctrl)
+ gamectrl = Fast2048Control(ctrl)
+ # gamectrl = Keyboard2048Control(ctrl)
if gamectrl.get_status() == 'ended':
gamectrl.restart_game()
moveno = 0
start = time.time()
while 1:
+ if(gamectrl.get_score()<10000):
+ time.sleep(0.6)
state = gamectrl.get_status()
if state == 'ended':
break
@@ -91,9 +92,7 @@
if move < 0:
break
print("%010.6f: Score %d, Move %d: %s" % (time.time() - start, gamectrl.get_score(), moveno, movename(move)))
- time.sleep(random.randint(3,10)/10.0)
gamectrl.execute_move(move)
-
score = gamectrl.get_score()
board = gamectrl.get_board()
maxval = max(max(row) for row in to_val(board))
[guest@localhost py]$



Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version