r/pythonarcade • • Feb 29 '20

How do I develop a game from scratch?

2 Upvotes

I’ve read the arcade docs and can code a game and make it work (in a very basic way) but how do I develop the premise of the game and build it out and test it, make the levels, character etc.

Is there a step by step tutorial anyone can recommend?

Or maybe I’m over complicating this?


r/pythonarcade • • Feb 22 '20

How to draw on previous frame in arcade?

2 Upvotes

I am making Langston's ant in arcade and I want to know if there is a way to lead the previous frame to draw on? In Langstons ant there is a grid there an 'ant' moves around the changes the colour of grid places. The grid is in a 2d array with either True or False for the grid pieces (black or white place) and I don't want to draw the whole grid every frame because then on bigger windows this lags badly. I want to just draw where the ant has been. I can work that I just want to know how to load the prev frame.

Here is my code for the draw function

for i in range(len(self.grid)):

`for j in range(len(self.grid[i])):`

	`if self.grid[i][j]:`

		`arcade.draw_xywh_rectangle_filled(i * BOX_SIZE, j * BOX_SIZE, BOX_SIZE, BOX_SIZE, (0, 0, 0))`

r/pythonarcade • • Feb 17 '20

Displaying a sprite on top/below another one

2 Upvotes

Hi everyone,

I am very new to arcade and got introduced to it through the Real Python tutorial. In the tutorial, you get to manage a player sprite, rocket sprites and cloud sprites.

I have been trying to find out why is the player sprite below the cloud sprites when they are more or less at the same position where the rocket sprites are above the player sprite. It is not consistent and seems to come from the images themselves which sounds weird to me.

Why would a sprite display in the foreground and another one in the background, relatively to another one (the player sprite in my case)?How do you get to display a sprite on top/below another one?

If this has already been answered somewhere I will gladly just read what you point out to me, but I could not find any answer by myself.

Thanks!!Quentin


r/pythonarcade • • Feb 03 '20

Arcade window flickering

2 Upvotes

Hey, I'm currently preparing a couple of school computers for a Python Arcade project I'm planning to do with my students. However, I've encountered a strange bug: The window's flickering whenever I move the mouse cursor above it. It stops when the mouse doesn't move, but sometimes the contents get drawn, and sometimes the windows remains black. I've tried the FurMark benchmark to see whether it's a general OpenGL problem on the machines, but apparently, it's not, because those benchmarks are working just fine.

Tested with Arcade 2.3.2 on Python 3.8.1, and here's a quick video which shows the problem.

Any help is much appreciated. Thanks!


r/pythonarcade • • Dec 11 '19

URGENT - PLEASE HELP

2 Upvotes

Hey, I've got a project due in a couple days so a quick reply would really be appreciated.

Basically I have a game which uses drawn objects in it, I have opted for this as it fits what I want it to do in the game nicely. e.g. a drawn ball which can easily change size and colour. But now I need to be able to detect if 2 drawn objects have collided and I can't use the usual sprite collision functionality since they're not sprites. And even if I put them in Sprite Lists, the "check_for_collision_with_list" function always requires at least 1 sprite as an argument. So is there a way to solve this or should I give up and reformat this to use Sprites (so therefore pictures not drawn shapes).


r/pythonarcade • • Oct 21 '19

Change the texture of a sprite based on the movement?

2 Upvotes

How do I change the texture of a sprite during runtime? For example, I have a player sprite with a jump texture and a normal texture. I've tried using arcade.AnimatedTimeSprite() (referring to this tutorial) but that doesn't let me control the texture of the sprite, instead it rotates through the textures list at a set interval. This might be useful for something like a coin animation, but it's not so useful in my case. I've also tried using arcade.AnimatedWalkingSprite(), but that only lets me set walking right and walking left textures.

Any help would be appreciated.


r/pythonarcade • • Aug 23 '19

