As you can tell I am very new to python...I stumbled upon pygame and it looked fun. So I started to build a game and I got stuck right away...Player controls. I would like the player to be able to contorl the person. Thank you.

import pygame, random
import random, os
import sys
from pygame.locals import *
import time

screen = pygame.display.set_mode((900, 50))
pygame.display.set_caption("game")
pygame.mouse.set_visible(True)
screen.fill((255,255,90))
img = pygame.image.load ('elder.jpg'). convert()
running = 1


while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = 0
    screen.blit(img, (0, 0))
    pygame.display.flip()

Recommended Answers

All 3 Replies

This should help ...

# pygame key events
# control a small moving circle with the arrow keys
# avoid crashing against the screen borders
# modified http://wordpress.com/tag/pygame-tutorial/

import pygame as pg

# r, g, b color values
white = 255, 255, 255
black = 0, 0, 0
blue = 0, 0, 255
yellow = 255, 255, 0

# window dimensions
width = 640
height = 400

# starting position at center
x = width // 2
y = height // 2

# direction of the circle move
dir_x = 0
dir_y = -1

screen = pg.display.set_mode((width, height))
s = "control the moving circle with arrow keys don't touch the wall"
pg.display.set_caption(s)

clock = pg.time.Clock()

running = True
while running:
    x += dir_x
    y += dir_y

    # when circle's center reaches the screen border exit
    if x <= 0 or x >= width or y <= 0 or y >= height:
        print( "Crash!!!" )
        running = False

    screen.fill(blue)
    # use a small circle to move
    pg.draw.circle(screen, yellow, (x, y), 20)

    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False

        # respond to arrow keys
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_UP:
                dir_x = 0
                dir_y = -1
            elif event.key == pg.K_DOWN:
                dir_x = 0
                dir_y = 1
            elif event.key == pg.K_LEFT:
                dir_x = -1
                dir_y = 0
            elif event.key == pg.K_RIGHT:
                dir_x = 1
                dir_y = 0

    pg.display.flip()
    # lower number means slower movement
    clock.tick(50)

Thank you but still confused I tried to insert the key events in my code but it doesn't work. Would you please insert the keys inside my code.?

Nevermind I have figured out thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.