示例#1
0
 def move(self, dx, dy):
     """
     Parameters: dx - type: int, dy - type: int
     moves the block dx squares in the x direction
     and dy squares in the y direction
     """
     self.x += dx
     self.y += dy
     Rectangle.move(self, dx*Block.BLOCK_SIZE, dy*Block.BLOCK_SIZE)
示例#2
0
def test():
    window = GraphWin()
    window.setCoords(0, 0, 10, 10)
    r = Rectangle(Point(1, 1), Point(2, 2))
    r.setFill("red")
    r.draw(window)
    for i in range(10):
        time.sleep(1)
        r.undraw()
        r.move(1, 0)
        r.draw(window)
    window.getMouse()
    window.close()
示例#3
0
文件: Part.py 项目: hjack69/SnakeAI
class Part:
    def __init__(self, win, game, position, next=None):
        self.win = win

        # This is the relative position without any scale
        self.position = position.clone()

        self.game = game
        self.next = next

        # This uses the true screen position
        self.__rectangle = Rectangle(
            self.position + (self.game.position * SCALE_V),
            self.position + (self.game.position * SCALE_V))
        self.__rectangle.setFill('red')
        self.__rectangle.draw(self.win)

    def update(self, position):
        oldPos = self.position.clone()
        self.position = position
        self.__rectangle.move((oldPos.x - self.position.x) * SCALE,
                              (oldPos.y - self.position.y) * SCALE)
        update()
        if self.next:
            self.next.update(oldPos)

    def add_part(self):
        return Part(self.win, self.game, self.position.clone(), self)

    def is_colliding(self, p=None):
        if not p:
            if self.next:
                return self.next.is_colliding(self.position.clone())
            else:
                return False
        else:
            if p == self.position:
                return True
            else:
                if self.next:
                    return self.next.is_colliding(p)
        return False

    def delete(self):
        self.__rectangle.undraw()
        if self.next:
            self.next.delete()
    def Table():
        title = Text(Point(3.5, 10.5), 'Tic - Tac - Toe')
        title.draw(win)
        box_1 = Rectangle(Point(0, 0), Point(3, 3))
        box_1.setFill('white')
        box_1.move(-1, 0)
        box_1.draw(win)

        box_2 = box_1.clone()
        box_2.move(3, 0)

        box_2.draw(win)

        box_3 = box_1.clone()
        box_3.move(6, 0)
        box_3.draw(win)

        box_4 = box_1.clone()
        box_4.move(0, 3)
        box_4.draw(win)

        box_5 = box_1.clone()
        box_5.move(0, 6)
        box_5.draw(win)

        box_6 = box_1.clone()
        box_6.move(3, 3)
        box_6.draw(win)

        box_7 = box_1.clone()
        box_7.move(3, 6)
        box_7.draw(win)

        box_8 = box_1.clone()
        box_8.move(6, 3)
        box_8.draw(win)

        box_9 = box_1.clone()
        box_9.move(6, 6)
        box_9.draw(win)
示例#5
0
    def draw(self):

        rect1 = Rectangle(Point(50, 50 + self.m),
                          Point(50 + self.m * 2, 50 - self.m))
        rect2 = Rectangle(Point(50 - self.size, 50 + self.m),
                          Point(50 + self.m * 2 - self.size, 50 - self.m))
        rect1.setFill("red")
        rect2.setFill("red")
        rect1.draw(self.win1)
        rect2.draw(self.win2)

        right = -2 * self.size + 50 + 2 * self.m
        left = 50
        top = 50 - self.m
        bottom = -self.size + 50 + self.m

        while True:

            rect1.move(self.vx, self.vy)
            rect2.move(self.vx, self.vy)

            right += self.vx
            left += self.vx
            top += self.vy
            bottom += self.vy

            if right >= 0:
                self.vx *= -1

            if left <= 0:
                self.vx *= -1

            if top <= 0:
                self.vy *= -1

            if bottom >= 0:
                self.vy *= -1

            sleep(0.01)