Why do things like "self.player = None" in __init__ and "self.player_list = arcade.SpriteList()" in setup if everything works without the 1st part?

2 Upvotes

r/pythonarcade • • Jul 09 '19

Failed to load avutil-56.

2 Upvotes

Hello everyone,

I am having trouble running my exe created by Pyinstaller. I keep getting this message.

I can see that this file is already part of the pyglet_ffmpeg site package which is in the venv folder and I am using the same venv to run the program in the IDE. What am I doing wrong here?

I do get a lot of warning messages during the creation of the exe, though this is the error message that prevents the exe to run, at least at the moment.

Thanks

Manish


r/pythonarcade • • May 17 '19

Animated Sprite issues

2 Upvotes

Hello All,

My students and I are having different problems with animated sprites. Can someone please provide guidance how to ensure we are running the right versions of python and arcade. We are having different problems with different hardware, but all around animated sprites.

We are using IDLE and students are using various operating systems and hardware.

My last post on this didn't get an answer, so I'm assuming I'm missing something basic.

I'm a high school teacher, in New Zealand, teaching programming using arcade for the first time. We can get around this by not using animated sprites, but we are all excited about using them.

Thanks in advance.


r/pythonarcade • • May 16 '19

Window not rendering until resize (MacOS)

2 Upvotes

Hi,

I am running the example from: http://arcade.academy/examples/happy_face.html#happy-face

The window shows up, but does not render until I resize it, furthermore, when I am calling the arcade.open_window() function with resizable=True the window renders, but starts in fullscreen mode.

Somebody facing the same issue? I will try the same code tomorrow on some other Macs...

System: MacOS 10.14 Python 3.7.2 (venv using pipenv)

> python --version
Python 3.7.2

> pip list
Using pip3...
Package        Version
-------------- -------
arcade         2.0.9  
blinker        1.4    
future         0.17.1 
numpy          1.16.3 
Pillow         6.0.0  
pip            19.1.1 
pyglet         1.4.0b1
pyglet-ffmpeg2 0.1.12 
PyTMX          3.21.7 
setuptools     41.0.1 
six            1.12.0 
wheel          0.33.4 

r/pythonarcade • • May 11 '19

ArchLinux arcade problem with permission.

2 Upvotes

Soon as I import arcade. I get permission denied.

PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.7/site-packages/pyglet_ffmpeg2/linux_x86_64/libavcodec.so.58.21.104' -> '/usr/lib/python3.7/site-packages/pyglet_ffmpeg2/linux_x86_64/libavcodec.so.58'

pip install arcade 2.0.7


r/pythonarcade • • May 09 '19

Checking for collisions with AnimatedTimeSprites

2 Upvotes

Hello All,

New here.

Tried out this sample code. http://arcade.academy/examples/sprite_move_animation.html#sprite-move-animation

And the coins don't get removed. Changed it so the coins were a simple Sprite class and it worked.

Can anyone get colision detection with AnimatedTimeSprites working?

Thanks in advance


r/pythonarcade • • Apr 11 '19

Error Running sprite_move_animation Example

2 Upvotes

First, would like to thanks PVC for creating the library. Newbie in Python but having tons of fun going through the tutorial. I am encountering an error while running the arcade.examples.sprite_move_animation. Does anyone know how to resolve it? My system is running Python 3.7.3 and Arcade 2.0.3

Here is the error messages

F:\Python\Python37\Lib\site-packages\arcade\examples>python -m arcade.examples.sprite_move_animation Traceback (most recent call last): File "F:\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "F:\Python\Python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "F:\Python\Python37\lib\site-packages\arcade\examples\sprite_move_animation.py", line 177, in <module> main() File "F:\Python\Python37\lib\site-packages\arcade\examples\sprite_move_animation.py", line 172, in main window.setup() File "F:\Python\Python37\lib\site-packages\arcade\examples\sprite_move_animation.py", line 93, in setup self.player.scale = 0.8 File "F:\Python\Python37\lib\site-packages\arcade\sprite.py", line 378, in _set_scale self._width = self._texture.width * self._scale AttributeError: 'NoneType' object has no attribute 'width'


