Esempio n. 1
0
 def reset_apples(self):
     self.apples = []
     coordinates = []
     word, answer = self.word_generator.get_word(answer=True)
     self.word, self.answer = word, answer
     for i in range(self.apple_num):
         ap = apple.Apple(answer, self.grid)
         while ap.position in coordinates:
             ap = apple.Apple(answer, self.grid)
         coordinates.append(ap.position)
         self.apples.append(ap)
         word, answer = self.word_generator.get_word()
Esempio n. 2
0
    def __init__(self, agent2):
        p.init()
        p.display.set_caption('Snake Game')
        self.displayWidth = 800
        self.displayHeight = 600
        self.gameDisplay = p.display.set_mode(
            (self.displayWidth, self.displayHeight))
        self.FPS = 60
        self.font = p.font.SysFont(None, 25)
        self.blockSize = 25
        self.clock = p.time.Clock()
        self.player = opsnake.OpSnake(self.displayWidth / 2,
                                      self.displayHeight / 2, self.blockSize)
        self.gameExit = False
        self.gameOver = False
        self.apple = apple.Apple(self.displayWidth, self.displayHeight,
                                 self.blockSize, self.player.snakeList)
        self.fitness = 0.0
        self.control = True
        self.outS = False
        self.debug = False
        self.agent = agent2
        #self.hamilton      = hamilton.HamiltonSnake(self.displayWidth/2,self.displayHeight/2,self.blockSize)

        self.player.snakeLength = 3
Esempio n. 3
0
    def POST(self, arg):
        """POST operation that enables the interaction with the MySQL database
        through a JSON file

        Parameters
        ----------
        data_json : json
            Arguments specifying the type of operation to
            apply in the MySQL database (it could be any kind of CRUD 
            operation). In must cases it also needs to have more arguments to
            be able to query some specific things in the database.

        Returns
        -------
        json
            Results from the database in JSON format
        """
        data_json = cherrypy.request.json
        apple_obj = apple.Apple(data_json)
        try:
            response = apple_obj.manage_operations()
        except Exception as catched_exception:
            response = str(catched_exception)
        response = {'response': response}
        return response
Esempio n. 4
0
    def createObjects(self):
        ''' Cria os objetos da aplicação '''
        return {
            # Objeto da snake
            'snake': snake.Snake(),

            # Fábrica de maçãs
            'apple': apple.Apple(),
        }
 def add_apples(self, size=3, start=np.array([0, 0])):
     """
     add apples of the diamond shape with given size
     :param size: the size of diamond
     :param start: the starting point of the diamond in 
                     the left-bottom corner
     :return: the added apple
     """
     l = size * 2 - 1
     top = start + l - 1
     for idx in range(size - 1):
         for i in range(idx * 2 + 1):
             row = top[0] - idx
             col = start[1] + size - 1 - idx + i
             self.apples.append(apple.Apple(row, col))
     for idx in range(size - 1, -1, -1):
         for i in range(idx * 2 + 1):
             row = start[0] + idx
             col = start[1] + size - 1 - idx + i
             self.apples.append(apple.Apple(row, col))
Esempio n. 6
0
 def new_game(self):
     # varaible to store our score
     self.score = 0
     # variable to control snake speed
     self.ticks = 0
     # flag with game stance
     self.game_on = False
     # store ticks since last facing change to avoid bugs
     self.time_since_change = 0
     # make new snake
     self.snk = snake.Snake()
     # make new apple
     self.appl = apple.Apple(self.snk)
Esempio n. 7
0
 def update(self):
     self.snk.update()
     # check if snake collided with wall, if true end active game and reset snake, show game over info and wait some time
     if self.snk.wall_collision() or self.snk.self_collision():
         settings.gameover.play()
         #check if record was beated when died
         if self.score > self.high_score:
             self.high_score = self.score
         self.new_game()
         rect = settings.GAME_OVER.get_rect()
         rect.center = self.window.get_rect().center
         self.window.blit(settings.GAME_OVER, rect)
         pygame.display.update()
         pygame.time.delay(700)
     elif self.snk.apple_collision(self.appl):
         settings.score.play()
         self.score += 1
         self.appl = apple.Apple(self.snk)
         # make snake grow up
         self.snk.grow = True