示例#6
0
class Square(Character):
    def __init__(self, color, lower_x, lower_y, size):
        Character.__init__(self)
        self.rect = Rectangle(Point(lower_x, lower_y),
                              Point(lower_x + size, lower_y + size))

    def move(self, dx, dy):
        self.rect.move(dx, dy)

    def rotate(self, angle, x=0, y=0):
        pass

    def recolor(self, color):
        pass

    def scale(self, amount):
        pass

    def draw(self, window):
        self.rect.draw(window)

    def undraw(self):
        self.rect.undraw()
示例#7
0
class Car():
    WHEEL_TO_TIRE_RATIO = 0.6

    def __init__(self, back_wheel_center, back_tire_radius, front_wheel_center,
                 front_tire_radius, body_height):
        upper_left_point = Point(back_wheel_center.x,
                                 back_wheel_center.y - body_height)
        bottom_right_point = front_wheel_center
        self.body = Rectangle(upper_left_point, bottom_right_point)

        self.back_wheel = Wheel(back_wheel_center,
                                back_tire_radius * Car.WHEEL_TO_TIRE_RATIO,
                                back_tire_radius)
        self.front_wheel = Wheel(front_wheel_center,
                                 front_tire_radius * Car.WHEEL_TO_TIRE_RATIO,
                                 front_tire_radius)

    def set_color(self, tire_color, wheel_color, body_color):
        self.body.setFill(body_color)

        self.back_wheel.set_color(wheel_color, tire_color)
        self.front_wheel.set_color(wheel_color, tire_color)

    def draw(self, win):
        self.body.draw(win)
        self.back_wheel.draw(win)
        self.front_wheel.draw(win)

    def move(self, dx, dy):
        self.back_wheel.move(dx, dy)
        self.front_wheel.move(dx, dy)
        self.body.move(dx, dy)

    def animate(self, win, dx, dy, n):
        if n > 0:
            self.move(dx, dy)
            win.after(10, self.animate, win, dx, dy, n - 1)
示例#8
0
rect.setFill("red")

rect.draw(win)

g = -9.0665 / 100

v = 0

c = 0

u = 0

while True:

    bottom = size - rect.getP2().getY()

    rect.move(0, -v)

    v = u + g * c
    print(v)

    bottom += v

    c += 1

    if bottom <= 0:
        u = -v
        c = 0

    sleep(0.01)
示例#9
0
from math import radians as rad
from time import sleep

size = 500
half = size / 2
win = GraphWin("SPRING", size, size)

rect = Rectangle(Point(half - 25, size - 50), Point(half + 25, size))
rect.setFill("red")
rect.draw(win)

pos = win.getMouse()
print(pos, "start")
x = pos.getX() - half

cen = rect.getCenter()

for i in range(1000):

    dist = 4 * pi * sin(rad(4 * pi * i))
    rect.move(dist + x, 0)

    if cen.getX() >= rect.getCenter().getX():
        print(cen.getX(), "min")
    else:
        print(cen.getX())

    cen = rect.getCenter()

    sleep(0.1)
