1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
# Robot saving nature
import os
import sys
import time
import pygame
from pygame.locals import *
pygame.init()
# Screen size
window_h = 600
window_w = 800
screen = pygame.display.set_mode((window_w, window_h))
# Background image
object_background = pygame.image.load('images/park_2.png')
screen.blit(object_background, (0, 0))
# Normal speed
speed = 9
# Garbage image
#object_garbage = pygame.image.load('images/paper.png')
#position_garbage = [ 400, 300 ]
#screen.blit(object_garbage, position_garbage)
# Robot image
object_robot = pygame.image.load('images/robot_1.png')
position_robot = [0, window_h - object_robot.get_height()]
x_direction = 0
y_direction = 0
screen.blit(object_robot, position_robot)
# Initialize images
pygame.display.update()
position_garbage = [0,0]
start_time = time.time()
fps = 30
frame_time = 1.0/fps
# Main loop
exit = False
while not exit:
# Process pygame events
for event in pygame.event.get():
# Escape key to quit the game
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
exit = True
break
# Handle movement for the character
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_direction = -1
y_direction = 0
if event.key == pygame.K_RIGHT:
x_direction = 1
y_direction =0
if event.key == pygame.K_UP:
y_direction = -1
x_direction = 0
if event.key == pygame.K_DOWN:
y_direction = 1
x_direction = 0
# Uncomment this if you want the robot to stop when you release the keys
# if event.type == pygame.KEYUP:
# if (event.key == pygame.K_LEFT and x_direction == -1 and y_direction == 0) or\
# (event.key == pygame.K_RIGHT and x_direction == 1 and y_direction == 0) or\
# (event.key == pygame.K_UP and y_direction == -1 and x_direction == 0) or\
# (event.key == pygame.K_DOWN and y_direction == 1 and x_direction == 0):
# x_direction = 0
# y_direction = 0
if exit:
break
current_time = time.time()
if current_time - start_time <= frame_time:
continue
start_time = current_time
# draw the background first, because it will cover all the screen
screen.blit(object_background, (0,0))
# draw everything else over the background
screen.blit(object_robot, (position_robot[0], position_robot[1]))
# Move the character around the screen
position_robot = [((position_robot[0] + x_direction * speed )%window_w), ((position_robot[1] + y_direction * speed )%window_h) ]
pygame.display.update()
pygame.quit()
|