Esempio n. 8
0
def run_game():
    """
    运行游戏
    :return None:
    """
    pygame.init()
    screen = pygame.display.set_mode(st.WindowSetting.size)
    pygame.display.set_caption(st.WindowSetting().game_tetle)
    my_snake = snake.Snake()
    my_edge = edge.Edge()
    my_apple = apple.Apple(
        (st.GameAreaSetting.width // 2, st.GameAreaSetting.hight // 2))
    music.load(r"./bgm.aiff")
    music.play(loops=-1)

    while True:
        """游戏主循环"""

        begin_time = time.clock()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    my_snake.forward = my_snake.RIGHT
                elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    my_snake.forward = my_snake.LEFT
                elif event.key == pygame.K_UP or event.key == pygame.K_w:
                    my_snake.forward = my_snake.UP
                elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                    my_snake.forward = my_snake.DOWN

        if my_snake.is_dead():
            time.sleep(0.5)
            sys.exit()

        if my_snake.is_get_apple(my_apple):
            my_snake.grow()

            while True:
                local = random.randint(0, st.GameAreaSetting.width -
                                       1), random.randint(
                                           0, st.GameAreaSetting.hight - 1)
                if local not in [item.local for item in my_snake.body]:
                    break
            my_apple = apple.Apple(local)

        else:
            my_snake.move()

        screen.fill(st.GameAreaSetting.color)
        my_edge.draw(screen)
        my_apple.draw(screen)
        my_snake.draw(screen)
        pygame.display.flip()

        try:
            time.sleep(0.125 - time.clock() + begin_time)
        except ValueError:
            pass
Esempio n. 9
0
pygame.font.init()

canvasLength = 480
canvasHeight = 480

win = pygame.display.set_mode((canvasLength, canvasHeight))

pygame.display.set_caption("Slange")

x = 50
y = 50
width = 20
height = 20

snake = snake.Snake(win)
apple1 = apple.Apple(win, snake)
apple2 = apple.Apple(win, snake)


def drawGrid():
    for k in range(2):
        for i in range(0, canvasLength, 20):
            if k == 0:
                pygame.draw.line(win, (50, 50, 50), (i, 0), (i, canvasLength),
                                 1)
            else:
                pygame.draw.line(win, (50, 50, 50), (0, i), (canvasHeight, i),
                                 1)


def drawGameOver():
Esempio n. 10
0
 def initialize(self):
     self.snake = snake.Snake(self.tile_size, self.grid_width,
                              self.grid_height)
     self.apple = apple.Apple(self.tile_size, self.grid_width,
                              self.grid_height, self.snake)
Esempio n. 11
0
 def __init__(self):
     self._player = player.Player((GRID_SIZE[0] / 2, GRID_SIZE[1] / 2))
     self._apple = apple.Apple()
Esempio n. 12
0
def main():
    # set screen width and height
    SCREEN_WIDTH = 1000
    SCREEN_HEIGHT = 900
    # needed to start pygame
    pygame.init()
    mainsurface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
    pygame.display.set_caption("Chomper")

    # sets color to white
    WHITE = (255, 255, 255)
    # defines apple group
    appleGroup = pygame.sprite.Group()
    for x in range(15):
        """loop blits blits apples in random locations"""
        xpos = random.randint(0, 950)
        ypos = random.randint(0, 850)
        myapple = apple.Apple(mainsurface)
        myapple.rect.topleft = (xpos, ypos)
        myapple.add(appleGroup)
        mainsurface.blit(myapple.image, myapple.rect)

    # defines the mouth group
    mouthGroup = pygame.sprite.Group()
    # difines the mouth
    mymouth = mouth.Mouth(mainsurface)
    # defines size of the mouth
    mymouth.rect.topleft = (50, 50)
    # adds mouth to a sprite group
    mymouth.add(mouthGroup)
    # blits mouth to the screen
    mainsurface.blit(mymouth.image, mymouth.rect)
    # dfines the font and the label for the game over screen
    myfont = pygame.font.SysFont("Britannic Bold", 200)
    nlabel = myfont.render("Game Over", 1, (0, 0, 0))

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        # sets the frames per second of the game/animation
        clock = pygame.time.Clock()
        clock.tick(50)
        # fills the screen with white
        mainsurface.fill(WHITE)

        pressed = pygame.key.get_pressed()
        # moves mouth if key is pressed
        if pressed[pygame.K_UP]:
            mymouth.up()
        # moves mouth if key is pressed
        if pressed[pygame.K_DOWN]:
            mymouth.down()
        # moves mouth if key is pressed
        if pressed[pygame.K_LEFT]:
            mymouth.left()
        # moves mouth if key is pressed
        if pressed[pygame.K_RIGHT]:
            mymouth.right()
        mainsurface.blit(mymouth.image, mymouth.rect)
        # blits the apples to the screen
        for myapple in appleGroup:
            mainsurface.blit(myapple.image, myapple.rect)

        mymouth.collide(appleGroup)
        # displays game over when all the aplles are gone
        if len(appleGroup) == 0:
            mainsurface.blit(nlabel, (100, 400))
        # updates display
        pygame.display.update()
Esempio n. 13
0
from constants import *
import pygame
import snake
import apple

clock = pygame.time.Clock()
surface = pygame.display.set_mode((GAME_WIDTH, GAME_HEIGHT))

pygame.init()

snake = snake.Snake()
apple = apple.Apple()


def main():
    running = True

    while running:
        clock.tick(TICK_RATE)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        draw()
        update()

    pygame.quit()


def draw():
    surface.fill((0, 0, 0))  #background
Esempio n. 14
0
    ##create Canvas
    canvas = tkinter.Canvas(window,
                            width=constantes.width,
                            height=constantes.height,
                            bg='green')
    canvas.grid()

    ##scoreboard
    tscore = tkinter.Text(window, width=20, height=1)
    tscore.grid(row=1, column=0)

    ##create snake and apple
    snake = snake.Snake(int(constantes.blocks[0] / 2),
                        int(constantes.blocks[0] / 2),
                        canvas=canvas)
    apple = apple.Apple(1, 1)
    apple.move(snake)
    apple.insert(canvas)
    snake.insert()
    ##key binds
    window.bind("<Return>", execute)
    # window.bind("<Key>", input)
    window.bind("<Up>", wkey)
    window.bind("<Left>", akey)
    window.bind("<Right>", dkey)
    window.bind("<Down>", skey)
    window.bind("<Shift-Up>", grow_cheat)
    window.bind("<Shift-Down>", d_grow_cheat)

    window.mainloop()