示例#10
0
class BlockJumpGame(GraphWin):
    def __init__(self,
                 gameMode='normal',
                 numOfPlayers=1,
                 maxFrameRate=80,
                 popName=False,
                 render=True,
                 screenSize=[800, 600],
                 initialGameSpeed=20):
        if render == True:
            self.renderization = True
            GraphWin.__init__(self, 'Block-Jump-Game', screenSize[0],
                              screenSize[1])
        else:
            self.renderization = False

        self.gameConfig = {
            'maxFrameRate': maxFrameRate,
            'screenSize': screenSize,
            'initialGameSpeed': initialGameSpeed
        }
        self.gameMode = gameMode
        self.numOfPlayers = numOfPlayers
        self.playersAlive = [x for x in range(numOfPlayers)]
        self.player = []
        for i in range(numOfPlayers):
            if gameMode == 'aitrain':
                self.player.append(Player(self, i, popName))
            else:
                self.player.append(Player(self, i))
        self.initialGameSpeed = initialGameSpeed
        self.gameSpeed = initialGameSpeed
        self.groundLevel = self.gameConfig['screenSize'][1] - 7
        self.obstacle = None
        self.createObstacle()

        self.points = 0
        self.maxFrameRate = maxFrameRate

        self.pointsText = Text(
            Point(0 + screenSize[0] / 10, 0 + screenSize[0] / 50),
            'Points: ' + str(self.points))
        if self.renderization:
            self.pointsText.draw(self)

        self.timeWhenGameStarted = time.time()
        self.gameEnd = False
        self.start()

    def start(self):
        while self.gameEnd == False:
            self.render()

    def render(self):
        self.checkPoints()
        self.refreshHUD()
        self.checkObstacle()
        self.detectInput()
        self.moveObjects()
        for i in self.playersAlive:
            self.player[i].fall()
        self.addPoints()
        self.checkColisions()
        if self.renderization:
            time.sleep(1 / self.maxFrameRate)

    def checkColisions(self):
        if self.obstacle != None:
            for i in self.playersAlive:
                if self.player[i].getP2().getX() > self.obstacle.getP1().getX(
                ) and self.player[i].getP1().getX() < self.obstacle.getP1(
                ).getX() or self.player[i].getP2().getX(
                ) > self.obstacle.getP2().getX() and self.player[i].getP1(
                ).getX() < self.obstacle.getP2().getX(
                ) or self.player[i].getP2().getX(
                ) > self.obstacle.getCenter().getX() and self.player[i].getP1(
                ).getX() < self.obstacle.getCenter().getX():
                    if self.player[i].getP2().getY() > self.obstacle.getP1(
                    ).getY():
                        self.gameOver(i)

    def gameOver(self, player_id):
        self.player[player_id].move(10000, 10000)
        if self.renderization:
            self.player[player_id].undraw()
        self.playersAlive.remove(player_id)
        self.player[player_id].alive = False
        self.player[player_id].points = self.points
        if not self.checkPlayersAlive():
            if self.gameMode == 'normal' and self.renderization:
                self.gameOverText = Text(
                    Point(self.gameConfig['screenSize'][0] / 2,
                          self.gameConfig['screenSize'][1] / 2),
                    'Game Over\nPress R to restart\nor press any key to quit')
                self.gameOverText.draw(self)
                key = self.getKey()
                self.gameEnd = True
                print('XXXXXXXXXXXXXXXXXXXXXXXXX')
                print('------Game Status------')
                print('Points: ' + str(round(self.points)))
                print('Played for: ' +
                      str(round(time.time() - self.timeWhenGameStarted)) +
                      ' seconds')
                print('XXXXXXXXXXXXXXXXXXXXXXXXX')
                if key == 'r':
                    self.restart()
                else:
                    self.close()
            elif self.gameMode == 'aitrain':
                self.finalPoints = []
                for i in range(self.numOfPlayers):
                    self.finalPoints.append(self.player[i].points)
                self.gameEnd = True
                if self.renderization:
                    self.close()

    def refreshHUD(self):
        self.pointsText.setText('Points: ' + str(round(self.points)))

    def checkPoints(self):
        if int(self.points / 10) - (self.gameSpeed -
                                    self.initialGameSpeed) == 1:
            if self.points < 500:
                self.gameSpeed += 1

    def checkPlayersAlive(self):
        for i in range(self.numOfPlayers):
            if self.player[i].alive:
                return True
        return False

    def addPoints(self):
        self.points += 1 / self.maxFrameRate * self.gameSpeed / 10

    def detectInput(self):
        if self.gameMode == 'normal' and self.renderization:
            input = self.checkKey()
        for i in self.playersAlive:
            if self.gameMode == 'aitrain':
                input = self.player[i].brain.guess(self.generateInput(i))
            if input == 'Up' and self.player[i].status == 'nothing':
                self.player[i].jump()
                self.player[i].status = 'jumping'
            if input == 'Down' and self.player[i].status == 'jumping':
                if self.player[i].speed < 0:
                    self.player[i].speed = 0
                self.player[i].status = 'fastfall'

    def generateInput(self, id):
        array = []
        array += self.DecToBinaryArray(int(self.player[id].getDistance()), 10)
        array += self.DecToBinaryArray(self.obstacleType, 2)
        array += self.DecToBinaryArray(self.gameSpeed, 7)
        # array += self.DecToBinaryArray(self.obstacleHeight , 8)
        return array

    @staticmethod
    def DecToBinaryArray(num, arrayRange):
        array = list(0 for _ in range(arrayRange - len(bin(num)[2:])))
        array.extend(list(int(x) for x in bin(num)[2:]))
        return array

    def checkObstacle(self):
        if self.obstacle != None:
            if self.obstacle.getCenter().getX() < -self.obstacleWidth + 10:
                if self.renderization:
                    self.obstacle.undraw()
                self.obstacle = None
                self.createObstacle()

    def createObstacle(self):
        height = 150
        randomizer = random.randint(1, 3)
        if randomizer == 1:
            width = 75
        elif randomizer == 2:
            width = 100
        else:
            width = 125

        self.obstacleType = randomizer
        self.obstacleHeight = height
        self.obstacleWidth = width
        self.obstacle = Rectangle(
            Point(self.gameConfig['screenSize'][0],
                  self.gameConfig['screenSize'][1] - self.obstacleHeight),
            Point(self.gameConfig['screenSize'][0] + self.obstacleWidth,
                  self.gameConfig['screenSize'][1]))
        self.obstacle.setFill(
            color_rgb(random.randint(0, 255), random.randint(0, 255),
                      random.randint(0, 255)))
        if self.renderization:
            self.obstacle.draw(self)

    def moveObjects(self):
        for i in range(self.numOfPlayers):
            self.player[i].move(
                0, round(self.player[i].speed / self.maxFrameRate, 1))
            if self.player[i].getP2().getY() >= self.groundLevel:
                self.player[i].move(
                    0, self.groundLevel - self.player[i].getP2().getY())
                self.player[i].speed = 0
                self.player[i].status = 'nothing'

        if self.obstacle != None:
            self.obstacle.move(-self.gameSpeed * 10 / self.maxFrameRate, 0)

    def restart(self):
        for i in range(self.numOfPlayers):
            self.player[i] = Player(self, i)
            self.player[i].speed = 0
            self.player[i].status = 'nothing'
        self.gameSpeed = self.initialGameSpeed
        self.obstacle.undraw()
        self.gameOverText.undraw()
        self.obstacle = None
        self.createObstacle()

        self.points = 0

        self.pointsText.undraw()
        self.pointsText = Text(
            Point(0 + self.gameConfig['screenSize'][0] / 10,
                  0 + self.gameConfig['screenSize'][0] / 50),
            'Points: ' + str(self.points))
        self.pointsText.draw(self)

        self.timeWhenGameStarted = time.time()
        self.gameEnd = False
        self.start()

    @staticmethod
    def playGames(timesToPlay=1,
                  gameMode='normal',
                  numOfPlayers=1,
                  maxFrameRate=80,
                  popName=False,
                  render=True,
                  screenSize=[800, 600],
                  initialGameSpeed=20):
        totalPoints = [0 for _ in range(numOfPlayers)]
        for _ in range(timesToPlay):
            gameInstance = BlockJumpGame(gameMode, numOfPlayers, maxFrameRate,
                                         popName, render, screenSize,
                                         initialGameSpeed)
            for i in range(len(gameInstance.finalPoints)):
                totalPoints[i] += gameInstance.finalPoints[i]
        highestPoints = 0
        betterPlayerId = 0
        for i in range(len(totalPoints)):
            if totalPoints[i] > highestPoints:
                highestPoints = totalPoints[i]
                betterPlayerId = i

        print('MAX AVERAGE RECORD: ' +
              str(round(highestPoints / timesToPlay, 2)))
        return betterPlayerId
