def __init__(self):
        self.pub_player1 = rospy.Publisher('airhockey/simulator/player1', Twist, queue_size=60)
        self.pub_player2 = rospy.Publisher('airhockey/simulator/player2', Twist, queue_size=60)
        self.vel_player1 = 0, 0
        self.vel_player2 = 0, 0
        self.pub_image = rospy.Publisher('/airhockey/simulator/image', ImageMsg, queue_size=60)
        self.bridge = CvBridge()

        self.space = pymunk.Space()
        self.space.gravity = (0.0, 0.0)

        self.root = tk.Tk()
        self.root.title('Airhockey')
        self.root.resizable(width=False, height=False)
        self.root.geometry("{}x{}+{}+{}".format(1595, 1000, 0, 0))
        self.root.bind("<Escape>", lambda e: self.root.quit())
        #self.root.bind('<Motion>', self.mouse_position)

        self.field_image = Image.open(os.path.join(self.dir, '../res', 'field.png'))

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 40), (1595, 40), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 960), (1595, 960), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (40, 0), (40, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (1550, 0), (1550, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.player1_object = Pod(200, 500, 100, 3, 'player1', 'airhockey/simulator/player1')
        self.player2_object = Pod(1390, 500, 100, 3, 'player2', 'airhockey/simulator/player2')
        self.puck = Puck(795, 500, 60, 1)

        self.space.add(self.player1_object.body, self.player1_object.shape)
        self.space.add(self.player2_object.body, self.player2_object.shape)
        self.space.add(self.puck.body, self.puck.shape)

        self.field = ImageTk.PhotoImage(self.get_field_image(self.player1_object, self.player2_object, self.puck))

        self.canvas = tk.Canvas(self.root, width=1590, height=1000)
        self.canvas.pack()

        self.root.bind_all('<KeyPress>', self.key_pressed)
        self.root.bind_all('<KeyRelease>', self.key_released)

        self.root.after(int(round(1000 / self.FPS, 0)), func=self.tick)
示例#2
0
    def reset(self):
        self.animating = False
        if self.draw:
            self.clock = pygame.time.Clock()

        self.table  = Rect(50, 50, self.width-50, self.height-50)
        self.center_y = (self.table.y1 + self.table.y2) / 2
        self.puck = Puck(self.width/2, 0.75 * self.height, 20, pygame.Color('red'))
        self.striker = Striker(self.width/2, 0.25 * self.height, 40, pygame.Color('blue'))
        self.collide_rect = self.table.collide_rect(self.puck)
示例#3
0
 def create_puck(self, pos, immobile=False):
     puck = Puck(choice(self.puck_kinds),
                 self.puck_shape,
                 immobile=immobile)
     puck.body.position = pos
     self.env.add(puck.body, puck.shape)
     self.pucks.append(puck)
     return puck
class GameSpace:
	#Set up gamespace
        def setup(self):
                pygame.init()
                self.size=self.width,self.height=1250,600
                self.black=0,0,0
                self.player1=None
                self.player2=None
                self.b_run = 1
                self.puck=Puck(self)
                self.p1score=0
                self.p2score=0	
		self.scoretimer=SCORE_TIME+1 #determines how long to show score message
		self.win=0 #indicates if a player has won
		self.winscore=7 #score needed to win

	#Add player 1 to game
        def addPlayer1(self):
                self.player1=Player(self,1)

	#Add player 2 to game
        def addPlayer2(self):
                self.player2=Player(self,2)

	#Increase score after a goal
        def updateScore(self,p1,p2):
                self.p1score+=p1
                self.p2score+=p2
                print "P1: "+str(self.p1score)+" P2: "+str(self.p2score)
		self.scoretimer=0
		if self.p1score==self.winscore:
			self.win=1
		elif self.p2score==self.winscore:
			self.win=2
		self.puck.reset()

	#Iterate - tick game objects
        def gameLoop(self, p1data, p2data):
		self.scoretimer+=1
                if self.player1!=None:
                        self.player1.tick(p1data)
                if self.player2!=None:
                        self.player2.tick(p2data)
                self.puck.tick()
示例#5
0
    def create_pucks_random(self):
        for i in range(self.number_pucks):
            puck = Puck(choice(self.puck_kinds), self.puck_shape)
            #offset = int(self.wall_thickness + puck.radius)
            offset = int(puck.radius)
            placed = False
            while not placed:
                puck.body.position = self.get_random_pos_within_border(offset)
                if self.env.shape_query(puck.shape) == []:
                    placed = True
            self.env.add(puck.body, puck.shape)

            self.pucks.append(puck)
示例#6
0
 def create_pucks_random(self):
     for i in range(self.number_pucks):
         puck = Puck(choice(self.puck_kinds))
         offset = int(self.wall_thickness + puck.radius)
         placed = False
         while not placed:
             x = randint(offset, self.width - offset)
             y = randint(offset, self.height - offset)
             puck.body.position = x, y
             if self.env.shape_query(puck.shape) == []:
                 placed = True
         self.env.add(puck.body, puck.shape)
         self.pucks.append(puck)
        def setup(self):
                pygame.init()
                self.size=self.width,self.height=1250,600
                self.black=0,0,0
                self.player1=None
                self.player2=None
                self.b_run = 1
                self.puck=Puck(self)
                self.p1score=0
                self.p2score=0	
		self.scoretimer=SCORE_TIME+1 #determines how long to show score message
		self.win=0 #indicates if a player has won
		self.winscore=7 #score needed to win
示例#8
0
from paddle import Paddle
from puck import Puck
from score import Score

# Setting up screen.
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)

# Creating up game objects.
p1_paddle = Paddle(-350, 0)
p2_paddle = Paddle(350, 0)
score = Score()
puck = Puck()

# Accepting user input.
screen.onkeypress(p1_paddle.move_up, "w")
screen.onkeypress(p1_paddle.move_down, "s")
screen.onkeypress(p2_paddle.move_up, "Up")
screen.onkeypress(p2_paddle.move_down, "Down")
screen.listen()

# Game loop
run = True
while run:
    time.sleep(puck.acceleration)
    screen.update()
    puck.move()
示例#9
0
from puck import Puck, api_response, request, session


app = Puck(redis_host='127.0.0.1', redis_port=6379)


@app.after_request
def after(response):
    response.set_cookies('heihei', 'this is a test!', expires=2000000111)
    return response


@app.route('/', methods=['GET'])
def index():
    session['haha'] = 'asdfasdf'
    return api_response(data=session.data, message='this is the session.')


if __name__ == '__main__':
    app.run()
示例#10
0
import sys
from pygame.locals import *
from paddle import Paddle
from puck import Puck
from startScreen import air_hockey_start, disp_text
from themeScreen import theme_screen
from globals import *
from endScreen import game_end

# Globals, initialized in method `init()`

# Create game objects.
paddle1 = Paddle(const.PADDLE1X, const.PADDLE1Y)
paddle2 = Paddle(const.PADDLE2X, const.PADDLE2Y)
puck = Puck(width / 2, height / 2)


def init():
    global paddleHit, goal_whistle, clock, screen, smallfont, roundfont
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.mixer.init()
    pygame.init()

    gamelogo = pygame.image.load(os.path.join(auxDirectory, 'AHlogo.png'))
    pygame.display.set_icon(gamelogo)
    pygame.display.set_caption('Air Hockey')
    screen = pygame.display.set_mode((width, height))

    paddleHit = pygame.mixer.Sound(os.path.join(auxDirectory, 'hit.wav'))
    goal_whistle = pygame.mixer.Sound(os.path.join(auxDirectory, 'goal.wav'))
示例#11
0
def run(amount, puck_radius, mass):
    pygame.init()

    # Set the name of the window
    pygame.display.set_caption("Puck Game")

    clock = pygame.time.Clock()

    for puck_amount in range(amount):
        # if puck_amount > 0 and puck_amount % 5 == 0:
        #     puck_radius = puck_radius - 5

        if PUCKS:
            puck_placed = False
            no_pucks = True
            while not puck_placed:
                x_position = (round(random.randint(puck_radius + 5, (WINDOW_PARAMETERS[0] - puck_radius - 5))))
                y_position = (round(random.randint(puck_radius + 5, (WINDOW_PARAMETERS[1] - puck_radius - 5))))

                p1_position = [x_position, y_position]
                for puck in PUCKS:
                    distX = abs(p1_position[0] - puck.position[0])
                    distY = abs(p1_position[1] - puck.position[1])
                    if pythagoras(distX, distY) <= puck.radius + puck_radius:
                        print("New Puck placed at same position as: " + puck.name)
                        no_pucks = False
                if no_pucks:
                    PUCKS.append(Puck(position=p1_position, radius=puck_radius, number=puck_amount, mass=mass))
                    puck_placed = True
                no_pucks = True
        else:
            x_position = (round(random.randint(puck_radius + 5, (WINDOW_PARAMETERS[0] - puck_radius - 5))))
            y_position = (round(random.randint(puck_radius + 5, (WINDOW_PARAMETERS[1] - puck_radius - 5))))
            p1_position = [x_position, y_position]
            PUCKS.append(
                Puck(position=p1_position, radius=puck_radius, number=puck_amount, mass=mass, color=[255, 255, 255]))

    # User exit boolean
    done = False

    while not done:
        clock.tick(FPS_FOR_TIMER)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                pass
                if event.key == pygame.K_UP:
                    PUCKS[0].force[1] = -1.0
                if event.key == pygame.K_DOWN:
                    PUCKS[0].force[1] = 1.0
                if event.key == pygame.K_LEFT:
                    PUCKS[0].force[0] = -1.0
                if event.key == pygame.K_RIGHT:
                    PUCKS[0].force[0] = 1.0
                if event.key == pygame.K_SPACE:
                    for puck in PUCKS:
                        puck.force[0] = round(random.randint(-10, 10))
                        puck.force[1] = round(random.randint(-10, 10))

        SCREEN.fill(BLACK)  # Clear screen on frame start, then build arena walls
        pygame.draw.rect(SCREEN, ORANGE, [0, 0, WINDOW_PARAMETERS[0], WINDOW_PARAMETERS[1]], 10)

        # Process each created object
        for p in PUCKS:
            p.frame_process()
            # print(p.stats())  # Used for debugging, prints all Puck parameters
            p.draw()

        pygame.display.flip()
示例#12
0
class Simulation:
    def __init__(self, width, height, camera, draw=True):
        self.width = width
        self.height = height
        self.draw = draw
        self.camera = camera

        if self.draw:
            pygame.init()
            self.screen = pygame.display.set_mode((width, height))
            pygame.display.set_caption("Simulation")
        self.reset()

    def reset(self):
        self.animating = False
        if self.draw:
            self.clock = pygame.time.Clock()

        self.table  = Rect(50, 50, self.width-50, self.height-50)
        self.center_y = (self.table.y1 + self.table.y2) / 2
        self.puck = Puck(self.width/2, 0.75 * self.height, 20, pygame.Color('red'))
        self.striker = Striker(self.width/2, 0.25 * self.height, 40, pygame.Color('blue'))
        self.collide_rect = self.table.collide_rect(self.puck)

    def handle_events(self):
        if self.draw:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                # if event.type == pygame.KEYDOWN:
                #     if event.key == 32:
                #         self.animating = True

    def run(self, iterations=1):
        self.done = False

        for _ in range(iterations):
            if self.done:
                break

            self.handle_events()
            if self.draw:
                self.screen.fill(pygame.Color('white'))
                self.table.draw(self.screen)

            self.puck.vel = self.camera.puck['pos'] - self.puck.pos
            self.puck.pos = self.camera.puck['pos']
            print(self.puck.vel)
            self.striker.pos = self.camera.striker['pos']
            self.table = Rect(self.camera.table['min_x'], self.camera.table['min_y'],
                                self.camera.table['max_x'], self.camera.table['max_y'])
            self.puck.update(self)
            #self.striker.update(self)

            if self.draw:
                pygame.display.flip()

        return self.striker.vel

    def quit(self):
        if self.draw:
            pygame.quit()
示例#13
0
# Constants
WIDTH = 600
HEIGHT = 480
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# window setup
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen_rect = screen.get_rect()
pygame.display.set_caption("Old School Pong")
clock = pygame.time.Clock()

# create a puck
puck = Puck(WIDTH, HEIGHT, screen)

# create 2 paddles
left = Paddle(screen, HEIGHT, WIDTH, RED, True)
right = Paddle(screen, HEIGHT, WIDTH, GREEN, False)


def draw():
    # black background
    screen.fill(BLACK)

    # show the 2 paddles on window
    left.show()
    right.show()

    # move the puck around the window
示例#14
0
    def run(self):

        self.scoreboard.reset_score()

        width = self.screen.get_rect().width
        height = self.screen.get_rect().height

        # create objects and data parameters
        puck = Puck(width, height, self.puck_speed, 10)
        left_paddle = Paddle(30, height, self.paddle_speed, self.paddle_length)
        right_paddle = Paddle(680, height, self.paddle_speed,
                              self.paddle_length)

        clock = pygame.time.Clock()
        mixer.init()
        sound = mixer.Sound('boop_sound.ogg')
        music = mixer.Sound('8-bit-music.ogg')

        if Settings.music:
            music.play(loops=-1)

        if Settings.special == 'WALL':
            self.special = Wall(self.screen.get_rect().width,
                                self.screen.get_rect().height)
        elif Settings.special == 'BOOST':
            self.special = Boost(self.screen.get_rect().width,
                                 self.screen.get_rect().height)
        elif Settings.special == 'COIN':
            self.special = Coin(self.screen.get_rect().width,
                                self.screen.get_rect().height)
        else:
            self.special = NoSpecial(self.screen.get_rect().width,
                                     self.screen.get_rect().height)

        game_playing = True
        end_state = False
        replay = False

        # game loop
        while game_playing:
            clock.tick(60)

            # if either score reaches 11, then stop gameplay
            if self.scoreboard.left_score > 10 or self.scoreboard.right_score > 10:
                game_playing = False
                end_state = True

            # close application when cross is pressed
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            # bot player controls
            puck_centre = puck.y + puck.side_length / 2
            paddle_centre = left_paddle.y + left_paddle.length / 2

            if puck_centre > paddle_centre:
                left_paddle.move_down()
            if puck_centre < paddle_centre:
                left_paddle.move_up()

            # human player controls
            # check events to move paddle up or down (downkey pressed, upkey pressed)
            keys = pygame.key.get_pressed()
            if keys[pygame.K_DOWN]:
                right_paddle.move_down()
            if keys[pygame.K_UP]:
                right_paddle.move_up()
            # check events to exit gameplay
            if keys[pygame.K_ESCAPE]:
                game_playing = False

            # reset the screen to black
            self.screen.fill(Settings.background_colour)
            # show objects
            puck.show(self.screen, self.scoreboard)
            left_paddle.show(self.screen)
            right_paddle.show(self.screen)
            self.special.show(self.screen)
            self.scoreboard.show()
            # update the screen
            display.flip()

            # puck changes direction if it collides with left or right paddle
            if puck.collides_with(left_paddle):
                puck.change_x_direction('right')
                if Settings.sound_effects:
                    sound.play()
            elif puck.collides_with(right_paddle):
                puck.change_x_direction('left')
                if Settings.sound_effects:
                    sound.play()

            if self.special.collides_with(puck, self.scoreboard):
                self.special.perform_action(puck, self.scoreboard)

        # certificate screen
        while end_state:
            clock.tick(10)

            self.screen.fill(Settings.background_colour)
            self.scoreboard.show_end_state()

            # on certificate display instructions to replay or return to menu
            font_small = font.Font(pygameMenu.fonts.FONT_MUNRO, 20)
            font_large = font.Font(pygameMenu.fonts.FONT_MUNRO, 30)
            level = font_large.render(
                'Level: ' + self.level + ' (' + str(self.special) + ')',
                True,
                Settings.text_colour,
            )
            instructions = font_small.render(
                'press R to replay or ESC to go back',
                True,
                Settings.text_colour,
            )
            screen_width = self.screen.get_rect().width
            screen_height = self.screen.get_rect().height
            level_width = level.get_rect().width
            level_height = level.get_rect().height
            instructions_width = instructions.get_rect().width
            instructions_height = instructions.get_rect().height
            self.screen.blit(level, (screen_width / 2 - level_width / 2,
                                     screen_height / 2 - level_height * 6))
            self.screen.blit(instructions,
                             (screen_width / 2 - instructions_width / 2,
                              screen_height / 2 + instructions_height * 5))

            display.flip()

            events = pygame.event.get()
            for event in events:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        end_state = False
                    if event.key == pygame.K_r:
                        end_state = False
                        replay = True
                if event.type == pygame.QUIT:
                    sys.exit()

        music.stop()
        if replay:
            self.run()
示例#15
0
# -*- coding: utf-8 -*-
from puck import Puck, api_response
from puck.restful import Param, RequestParamParser
from puck.restful import variable_parser


class Student(RequestParamParser):
    name = Param('name', str, required=True)
    age = Param('age', int, required=True)
    sex = Param('sex', int, required=True)
    address = Param('address', str)


app = Puck(use_api=True)


class StudentAPI(object):

    @variable_parser(Student)
    def post(self, i):
        variable_data = getattr(self, 'variable_data')
        return api_response(data=variable_data)

app.add_route('/stu/<int:i>', resource=StudentAPI())


if __name__ == '__main__':
    app.run()
class AirhockeyScreen:
    dir = os.path.dirname(__file__)
    FPS = 60.0

    player1_keys = ['d', 'q', 'z', 's']
    player2_keys = ['Right', 'Left', 'Up', 'Down']

    score = {'player_1': 0, 'player_2': 0}

    def __init__(self):
        self.pub_player1 = rospy.Publisher('airhockey/simulator/player1', Twist, queue_size=60)
        self.pub_player2 = rospy.Publisher('airhockey/simulator/player2', Twist, queue_size=60)
        self.vel_player1 = 0, 0
        self.vel_player2 = 0, 0
        self.pub_image = rospy.Publisher('/airhockey/simulator/image', ImageMsg, queue_size=60)
        self.bridge = CvBridge()

        self.space = pymunk.Space()
        self.space.gravity = (0.0, 0.0)

        self.root = tk.Tk()
        self.root.title('Airhockey')
        self.root.resizable(width=False, height=False)
        self.root.geometry("{}x{}+{}+{}".format(1595, 1000, 0, 0))
        self.root.bind("<Escape>", lambda e: self.root.quit())
        #self.root.bind('<Motion>', self.mouse_position)

        self.field_image = Image.open(os.path.join(self.dir, '../res', 'field.png'))

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 40), (1595, 40), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (0, 960), (1595, 960), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (40, 0), (40, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.static_line = pymunk.Segment(self.static_body, (1550, 0), (1550, 1000), 0.0)
        self.static_line.elasticity = 1
        self.space.add(self.static_body, self.static_line)

        self.player1_object = Pod(200, 500, 100, 3, 'player1', 'airhockey/simulator/player1')
        self.player2_object = Pod(1390, 500, 100, 3, 'player2', 'airhockey/simulator/player2')
        self.puck = Puck(795, 500, 60, 1)

        self.space.add(self.player1_object.body, self.player1_object.shape)
        self.space.add(self.player2_object.body, self.player2_object.shape)
        self.space.add(self.puck.body, self.puck.shape)

        self.field = ImageTk.PhotoImage(self.get_field_image(self.player1_object, self.player2_object, self.puck))

        self.canvas = tk.Canvas(self.root, width=1590, height=1000)
        self.canvas.pack()

        self.root.bind_all('<KeyPress>', self.key_pressed)
        self.root.bind_all('<KeyRelease>', self.key_released)

        self.root.after(int(round(1000 / self.FPS, 0)), func=self.tick)

    def tick(self):
        self.player1_object.move()
        self.player2_object.move()
        self.space.step(1 / self.FPS)
        self.render()
        self.puck.check_goal(self.score)
        self.root.after(int(round(1000 / self.FPS, 0)), func=self.tick)

    def render(self):
        self.canvas.delete('all')
        image = self.get_field_image(self.player1_object, self.player2_object, self.puck)
        field = ImageTk.PhotoImage(image)
        self.canvas.create_image((795, 500), image=field)
        self.canvas.image = field
        self.canvas.create_text(799, 75, fill='darkblue', font='Times 80 bold',
                                text='{}:{}'.format(self.score['player_1'], self.score['player_2']))
        """
        Subscribe to this topic to analyze the board in ROS with OpenCV
        To move the player publish a message of geometry_msgs.msg.Twist to /airhockey/player1 or /airhockey/player2.
        """
        self.pub_image.publish(self.bridge.cv2_to_imgmsg(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR), 'bgr8'))

    def get_field_image(self, *args):
        img_to_show = Image.new('RGB', (1590, 1000), color=(255, 255, 255, 1))
        img_to_show.paste(self.field_image, (0, 0), self.field_image)
        for game_object in args:
            img_to_show.paste(game_object.image, (game_object.get_position()), game_object.image)
        return img_to_show

    def mouse_position(self, event):
        pos_x, pos_y = event.x, event.y
        self.player1_object.set_position(pos_x, pos_y)

    def key_pressed(self, event):
        motion_command = Twist()
        if event.keysym in self.player1_keys:
            velocity = self.get_velocity(event, self.vel_player1)
            self.vel_player1 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player1.publish(motion_command)
        elif event.keysym in self.player2_keys:
            velocity = self.get_velocity(event, self.vel_player2)
            self.vel_player2 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player2.publish(motion_command)

    def key_released(self, event):
        motion_command = Twist()
        if event.keysym in self.player1_keys:
            velocity = self.reset_velocity(event, self.vel_player1)
            self.vel_player1 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player1.publish(motion_command)
        elif event.keysym in self.player2_keys:
            velocity = self.reset_velocity(event, self.vel_player2)
            self.vel_player2 = velocity
            motion_command.linear.x = velocity[0]
            motion_command.linear.y = velocity[1]
            self.pub_player2.publish(motion_command)

    def get_velocity(self, event, velocity):
        _vel_x, _vel_y = velocity
        if 'Right' == event.keysym or event.keysym  == 'd':
            _vel_x = 15
        elif 'Left' == event.keysym or event.keysym == 'q':
            _vel_x = -15
        elif 'Up' == event.keysym or event.keysym == 'z':
            _vel_y = -15
        elif 'Down' == event.keysym or event.keysym == 's':
            _vel_y = 15
        return _vel_x, _vel_y

    def reset_velocity(self, event, velocity):
        _vel_x, _vel_y = velocity
        if 'Right' == event.keysym or event.keysym == 'd' or 'Left' == event.keysym or event.keysym == 'q':
            _vel_x = 0
        elif 'Up' == event.keysym or event.keysym == 'z' or 'Down' == event.keysym or event.keysym == 's':
            _vel_y = 0
        return _vel_x, _vel_y
示例#17
0
import pyglet

from puck import Puck
from paddle import Paddle
from pyglet.window import key, mouse, Window

window = Window(width=1000, height=1000, resizable=True)
keys = key.KeyStateHandler()
puck = Puck(window)
player1 = Paddle(window, left=True)
player2 = Paddle(window, left=False)
players = player1, player2


def update(dt):
    window.clear()

    player1.draw()
    player1.update()
    player1.keep_in_bounds()

    player2.draw()
    player2.update()
    player2.keep_in_bounds()

    [puck.check_collision(player) for player in players]
    puck.draw()
    puck.update()

    player1.score = pyglet.text.Label(text=str(puck.get_score('player1')),
                                      font_name='Times New Roman',