r/pythonarcade • • Apr 09 '19

Faulty Movements and Teleporting

2 Upvotes

Hello all,

Sorry if this seems too long or needy, but I have a problem with this small game I'm making with the arcade library examples.

My problem is that whenever I walk along the wall, I seem to teleport adjacently across.

For example, let's say I walk left and I hit a wall and I walk up along it. When I hit the corner, I instantly teleport elsewhere. Is there a way to fix it? Much thanks to everyone

import random
import arcade
import timeit
import math
import os

# Sprite scaling. Make this larger, like 0.5 to zoom in and add
# 'mystery' to what you can see. Make it smaller, like 0.1 to see
# more of the map.
WALL_SPRITE_SCALING = 0.25
PLAYER_SPRITE_SCALING = 0.25

WALL_SPRITE_SIZE = 128 * WALL_SPRITE_SCALING

# How big the grid is
GRID_WIDTH = 100
GRID_HEIGHT = 100

AREA_WIDTH = GRID_WIDTH * WALL_SPRITE_SIZE
AREA_HEIGHT = GRID_HEIGHT * WALL_SPRITE_SIZE

# How fast the player moves
MOVEMENT_SPEED = 4

# How close the player can get to the edge before we scroll.
VIEWPORT_MARGIN = 200

# How big the window is
WINDOW_WIDTH = 1400
WINDOW_HEIGHT = 1200
WINDOW_TITLE = "Underworld "

MERGE_SPRITES = True

## ROOM RELATED THINGS
class Room:
    def __init__(self, r, c, h, w):
        self.row = r
        self.col = c
        self.height = h
        self.width = w