示例#11
0
    def draw(self):

        p1 = (self.v1x**2 + self.v1y**2)**0.5 * self.m1
        p2 = (self.v2x**2 + self.v2y**2)**0.5 * self.m2
        pt = p1 + p2

        print("Total Momentum: {} kgm/s".format(pt))

        win = Collisions.window(self)

        h1 = random.randint(self.m1 * 2, self.size - self.m1 * 2)
        h2 = random.randint(self.m2 * 2, self.size - self.m2 * 2)
        # h1 = self.m1+51
        # h2 = self.size-self.m2-51

        distancex = self.size - 100 - self.m1 * 2 - self.m2 * 2
        distancey = h2 - h1 - self.m1 - self.m2

        rect1 = Rectangle(Point(50, h1 + self.m1),
                          Point(50 + self.m1 * 2, h1 - self.m1))
        rect1.setFill("blue")
        rect2 = Rectangle(Point(self.size - 50, h2 + self.m2),
                          Point(self.size - 50 - self.m2 * 2, h2 - self.m2))
        rect2.setFill("red")

        left1 = 50
        right1 = -self.size + 50 + self.m1 * 2
        top1 = h1 - self.m1
        bottom1 = -self.size + h1 + self.m1
        left2 = self.size - 50 - self.m2 * 2
        right2 = self.size - 50
        top2 = h2 - self.m2
        bottom2 = -self.size + h2 + self.m2

        rect1.draw(win)
        rect2.draw(win)

        while True:

            u1x = self.v1x
            u1y = self.v1y
            u2x = self.v2x
            u2y = self.v2y

            if -2 * self.m1 - 2 * self.m2 <= distancex <= 0:
                ycheck = True
            else:
                ycheck = False

            if -2 * self.m1 - 2 * self.m2 <= distancey <= 0:
                xcheck = True
            else:
                xcheck = False

            rect1.move(self.v1x, self.v1y)
            rect2.move(self.v2x, self.v2y)

            right1 += self.v1x
            left1 += self.v1x
            top1 += self.v1y
            bottom1 += self.v1y
            right2 += self.v2x
            left2 += self.v2x
            top2 += self.v2y
            bottom2 += self.v2y

            distancex -= self.v1x - self.v2x
            distancey -= self.v1y - self.v2y

            if right1 >= 0 or left1 <= 0:
                self.v1x *= -1

            if right2 >= self.size or left2 <= 0:
                self.v2x *= -1

            if top1 <= 0 or bottom1 >= 0:
                self.v1y *= -1

            if top2 <= 0 or bottom2 >= 0:
                self.v2y *= -1

            if -2 * self.m1 - 2 * self.m2 <= distancey <= 0 and ycheck:
                if -2 * self.m1 - 2 * self.m2 <= distancex <= 0:
                    self.v1y = (self.m1**2-self.m2**2)/(self.m1**2+self.m2**2)*u1y + \
                               (2*self.m2**2)/(self.m1**2+self.m2**2)*u2y
                    self.v2y = (self.m2**2-self.m1**2)/(self.m1**2+self.m2**2)*u2y + \
                               (2*self.m1**2)/(self.m1**2+self.m2**2)*u1y

            if -2 * self.m1 - 2 * self.m2 <= distancex <= 0 and xcheck:
                if -2 * self.m1 - 2 * self.m2 <= distancey <= 0:
                    self.v1x = (self.m1 -
                                self.m2) / (self.m1 + self.m2) * u1x + (
                                    2 * self.m2) / (self.m1 + self.m2) * u2x
                    self.v2x = (self.m2 -
                                self.m1) / (self.m1 + self.m2) * u2x + (
                                    2 * self.m1) / (self.m1 + self.m2) * u1x

            if win.checkMouse():
                win.close()

            sleep(0.01)