コード例 #1
0
def pygame_testai(ais):
    """
    输入ai列表, 跑一个pygame的测试游戏看看
    """
    from snake_game import Game
    from game_controller import Controller
    
    game = Game()
    c = Controller(game)
    m = c.map()
    for ai in ais:
        ai.setmap(m)
        result = c.add(ai.name, ai.type)
        ai.seq = result['seq']
        ai.id = result['id']

    clock = Clock(3)
    s = Shower(m)

    while True:
        clock.tick()
        
        info = c.info()
        for ai in ais:
            d = ai.onprocess(info)
            c.turn(ai.id, d, game.round)
        game.step()

        s.flip(info)
コード例 #2
0
def pygame_testai(ais):
    """
    输入ai列表, 跑一个pygame的测试游戏看看
    """
    from snake_game import Game
    from game_controller import Controller

    game = Game()
    c = Controller(game)
    m = c.map()
    for ai in ais:
        ai.setmap(m)
        result = c.add(ai.name, ai.type)
        ai.seq = result['seq']
        ai.id = result['id']

    clock = Clock(3)
    s = Shower(m)

    while True:
        clock.tick()

        info = c.info()
        for ai in ais:
            d = ai.onprocess(info)
            c.turn(ai.id, d, game.round)
        game.step()

        s.flip(info)
コード例 #3
0
    def test_end_game_if_the_snake_hits_a_wall(self):
        game = Game()
        game.snake.positions = [[5, 7], [5, 8], [5, 9]]

        game.read_key = lambda: 'j' # poor man's mock

        with self.assertRaises(GameOver):
            game.play()
コード例 #4
0
ファイル: population.py プロジェクト: kadirkun/Snnake
    def _generate_generation(self):
        if len(self.population) < 1:
            for i in range(self.population_num):
                self.population.append(self._create_new_individual())
            return self
        else:
            self._sort_population()
            alive_border = np.sum(self.partition)
            parents = self.population[:alive_border]

            for individual in self.population[alive_border:]:
                if self.random_select > np.random.rand():
                    parents.append(individual)

            for individual in parents:
                if self.mutation_rate > np.random.rand():
                    individual.player.mutation(self.mutation_rate)

            while len(parents) < self.population_num:
                parent_1 = np.random.randint(len(parents))
                parent_2 = np.random.randint(len(parents))

                if parent_1 != parent_2:
                    parent_1 = parents[parent_1]
                    parent_2 = parents[parent_2]

                    child_player = parent_1.player.crossover(parent_2.player)
                    child_game = Game(player=child_player,
                                      turn_limit=self.turn_limit,
                                      seed=self.random_seed)
                    parents.append(child_game)

            for i in range(len(parents)):
                player = parents[i].player
                parents[i] = Game(player=player,
                                  turn_limit=self.turn_limit,
                                  seed=self.random_seed)
            self.population = parents
        self.generation_num += 1
        self.random_seed = np.random.randint(0, 2**30)
コード例 #5
0
ファイル: population.py プロジェクト: kadirkun/Snnake
 def _create_new_individual(self):
     player = Machine(model=self.model)
     game = Game(player=player,
                 turn_limit=self.turn_limit,
                 seed=self.random_seed)
     return game
コード例 #6
0
import unittest, math
from snake_game import Snake, Game

BOARD_SIZE = 5
INIT_SNAKE_POSITIONS = [[
    math.floor(BOARD_SIZE / 2),
    math.floor(BOARD_SIZE / 2)
]]
INIT_POSITION = INIT_SNAKE_POSITIONS[0]

# import ipdb; ipdb.set_trace()
# snake = Snake(INIT_SNAKE_POSITIONS[:])
game = Game()


class TestMethods(unittest.TestCase):
    def test_calc_destination_up(self):
        game.snake.snake_body = [[2, 2]]
        snake_head = game.snake.snake_body[0]
        destination = game.snake.calc_destination('up')
        self.assertEqual(destination, [1, 2])

    def test_calc_destination_down(self):
        game.snake.snake_body = [[2, 2]]
        snake_head = game.snake.snake_body[0]
        destination = game.snake.calc_destination('down')
        self.assertEqual(destination, [3, 2])

    def test_calc_destination_right(self):
        game.snake.snake_body = [[2, 2]]
        snake_head = game.snake.snake_body[0]
コード例 #7
0
July 2019
"""

import turtle  # Graphics module
import time  # For delay
import random  # For placing fruits
from snake_game import Game, Snake, Food, Scoreboard

# Resource locations on disk
jungle_bg = "C:/Users/ganzk/Desktop/rise_high/python/snake/demo/bg.gif"
apple = "C:/Users/ganzk/Desktop/rise_high/python/snake/demo/apple.gif"
high_scores_path = "C:/Users/ganzk/Desktop/rise_high/python/snake/demo/high_scores.txt"

# Initialize helper objects
game = Game(512, 512, wn_bg=jungle_bg, delay=0.1)
snake = Snake(game, color="white")
food = Food(game, color="red")
scoreboard = Scoreboard(game)

# Counter for tracking the player's score
score = 0

# List of colors and index to track iteration
color_list = ["red", "orange", "yellow", "green", "blue", "violet"]
color_index = 0

high_score = None
# Load in high score
with open(high_scores_path) as file:
    for line in file:
コード例 #8
0
ファイル: snake_test.py プロジェクト: Gantulga9480/snake_full
from snake_game import Game
import numpy as np
import json
import time
from tkinter import Tk, filedialog
tk_root = Tk()
tk_root.withdraw()
dir_name = filedialog.askopenfilename()
data_file = open(dir_name, 'r')
q_table = json.load(data_file)
game = Game()
scores = 0
for i in range(100):
    state = game.reset()
    while not game.over:
        if state not in q_table:
            game.over = True
            print('state not ready')
        else:
            action = np.argmax(q_table[state])
            _, n_state, reward = game.step(action)
            state = n_state
    # time.sleep(5)
    scores += len(game.snake) - 3
    game.caption(f'{scores} : {scores/(i+1)}')
print(scores / 100)
コード例 #9
0
def main():
    game = Game()

    game.run()

    game.quit()
コード例 #10
0
By K. Ganz (and you!)
https://codingandcommunity.org/

Loosely based off of this tutorial:
https://www.youtube.com/watch?v=rrOqlfMujqQ&ab_channel=ChristianThompson

July 2019
"""

import turtle  # Graphics module
import time  # For delay
import random  # For placing fruits
from snake_game import Game, Snake, Food, Scoreboard  # Helpers

# Initialize helper objects
game = Game(600, 600, wn_color='grey', delay=0.05)
snake = Snake(game)
snake.set_direction("stop")
food = Food(game)
scoreboard = Scoreboard(game)

# Counter for tracking the player's score
score = 0
'''
Step 1: Write function to set where the snake will move

Do so with snake.set_direction(dir) where dir is a String and one of:
["up", "down", "left", "right", "stop"]
'''