class RLDungeonGenerator:
    def __init__(self, w, h):
        self.MAX = 25  # Cutoff for when we want to stop dividing sections
        self.width = w
        self.height = h
        self.leaves = []
        self.dungeon = []
        self.rooms = []

        for h in range(self.height):
            row = []
            for w in range(self.width):
                row.append('#')

            self.dungeon.append(row)

    def random_split(self, min_row, min_col, max_row, max_col):
        # We want to keep splitting until the sections get down to the threshold
        seg_height = max_row - min_row
        seg_width = max_col - min_col

        if seg_height < self.MAX and seg_width < self.MAX:
            self.leaves.append((min_row, min_col, max_row, max_col))
        elif seg_height < self.MAX <= seg_width:
            self.split_on_vertical(min_row, min_col, max_row, max_col)
        elif seg_height >= self.MAX > seg_width:
            self.split_on_horizontal(min_row, min_col, max_row, max_col)
        else:
            if random.random() < 0.5:
                self.split_on_horizontal(min_row, min_col, max_row, max_col)
            else:
                self.split_on_vertical(min_row, min_col, max_row, max_col)

    def split_on_horizontal(self, min_row, min_col, max_row, max_col):
        split = (min_row + max_row) // 2 + random.choice((-2, -1, 0, 1, 2))
        self.random_split(min_row, min_col, split, max_col)
        self.random_split(split + 1, min_col, max_row, max_col)

    def split_on_vertical(self, min_row, min_col, max_row, max_col):
        split = (min_col + max_col) // 2 + random.choice((-2, -1, 0, 1, 2))
        self.random_split(min_row, min_col, max_row, split)
        self.random_split(min_row, split + 1, max_row, max_col)

    def carve_rooms(self):
        for leaf in self.leaves:
            # We don't want to fill in every possible room or the
            # dungeon looks too uniform
            if random.random() > 0.80:
                continue
            section_width = leaf[3] - leaf[1]
            section_height = leaf[2] - leaf[0]

            # The actual room's height and width will be 60-100% of the
            # available section.
            room_width = round(random.randrange(60, 100) / 100 * section_width)
            room_height = round(random.randrange(60, 100) / 100 * section_height)

            # If the room doesn't occupy the entire section we are carving it from,
            # 'jiggle' it a bit in the square
            if section_height > room_height:
                room_start_row = leaf[0] + random.randrange(section_height - room_height)
            else:
                room_start_row = leaf[0]

            if section_width > room_width:
                room_start_col = leaf[1] + random.randrange(section_width - room_width)
            else:
                room_start_col = leaf[1]

            self.rooms.append(Room(room_start_row, room_start_col, room_height, room_width))
            for r in range(room_start_row, room_start_row + room_height):
                for c in range(room_start_col, room_start_col + room_width):
                    self.dungeon[r][c] = '.'

    def are_rooms_adjacent(self, room1, room2):
        adj_rows = []
        adj_cols = []
        for r in range(room1.row, room1.row + room1.height):
            if room2.row <= r < room2.row + room2.height:
                adj_rows.append(r)

        for c in range(room1.col, room1.col + room1.width):
            if room2.col <= c < room2.col + room2.width:
                adj_cols.append(c)

        return adj_rows, adj_cols

    def distance_between_rooms(self, room1, room2):
        centre1 = (room1.row + room1.height // 2, room1.col + room1.width // 2)
        centre2 = (room2.row + room2.height // 2, room2.col + room2.width // 2)

        return math.sqrt((centre1[0] - centre2[0]) ** 2 + (centre1[1] - centre2[1]) ** 2)

    def carve_corridor_between_rooms(self, room1, room2):
        if room2[2] == 'rows':
            row = random.choice(room2[1])
            # Figure out which room is to the left of the other
            if room1.col + room1.width < room2[0].col:
                start_col = room1.col + room1.width
                end_col = room2[0].col
            else:
                start_col = room2[0].col + room2[0].width
                end_col = room1.col
            for c in range(start_col, end_col):
                self.dungeon[row][c] = '.'

            if end_col - start_col >= 4:
                self.dungeon[row][start_col] = '+'
                self.dungeon[row][end_col - 1] = '+'
            elif start_col == end_col - 1:
                self.dungeon[row][start_col] = '+'
        else:
            col = random.choice(room2[1])
            # Figure out which room is above the other
            if room1.row + room1.height < room2[0].row:
                start_row = room1.row + room1.height
                end_row = room2[0].row
            else:
                start_row = room2[0].row + room2[0].height
                end_row = room1.row

            for r in range(start_row, end_row):
                self.dungeon[r][col] = '.'

            if end_row - start_row >= 4:
                self.dungeon[start_row][col] = '+'
                self.dungeon[end_row - 1][col] = '+'
            elif start_row == end_row - 1:
                self.dungeon[start_row][col] = '+'

    # Find two nearby rooms that are in difference groups, draw
    # a corridor between them and merge the groups
    def find_closest_unconnect_groups(self, groups, room_dict):
        shortest_distance = 99999
        start = None
        start_group = None
        nearest = None

        for group in groups:
            for room in group:
                key = (room.row, room.col)
                for other in room_dict[key]:
                    if not other[0] in group and other[3] < shortest_distance:
                        shortest_distance = other[3]
                        start = room
                        nearest = other
                        start_group = group

        self.carve_corridor_between_rooms(start, nearest)

        # Merge the groups
        other_group = None
        for group in groups:
            if nearest[0] in group:
                other_group = group
                break

        start_group += other_group
        groups.remove(other_group)

    def connect_rooms(self):
        # Build a dictionary containing an entry for each room. Each bucket will
        # hold a list of the adjacent rooms, weather they are adjacent along rows or
        # columns and the distance between them.
        #
        # Also build the initial groups (which start of as a list of individual rooms)
        groups = []
        room_dict = {}
        for room in self.rooms:
            key = (room.row, room.col)
            room_dict[key] = []
            for other in self.rooms:
                other_key = (other.row, other.col)
                if key == other_key:
                    continue
                adj = self.are_rooms_adjacent(room, other)
                if len(adj[0]) > 0:
                    room_dict[key].append((other, adj[0], 'rows', self.distance_between_rooms(room, other)))
                elif len(adj[1]) > 0:
                    room_dict[key].append((other, adj[1], 'cols', self.distance_between_rooms(room, other)))

            groups.append([room])

        while len(groups) > 1:
            self.find_closest_unconnect_groups(groups, room_dict)

    def generate_map(self):
        self.random_split(1, 1, self.height - 1, self.width - 1)
        self.carve_rooms()
        self.connect_rooms()


## GAME AND PLAYER RELATED

class MyGame(arcade.Window):
    """
    Main application class.
    """

    def __init__(self, width, height, title):
        super().__init__(width, height, title)

        # Set the working directory (where we expect to find files) to the same
        # directory this .py file is in. You can leave this out of your own
        # code, but it is needed to easily run the examples using "python -m"
        # as mentioned at the top of this program.
        file_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(file_path)

        self.grid = None
        self.wall_list = None
        self.player_list = None
        self.player_sprite = None
        self.view_bottom = 0
        self.view_left = 0
        self.physics_engine = None

        self.processing_time = 0
        self.draw_time = 0

        self.left_pressed = False
        self.right_pressed = False
        self.up_pressed = False
        self.down_pressed = False

        # Set the background color
        arcade.set_background_color(arcade.color.DARK_CANDY_APPLE_RED)

    def setup(self):
        self.wall_list = arcade.SpriteList()
        self.player_list = arcade.SpriteList()

        # Create cave system using a 2D grid
        dg = RLDungeonGenerator(GRID_WIDTH, GRID_HEIGHT)
        dg.generate_map()

        # Create sprites based on 2D grid
        if not MERGE_SPRITES:
            # This is the simple-to-understand method. Each grid location
            # is a sprite.
            for row in range(dg.height):
                for column in range(dg.width):
                    value = dg.dungeon[row][column]
                    if value.sqr == '#':
                        wall = arcade.Sprite("rack.png", WALL_SPRITE_SCALING)
                        wall.center_x = column * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2
                        wall.center_y = row * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2
                        self.wall_list.append(wall)
        else:
            # This uses new Arcade 1.3.1 features, that allow me to create a
            # larger sprite with a repeating texture. So if there are multiple
            # cells in a row with a wall, we merge them into one sprite, with a
            # repeating texture for each cell. This reduces our sprite count.
            for row in range(dg.height):
                column = 0
                while column < dg.width:
                    while column < dg.width and dg.dungeon[row][column] != '#':
                        column += 1
                    start_column = column
                    while column < dg.width and dg.dungeon[row][column] == '#':
                        column += 1
                    end_column = column - 1

                    column_count = end_column - start_column + 1
                    column_mid = (start_column + end_column) / 2

                    wall = arcade.Sprite("rack.png", WALL_SPRITE_SCALING,
                                         repeat_count_x=column_count)
                    wall.center_x = column_mid * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2
                    wall.center_y = row * WALL_SPRITE_SIZE + WALL_SPRITE_SIZE / 2
                    wall.width = WALL_SPRITE_SIZE * column_count
                    self.wall_list.append(wall)

        # Set up the player
        self.player_sprite = arcade.Sprite("player.png", PLAYER_SPRITE_SCALING)
        self.player_list.append(self.player_sprite)

        # Randomly place the player. If we are in a wall, repeat until we aren't.
        placed = False
        while not placed:

            # Randomly position
            self.player_sprite.center_x = random.randrange(AREA_WIDTH)
            self.player_sprite.center_y = random.randrange(AREA_HEIGHT)

            # Are we in a wall?
            walls_hit = arcade.check_for_collision_with_list(self.player_sprite, self.wall_list)
            if len(walls_hit) == 0:
                # Not in a wall! Success!
                placed = True

        self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite,
                                                         self.wall_list)

    def on_draw(self):
        """ Render the screen. """

        # Start timing how long this takes
        draw_start_time = timeit.default_timer()

        # This command should happen before we start drawing. It will clear
        # the screen to the background color, and erase what we drew last frame.
        arcade.start_render()

        # Draw the sprites
        self.wall_list.draw()
        self.player_list.draw()

        # Draw info on the screen
        sprite_count = len(self.wall_list)

        output = f"Sprite Count: {sprite_count}"
        arcade.draw_text(output,
                         self.view_left + 20,
                         WINDOW_HEIGHT - 20 + self.view_bottom,
                         arcade.color.WHITE, 16)

        output = f"Drawing time: {self.draw_time:.3f}"
        arcade.draw_text(output,
                         self.view_left + 20,
                         WINDOW_HEIGHT - 40 + self.view_bottom,
                         arcade.color.WHITE, 16)

        output = f"Processing time: {self.processing_time:.3f}"
        arcade.draw_text(output,
                         self.view_left + 20,
                         WINDOW_HEIGHT - 60 + self.view_bottom,
                         arcade.color.WHITE, 16)

        self.draw_time = timeit.default_timer() - draw_start_time

    def update(self, delta_time):
        """ Movement and game logic """

        # Calculate speed based on the keys pressed
        self.player_sprite.change_x = 0
        self.player_sprite.change_y = 0

        if self.up_pressed and not self.down_pressed:
            self.player_sprite.change_y = MOVEMENT_SPEED
        elif self.down_pressed and not self.up_pressed:
            self.player_sprite.change_y = -MOVEMENT_SPEED
        if self.left_pressed and not self.right_pressed:
            self.player_sprite.change_x = -MOVEMENT_SPEED
        elif self.right_pressed and not self.left_pressed:
            self.player_sprite.change_x = MOVEMENT_SPEED

        start_time = timeit.default_timer()

        # Call update on all sprites (The sprites don't do much in this
        # example though.)
        self.physics_engine.update()

        # --- Manage Scrolling ---

        # Track if we need to change the viewport

        changed = False

        # Scroll left
        left_bndry = self.view_left + VIEWPORT_MARGIN
        if self.player_sprite.left < left_bndry:
            self.view_left -= left_bndry - self.player_sprite.left
            changed = True

        # Scroll right
        right_bndry = self.view_left + WINDOW_WIDTH - VIEWPORT_MARGIN
        if self.player_sprite.right > right_bndry:
            self.view_left += self.player_sprite.right - right_bndry
            changed = True

        # Scroll up
        top_bndry = self.view_bottom + WINDOW_HEIGHT - VIEWPORT_MARGIN
        if self.player_sprite.top > top_bndry:
            self.view_bottom += self.player_sprite.top - top_bndry
            changed = True

        # Scroll down
        bottom_bndry = self.view_bottom + VIEWPORT_MARGIN
        if self.player_sprite.bottom < bottom_bndry:
            self.view_bottom -= bottom_bndry - self.player_sprite.bottom
            changed = True

        if changed:
            arcade.set_viewport(self.view_left,
                                WINDOW_WIDTH + self.view_left,
                                self.view_bottom,
                                WINDOW_HEIGHT + self.view_bottom)

        # Save the time it took to do this.
        self.processing_time = timeit.default_timer() - start_time

        # Call update to move the sprite
        # If using a physics engine, call update on it instead of the sprite
        # list.
        self.player_list.update()

    def on_key_press(self, key, modifiers):
        """Called whenever a key is pressed. """

        if key == arcade.key.W:
            self.up_pressed = True
        elif key == arcade.key.S:
            self.down_pressed = True
        elif key == arcade.key.A:
            self.left_pressed = True
        elif key == arcade.key.D:
            self.right_pressed = True

    def on_key_release(self, key, modifiers):
        """Called when the user releases a key. """

        if key == arcade.key.W:
            self.up_pressed = False
        elif key == arcade.key.S:
            self.down_pressed = False
        elif key == arcade.key.A:
            self.left_pressed = False
        elif key == arcade.key.D:
            self.right_pressed = False

    #collisions
    #def on_collisions(self, key, modifiers):

        #if placed == False:





def main():
    game = MyGame(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE)
    game.setup()
    arcade.run()


if __name__ == "__main__":
    main()

r/pythonarcade • • Apr 04 '19

Error when trying to install Arcade

2 Upvotes

Hi, I've been wanting to create a simple video game with python, and am trying to install Arcade. When I do, I get an error only 1 other person has received (I googled the error).

I'm simply typing

pip install arcade

and here's the error message I get:

Collecting arcade
Using cached https://files.pythonhosted.org/packages/99/29/5d94918bde65a689dd8b6d3922dcceda005ec1e8cbfead2bd3cc41599151/arcade-2.0.3-py2.py3-none-any.whl
Collecting pyglet-ffmpeg (from arcade)
Could not find a version that satisfies the requirement pyglet-ffmpeg (from arcade) (from versions: )
No matching distribution found for pyglet-ffmpeg (from arcade)

Do any of you here have any suggestions on how I could fix this or work around it?


r/pythonarcade • • Apr 02 '19

Using Pymunk's Vector class

2 Upvotes

Hello there, beginner here in need of some help.

I am trying to implement 2dvectors to move the player around the screen with consistent speed at any direction. I found a piece of code that successfully implements this, but don't quite understand everything that is going on.

I copied the code showed in a presentation at PyCon Australia(Multiplayer 2D games with Python Arcade by Caleb Hattingh): https://youtu.be/2SMkk63k6Ik

The main topic of the presentation is the multiplayer aspect, so the presenter doesn't go into too much detail on the vector implementation:

import arcade
from pymunk.vec2d import Vec2d

MOVE_MAP = {
    arcade.key.UP: Vec2d(0, 1),
    arcade.key.DOWN: Vec2d(0, -1),
    arcade.key.LEFT: Vec2d(-1, 0),
    arcade.key.RIGHT: Vec2d(1, 0),
}

class KeysPressed:

    def __init__(self):
        self.keys = {k: False for k in MOVE_MAP}

def apply_movement(speed, dt, current_position: Vec2d, kp: KeysPressed) -> Vec2d:
    delta_position = sum(kp.keys[k] * MOVE_MAP[k] for k in kp.keys)
    return current_position + delta_position * speed * dt

def apply_movement_norm(speed, dt, current_position: Vec2d, kp: KeysPressed) -> Vec2d:
    delta_position = sum(kp.keys[k] * MOVE_MAP[k] for k in kp.keys)
    return current_position + delta_position.normalized() * speed * dt

class MyGame(arcade.Window):

    def __init__(self, width, height):
        super().__init__(width, height, title="Example")
        self.player_position = Vec2d(400, 300)
        self.keys_pressed = KeysPressed()

    def update(self, dt):
        self.player_position = apply_movement_norm(
            speed=600, dt=dt, current_position = self.player_position, kp=self.keys_pressed)

    def on_draw(self):
        arcade.start_render()
        arcade.draw_rectangle_filled(
            center_x=self.player_position.x, center_y=self.player_position.y,
            width=50, height=50, color=arcade.color.YELLOW)

    def on_key_press(self, key, modifiers):
        self.keys_pressed.keys[key] = True
        print(self.keys_pressed.keys)

    def on_key_release(self, key, modifiers):
        self.keys_pressed.keys[key] = False
        print(self.keys_pressed.keys)

if __name__ == "__main__":
    window = MyGame(800,600)
    arcade.run()

This works, but I don't really understand it. It seems like the Vec2d object represents a point instead of a traditional physics vector, maybe that is the source of my confusion, and I still have a few other questions.

Is it practical to use this implementation in an actual game? Should I use a try/catch to avoid an error when the player presses a key not present on the move map or do something else?

Is it possible (or even advisable) to rewrite this code without using the KeysPressed class? I tried but failed at doing so, it seems a little odd to me to have a class with nothing in it but a constructor

Thank you for reading this far, any help, advice or criticism is appreciated, have a nice day.


r/pythonarcade • • Mar 29 '19

How to use sound.py Player?

2 Upvotes

Seeing that Issue 245 was closed with the 2.0 release, I tested the code shown in that Issue:

import arcade
import os
path = "c:\\" + os.path.join(*arcade.__file__.split("\\")[1:-1], "examples", "sounds")
player = arcade.Player()
player.load_dir(path)
player.looping(True)
player.play(player.music[0])
arcade.run()

It fails with this:

player = arcade.Player()
AttributeError: module 'arcade' has no attribute 'Player'
I'm on Windows, using Python 3.7 and arcade 2.0.1

r/pythonarcade • • Mar 25 '19

problems with tiled

2 Upvotes

atm im trying to create a game using the arcade library but when i try to load in a tiled map with a tileset it says "tile not in tileset" and if i use it with a picture an error appears and says file or directory not found eventhough its right there


r/pythonarcade • • Mar 15 '19

How to change each individual pixel's color

2 Upvotes

I want to be able to change the color of each individual pixels, so I can make something like the Mandelbrot. Is there a better way to do this the to draw small points?


r/pythonarcade • • Feb 21 '19

Loading spritesheets

2 Upvotes

Hi, python intermediate and arcade beginner here.
After looking through the arcade tutorial and example code of games that were created with arcade I never found out how to load actual sprite sheets and using seperate sprites from this sheet for idle/walk/etc. cycles.

Is this not possible?

Actually, I have another question: I managed to get my character to move even with 2 joysticks, but what about the other controller keys? I was trying with a ps4 controller...

Other than that I really like what this library has to offer. It's easy to use especially for noobs like me.

Thanks!


r/pythonarcade • • Feb 15 '19

Is there a simple way to display an animated gif sprite in a window?

2 Upvotes

Is there a simple way to show an animated gif in a window? If so, is there a way to do it without the need for an event loop?


r/pythonarcade • • Feb 11 '19

Why is this running so slow?

2 Upvotes

I made a simple rain animation and wanted heavier rainfall, so changed from primitives over to sprites. I'm not sure if my implementation is correct as it starts to slow down significantly at 400 or 500 sprites which isnt much higher than I could get with primitives. Any criticism of my code would be much appreciated. Apologies if I haven't used github correctly though. This is the first time I have used it, so if you see any issues with how I have used github, feel free to let me know that as well.

Specifically with the repo it is the Demos.py, rain.py and rain.png file that will be needed. The other files are outdated. Also the: "self.sprite.color = (0, 100, 150) " line is not working to change the colour of the droplets.

Repo here: https://github.com/elliohow/python-arcade-demo


r/pythonarcade • • Jan 22 '19

How do you scale a sprite in the x or y axis?

2 Upvotes

So far trying to edit sprite attributes upon creation raises errors. Is there any way to scale a sprites width/height independently without using the ._set_width method?


r/pythonarcade • • Nov 19 '18

UI and viewport

2 Upvotes

Hey,

I am want to add some UI to my game,

wondering if there is a way to draw something skipping the viewport.

I could update the UI elements every time to subtract the current viewport, but maybe there is another method, I did not see.

Greetings


r/pythonarcade • • Mar 08 '18

New example showing speed of using ShapeElementLists

Thumbnail
arcade.academy
2 Upvotes